repo
string
commit
string
message
string
diff
string
trek/red-sample-apps
8ae9ed9ece7e4c08f6bc0e1d464ad07ce50214d4
ready for screencast v1
diff --git a/facebook_photos/ajax/1.html b/facebook_photos/ajax/1.html index e69de29..ecb77cd 100644 --- a/facebook_photos/ajax/1.html +++ b/facebook_photos/ajax/1.html @@ -0,0 +1,17 @@ +<div class='photo'><div><img src='/images/tiny/j_01.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_02.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_03.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_04.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_05.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_06.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_07.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_08.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_09.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_10.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_11.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_12.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_13.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_14.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_15.jpg' /></div></div> diff --git a/facebook_photos/ajax/2.html b/facebook_photos/ajax/2.html index e69de29..73d2671 100644 --- a/facebook_photos/ajax/2.html +++ b/facebook_photos/ajax/2.html @@ -0,0 +1,17 @@ +<div class='photo'><div><img src='/images/tiny/j_16.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_17.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_18.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_19.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_20.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_21.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_22.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_23.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_24.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_25.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_26.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_27.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_28.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_29.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_30.jpg' /></div></div> diff --git a/facebook_photos/ajax/3.html b/facebook_photos/ajax/3.html index e69de29..02caeb0 100644 --- a/facebook_photos/ajax/3.html +++ b/facebook_photos/ajax/3.html @@ -0,0 +1,17 @@ +<div class='photo'><div><img src='/images/tiny/j_31.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_32.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_33.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_34.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_35.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_36.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_37.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_38.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_39.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_40.jpg' /></div></div> + +<div class='photo'><div><img src='/images/tiny/j_41.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_42.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_43.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_44.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_45.jpg' /></div></div> diff --git a/facebook_photos/ajax/4.html b/facebook_photos/ajax/4.html index b338aeb..6a07c94 100644 --- a/facebook_photos/ajax/4.html +++ b/facebook_photos/ajax/4.html @@ -1,5 +1,5 @@ -<div class='photo'><div></div></div> -<div class='photo'><div></div></div> -<div class='photo'><div></div></div> -<div class='photo'><div></div></div> -<div class='photo'><div></div></div> \ No newline at end of file +<div class='photo'><div><img src='/images/tiny/j_46.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_47.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_48.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_49.jpg' /></div></div> +<div class='photo'><div><img src='/images/tiny/j_50.jpg' /></div></div> \ No newline at end of file diff --git a/facebook_photos/images/tiny/j_01.jpg b/facebook_photos/images/tiny/j_01.jpg new file mode 100644 index 0000000..05ea012 Binary files /dev/null and b/facebook_photos/images/tiny/j_01.jpg differ diff --git a/facebook_photos/images/tiny/j_01_tn.jpg b/facebook_photos/images/tiny/j_01_tn.jpg deleted file mode 100644 index 5e76fd4..0000000 Binary files a/facebook_photos/images/tiny/j_01_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_02.jpg b/facebook_photos/images/tiny/j_02.jpg new file mode 100644 index 0000000..44020ba Binary files /dev/null and b/facebook_photos/images/tiny/j_02.jpg differ diff --git a/facebook_photos/images/tiny/j_02_tn.jpg b/facebook_photos/images/tiny/j_02_tn.jpg deleted file mode 100644 index a57d736..0000000 Binary files a/facebook_photos/images/tiny/j_02_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_03.jpg b/facebook_photos/images/tiny/j_03.jpg new file mode 100644 index 0000000..3ddcac5 Binary files /dev/null and b/facebook_photos/images/tiny/j_03.jpg differ diff --git a/facebook_photos/images/tiny/j_03_tn.jpg b/facebook_photos/images/tiny/j_03_tn.jpg deleted file mode 100644 index 24c1ef1..0000000 Binary files a/facebook_photos/images/tiny/j_03_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_04.jpg b/facebook_photos/images/tiny/j_04.jpg new file mode 100644 index 0000000..0adaaeb Binary files /dev/null and b/facebook_photos/images/tiny/j_04.jpg differ diff --git a/facebook_photos/images/tiny/j_04_tn.jpg b/facebook_photos/images/tiny/j_04_tn.jpg deleted file mode 100644 index bbc7474..0000000 Binary files a/facebook_photos/images/tiny/j_04_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_05.jpg b/facebook_photos/images/tiny/j_05.jpg new file mode 100644 index 0000000..ef982ee Binary files /dev/null and b/facebook_photos/images/tiny/j_05.jpg differ diff --git a/facebook_photos/images/tiny/j_05_tn.jpg b/facebook_photos/images/tiny/j_05_tn.jpg deleted file mode 100644 index f0cfe2d..0000000 Binary files a/facebook_photos/images/tiny/j_05_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_06.jpg b/facebook_photos/images/tiny/j_06.jpg new file mode 100644 index 0000000..bb93281 Binary files /dev/null and b/facebook_photos/images/tiny/j_06.jpg differ diff --git a/facebook_photos/images/tiny/j_06_tn.jpg b/facebook_photos/images/tiny/j_06_tn.jpg deleted file mode 100644 index 6395e7e..0000000 Binary files a/facebook_photos/images/tiny/j_06_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_07.jpg b/facebook_photos/images/tiny/j_07.jpg new file mode 100644 index 0000000..a4935c2 Binary files /dev/null and b/facebook_photos/images/tiny/j_07.jpg differ diff --git a/facebook_photos/images/tiny/j_07_tn.jpg b/facebook_photos/images/tiny/j_07_tn.jpg deleted file mode 100644 index 6889091..0000000 Binary files a/facebook_photos/images/tiny/j_07_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_08.jpg b/facebook_photos/images/tiny/j_08.jpg new file mode 100644 index 0000000..32a1aa8 Binary files /dev/null and b/facebook_photos/images/tiny/j_08.jpg differ diff --git a/facebook_photos/images/tiny/j_08_tn.jpg b/facebook_photos/images/tiny/j_08_tn.jpg deleted file mode 100644 index 6b50505..0000000 Binary files a/facebook_photos/images/tiny/j_08_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_09.jpg b/facebook_photos/images/tiny/j_09.jpg new file mode 100644 index 0000000..16f1a4d Binary files /dev/null and b/facebook_photos/images/tiny/j_09.jpg differ diff --git a/facebook_photos/images/tiny/j_09_tn.jpg b/facebook_photos/images/tiny/j_09_tn.jpg deleted file mode 100644 index eb74048..0000000 Binary files a/facebook_photos/images/tiny/j_09_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_10.jpg b/facebook_photos/images/tiny/j_10.jpg new file mode 100644 index 0000000..df2814c Binary files /dev/null and b/facebook_photos/images/tiny/j_10.jpg differ diff --git a/facebook_photos/images/tiny/j_10_tn.jpg b/facebook_photos/images/tiny/j_10_tn.jpg deleted file mode 100644 index 000cb1d..0000000 Binary files a/facebook_photos/images/tiny/j_10_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_11.jpg b/facebook_photos/images/tiny/j_11.jpg new file mode 100644 index 0000000..0157fbf Binary files /dev/null and b/facebook_photos/images/tiny/j_11.jpg differ diff --git a/facebook_photos/images/tiny/j_11_tn.jpg b/facebook_photos/images/tiny/j_11_tn.jpg deleted file mode 100644 index 366b6fb..0000000 Binary files a/facebook_photos/images/tiny/j_11_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_12.jpg b/facebook_photos/images/tiny/j_12.jpg new file mode 100644 index 0000000..e20b80f Binary files /dev/null and b/facebook_photos/images/tiny/j_12.jpg differ diff --git a/facebook_photos/images/tiny/j_12_tn.jpg b/facebook_photos/images/tiny/j_12_tn.jpg deleted file mode 100644 index 4b95dd5..0000000 Binary files a/facebook_photos/images/tiny/j_12_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_13.jpg b/facebook_photos/images/tiny/j_13.jpg new file mode 100644 index 0000000..7026168 Binary files /dev/null and b/facebook_photos/images/tiny/j_13.jpg differ diff --git a/facebook_photos/images/tiny/j_13_tn.jpg b/facebook_photos/images/tiny/j_13_tn.jpg deleted file mode 100644 index f622686..0000000 Binary files a/facebook_photos/images/tiny/j_13_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_14.jpg b/facebook_photos/images/tiny/j_14.jpg new file mode 100644 index 0000000..978cea4 Binary files /dev/null and b/facebook_photos/images/tiny/j_14.jpg differ diff --git a/facebook_photos/images/tiny/j_14_tn.jpg b/facebook_photos/images/tiny/j_14_tn.jpg deleted file mode 100644 index ce078c6..0000000 Binary files a/facebook_photos/images/tiny/j_14_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_15.jpg b/facebook_photos/images/tiny/j_15.jpg new file mode 100644 index 0000000..6a273ce Binary files /dev/null and b/facebook_photos/images/tiny/j_15.jpg differ diff --git a/facebook_photos/images/tiny/j_15_tn.jpg b/facebook_photos/images/tiny/j_15_tn.jpg deleted file mode 100644 index 7e4e6da..0000000 Binary files a/facebook_photos/images/tiny/j_15_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_16.jpg b/facebook_photos/images/tiny/j_16.jpg new file mode 100644 index 0000000..a82e84a Binary files /dev/null and b/facebook_photos/images/tiny/j_16.jpg differ diff --git a/facebook_photos/images/tiny/j_16_tn.jpg b/facebook_photos/images/tiny/j_16_tn.jpg deleted file mode 100644 index 8343e4a..0000000 Binary files a/facebook_photos/images/tiny/j_16_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_17.jpg b/facebook_photos/images/tiny/j_17.jpg new file mode 100644 index 0000000..567acab Binary files /dev/null and b/facebook_photos/images/tiny/j_17.jpg differ diff --git a/facebook_photos/images/tiny/j_17_tn.jpg b/facebook_photos/images/tiny/j_17_tn.jpg deleted file mode 100644 index 012c7dc..0000000 Binary files a/facebook_photos/images/tiny/j_17_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_18.jpg b/facebook_photos/images/tiny/j_18.jpg new file mode 100644 index 0000000..4f2934c Binary files /dev/null and b/facebook_photos/images/tiny/j_18.jpg differ diff --git a/facebook_photos/images/tiny/j_18_tn.jpg b/facebook_photos/images/tiny/j_18_tn.jpg deleted file mode 100644 index 4e3cff3..0000000 Binary files a/facebook_photos/images/tiny/j_18_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_19.jpg b/facebook_photos/images/tiny/j_19.jpg new file mode 100644 index 0000000..9473581 Binary files /dev/null and b/facebook_photos/images/tiny/j_19.jpg differ diff --git a/facebook_photos/images/tiny/j_19_tn.jpg b/facebook_photos/images/tiny/j_19_tn.jpg deleted file mode 100644 index 1ba4377..0000000 Binary files a/facebook_photos/images/tiny/j_19_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_20.jpg b/facebook_photos/images/tiny/j_20.jpg new file mode 100644 index 0000000..6d58ebe Binary files /dev/null and b/facebook_photos/images/tiny/j_20.jpg differ diff --git a/facebook_photos/images/tiny/j_20_tn.jpg b/facebook_photos/images/tiny/j_20_tn.jpg deleted file mode 100644 index 318ae76..0000000 Binary files a/facebook_photos/images/tiny/j_20_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_21.jpg b/facebook_photos/images/tiny/j_21.jpg new file mode 100644 index 0000000..da91c74 Binary files /dev/null and b/facebook_photos/images/tiny/j_21.jpg differ diff --git a/facebook_photos/images/tiny/j_21_tn.jpg b/facebook_photos/images/tiny/j_21_tn.jpg deleted file mode 100644 index f02e913..0000000 Binary files a/facebook_photos/images/tiny/j_21_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_22.jpg b/facebook_photos/images/tiny/j_22.jpg new file mode 100644 index 0000000..49f9bbc Binary files /dev/null and b/facebook_photos/images/tiny/j_22.jpg differ diff --git a/facebook_photos/images/tiny/j_22_tn.jpg b/facebook_photos/images/tiny/j_22_tn.jpg deleted file mode 100644 index c6f11a9..0000000 Binary files a/facebook_photos/images/tiny/j_22_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_23.jpg b/facebook_photos/images/tiny/j_23.jpg new file mode 100644 index 0000000..a122044 Binary files /dev/null and b/facebook_photos/images/tiny/j_23.jpg differ diff --git a/facebook_photos/images/tiny/j_23_tn.jpg b/facebook_photos/images/tiny/j_23_tn.jpg deleted file mode 100644 index dcd441e..0000000 Binary files a/facebook_photos/images/tiny/j_23_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_24.jpg b/facebook_photos/images/tiny/j_24.jpg new file mode 100644 index 0000000..f6a788d Binary files /dev/null and b/facebook_photos/images/tiny/j_24.jpg differ diff --git a/facebook_photos/images/tiny/j_24_tn.jpg b/facebook_photos/images/tiny/j_24_tn.jpg deleted file mode 100644 index 020adb3..0000000 Binary files a/facebook_photos/images/tiny/j_24_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_25.jpg b/facebook_photos/images/tiny/j_25.jpg new file mode 100644 index 0000000..8aaa35b Binary files /dev/null and b/facebook_photos/images/tiny/j_25.jpg differ diff --git a/facebook_photos/images/tiny/j_25_tn.jpg b/facebook_photos/images/tiny/j_25_tn.jpg deleted file mode 100644 index e4370e4..0000000 Binary files a/facebook_photos/images/tiny/j_25_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_26.jpg b/facebook_photos/images/tiny/j_26.jpg new file mode 100644 index 0000000..fb82722 Binary files /dev/null and b/facebook_photos/images/tiny/j_26.jpg differ diff --git a/facebook_photos/images/tiny/j_26_tn.jpg b/facebook_photos/images/tiny/j_26_tn.jpg deleted file mode 100644 index ba109b3..0000000 Binary files a/facebook_photos/images/tiny/j_26_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_27.jpg b/facebook_photos/images/tiny/j_27.jpg new file mode 100644 index 0000000..c8a6bf2 Binary files /dev/null and b/facebook_photos/images/tiny/j_27.jpg differ diff --git a/facebook_photos/images/tiny/j_27_tn.jpg b/facebook_photos/images/tiny/j_27_tn.jpg deleted file mode 100644 index cadbf7b..0000000 Binary files a/facebook_photos/images/tiny/j_27_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_28.jpg b/facebook_photos/images/tiny/j_28.jpg new file mode 100644 index 0000000..d402db3 Binary files /dev/null and b/facebook_photos/images/tiny/j_28.jpg differ diff --git a/facebook_photos/images/tiny/j_28_tn.jpg b/facebook_photos/images/tiny/j_28_tn.jpg deleted file mode 100644 index 6d36eaa..0000000 Binary files a/facebook_photos/images/tiny/j_28_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_29.jpg b/facebook_photos/images/tiny/j_29.jpg new file mode 100644 index 0000000..ced73bf Binary files /dev/null and b/facebook_photos/images/tiny/j_29.jpg differ diff --git a/facebook_photos/images/tiny/j_29_tn.jpg b/facebook_photos/images/tiny/j_29_tn.jpg deleted file mode 100644 index 6776bf3..0000000 Binary files a/facebook_photos/images/tiny/j_29_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_30.jpg b/facebook_photos/images/tiny/j_30.jpg new file mode 100644 index 0000000..43345a0 Binary files /dev/null and b/facebook_photos/images/tiny/j_30.jpg differ diff --git a/facebook_photos/images/tiny/j_30_tn.jpg b/facebook_photos/images/tiny/j_30_tn.jpg deleted file mode 100644 index eced3b1..0000000 Binary files a/facebook_photos/images/tiny/j_30_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_31.jpg b/facebook_photos/images/tiny/j_31.jpg new file mode 100644 index 0000000..9178987 Binary files /dev/null and b/facebook_photos/images/tiny/j_31.jpg differ diff --git a/facebook_photos/images/tiny/j_31_tn.jpg b/facebook_photos/images/tiny/j_31_tn.jpg deleted file mode 100644 index 73924bf..0000000 Binary files a/facebook_photos/images/tiny/j_31_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_32.jpg b/facebook_photos/images/tiny/j_32.jpg new file mode 100644 index 0000000..49d6948 Binary files /dev/null and b/facebook_photos/images/tiny/j_32.jpg differ diff --git a/facebook_photos/images/tiny/j_32_tn.jpg b/facebook_photos/images/tiny/j_32_tn.jpg deleted file mode 100644 index ef547cb..0000000 Binary files a/facebook_photos/images/tiny/j_32_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_33.jpg b/facebook_photos/images/tiny/j_33.jpg new file mode 100644 index 0000000..2903d58 Binary files /dev/null and b/facebook_photos/images/tiny/j_33.jpg differ diff --git a/facebook_photos/images/tiny/j_33_tn.jpg b/facebook_photos/images/tiny/j_33_tn.jpg deleted file mode 100644 index b23ac22..0000000 Binary files a/facebook_photos/images/tiny/j_33_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_34.jpg b/facebook_photos/images/tiny/j_34.jpg new file mode 100644 index 0000000..766067c Binary files /dev/null and b/facebook_photos/images/tiny/j_34.jpg differ diff --git a/facebook_photos/images/tiny/j_34_tn.jpg b/facebook_photos/images/tiny/j_34_tn.jpg deleted file mode 100644 index ecfb60b..0000000 Binary files a/facebook_photos/images/tiny/j_34_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_35.jpg b/facebook_photos/images/tiny/j_35.jpg new file mode 100644 index 0000000..d6ea245 Binary files /dev/null and b/facebook_photos/images/tiny/j_35.jpg differ diff --git a/facebook_photos/images/tiny/j_35_tn.jpg b/facebook_photos/images/tiny/j_35_tn.jpg deleted file mode 100644 index 437898c..0000000 Binary files a/facebook_photos/images/tiny/j_35_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_36.jpg b/facebook_photos/images/tiny/j_36.jpg new file mode 100644 index 0000000..9daefcc Binary files /dev/null and b/facebook_photos/images/tiny/j_36.jpg differ diff --git a/facebook_photos/images/tiny/j_36_tn.jpg b/facebook_photos/images/tiny/j_36_tn.jpg deleted file mode 100644 index 95f750c..0000000 Binary files a/facebook_photos/images/tiny/j_36_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_37.jpg b/facebook_photos/images/tiny/j_37.jpg new file mode 100644 index 0000000..d326587 Binary files /dev/null and b/facebook_photos/images/tiny/j_37.jpg differ diff --git a/facebook_photos/images/tiny/j_37_tn.jpg b/facebook_photos/images/tiny/j_37_tn.jpg deleted file mode 100644 index 33f9d07..0000000 Binary files a/facebook_photos/images/tiny/j_37_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_38.jpg b/facebook_photos/images/tiny/j_38.jpg new file mode 100644 index 0000000..6462433 Binary files /dev/null and b/facebook_photos/images/tiny/j_38.jpg differ diff --git a/facebook_photos/images/tiny/j_38_tn.jpg b/facebook_photos/images/tiny/j_38_tn.jpg deleted file mode 100644 index 4df2c73..0000000 Binary files a/facebook_photos/images/tiny/j_38_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_39.jpg b/facebook_photos/images/tiny/j_39.jpg new file mode 100644 index 0000000..bf19438 Binary files /dev/null and b/facebook_photos/images/tiny/j_39.jpg differ diff --git a/facebook_photos/images/tiny/j_39_tn.jpg b/facebook_photos/images/tiny/j_39_tn.jpg deleted file mode 100644 index 5f9b7f3..0000000 Binary files a/facebook_photos/images/tiny/j_39_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_40.jpg b/facebook_photos/images/tiny/j_40.jpg new file mode 100644 index 0000000..30d0f78 Binary files /dev/null and b/facebook_photos/images/tiny/j_40.jpg differ diff --git a/facebook_photos/images/tiny/j_40_tn.jpg b/facebook_photos/images/tiny/j_40_tn.jpg deleted file mode 100644 index e566a46..0000000 Binary files a/facebook_photos/images/tiny/j_40_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_41.jpg b/facebook_photos/images/tiny/j_41.jpg new file mode 100644 index 0000000..e28dbf7 Binary files /dev/null and b/facebook_photos/images/tiny/j_41.jpg differ diff --git a/facebook_photos/images/tiny/j_41_tn.jpg b/facebook_photos/images/tiny/j_41_tn.jpg deleted file mode 100644 index 15720f2..0000000 Binary files a/facebook_photos/images/tiny/j_41_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_42.jpg b/facebook_photos/images/tiny/j_42.jpg new file mode 100644 index 0000000..3fdb40e Binary files /dev/null and b/facebook_photos/images/tiny/j_42.jpg differ diff --git a/facebook_photos/images/tiny/j_42_tn.jpg b/facebook_photos/images/tiny/j_42_tn.jpg deleted file mode 100644 index b24f104..0000000 Binary files a/facebook_photos/images/tiny/j_42_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_43.jpg b/facebook_photos/images/tiny/j_43.jpg new file mode 100644 index 0000000..ff31389 Binary files /dev/null and b/facebook_photos/images/tiny/j_43.jpg differ diff --git a/facebook_photos/images/tiny/j_43_tn.jpg b/facebook_photos/images/tiny/j_43_tn.jpg deleted file mode 100644 index 64dfd3d..0000000 Binary files a/facebook_photos/images/tiny/j_43_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_44.jpg b/facebook_photos/images/tiny/j_44.jpg new file mode 100644 index 0000000..06804d7 Binary files /dev/null and b/facebook_photos/images/tiny/j_44.jpg differ diff --git a/facebook_photos/images/tiny/j_44_tn.jpg b/facebook_photos/images/tiny/j_44_tn.jpg deleted file mode 100644 index 268b0a9..0000000 Binary files a/facebook_photos/images/tiny/j_44_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_45.jpg b/facebook_photos/images/tiny/j_45.jpg new file mode 100644 index 0000000..234e378 Binary files /dev/null and b/facebook_photos/images/tiny/j_45.jpg differ diff --git a/facebook_photos/images/tiny/j_45_tn.jpg b/facebook_photos/images/tiny/j_45_tn.jpg deleted file mode 100644 index b775ab3..0000000 Binary files a/facebook_photos/images/tiny/j_45_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_46.jpg b/facebook_photos/images/tiny/j_46.jpg new file mode 100644 index 0000000..72924c6 Binary files /dev/null and b/facebook_photos/images/tiny/j_46.jpg differ diff --git a/facebook_photos/images/tiny/j_46_tn.jpg b/facebook_photos/images/tiny/j_46_tn.jpg deleted file mode 100644 index 1ca50f4..0000000 Binary files a/facebook_photos/images/tiny/j_46_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_47.jpg b/facebook_photos/images/tiny/j_47.jpg new file mode 100644 index 0000000..cf7cd97 Binary files /dev/null and b/facebook_photos/images/tiny/j_47.jpg differ diff --git a/facebook_photos/images/tiny/j_47_tn.jpg b/facebook_photos/images/tiny/j_47_tn.jpg deleted file mode 100644 index 172fa70..0000000 Binary files a/facebook_photos/images/tiny/j_47_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_48.jpg b/facebook_photos/images/tiny/j_48.jpg new file mode 100644 index 0000000..9c65558 Binary files /dev/null and b/facebook_photos/images/tiny/j_48.jpg differ diff --git a/facebook_photos/images/tiny/j_48_tn.jpg b/facebook_photos/images/tiny/j_48_tn.jpg deleted file mode 100644 index aa3125e..0000000 Binary files a/facebook_photos/images/tiny/j_48_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_49.jpg b/facebook_photos/images/tiny/j_49.jpg new file mode 100644 index 0000000..6e56fef Binary files /dev/null and b/facebook_photos/images/tiny/j_49.jpg differ diff --git a/facebook_photos/images/tiny/j_49_tn.jpg b/facebook_photos/images/tiny/j_49_tn.jpg deleted file mode 100644 index 67e3ee3..0000000 Binary files a/facebook_photos/images/tiny/j_49_tn.jpg and /dev/null differ diff --git a/facebook_photos/images/tiny/j_50.jpg b/facebook_photos/images/tiny/j_50.jpg new file mode 100644 index 0000000..88c44b1 Binary files /dev/null and b/facebook_photos/images/tiny/j_50.jpg differ diff --git a/facebook_photos/images/tiny/j_50_tn.jpg b/facebook_photos/images/tiny/j_50_tn.jpg deleted file mode 100644 index 5bb2a3f..0000000 Binary files a/facebook_photos/images/tiny/j_50_tn.jpg and /dev/null differ diff --git a/facebook_photos/index.html b/facebook_photos/index.html index f7e99e4..567f90d 100644 --- a/facebook_photos/index.html +++ b/facebook_photos/index.html @@ -1,30 +1,30 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>facebook images</title> <link rel="stylesheet" href="stylesheets/fb.css" type="text/css" media="screen" charset="utf-8"> <script type="text/javascript" charset="utf-8" src='/javascripts/application.red'></script> </head> <body> <div class='photo_wrapper'> <div class='info clearfix'> <div class='about'> <h3>Photos of Jason <span>50 photos</span></h3> </div> <div class='pagination'> - <ul> - <li class='current'><a href='1.html'>1</a></li> - <li><a href='2.html'>2</a></li> - <li><a href='3.html'>3</a></li> - <li><a href='2.html'>Next</a></li> + <ul class='pages'> + <li class='current'><a href='/ajax/1.html'>1</a></li> + <li><a href='/ajax/2.html'>2</a></li> + <li><a href='/ajax/3.html'>3</a></li> + <li><a href='/ajax/4.html'>4</a></li> </ul> </div> </div> <div class='photo_table'> <div id='loading'><img src="/images/indicator_blue_large.gif" width="32" height="32" alt="Indicator Blue Large"/></div> </div> </div> </body> </html> \ No newline at end of file diff --git a/facebook_photos/javascripts/application.red b/facebook_photos/javascripts/application.red index 6816313..97c268a 100644 --- a/facebook_photos/javascripts/application.red +++ b/facebook_photos/javascripts/application.red @@ -1,39 +1,65 @@ -require '../redshift/redshift' +require '../redshift/redshift.red' + class PhotoBucket def initialize(element) @element = element + @loader = @element['#loading'] @photo_container = element['.photo_table'].first @req = Request.new - c = self - @req.upon(:request) { c.show_loader } - @req.upon(:success) { c.hide_loader } - @req.upon(:response) {|response| c.load_photos(response) } + @req.upon(:request) { self.show_loader } + @req.upon(:success) { self.hide_loader } + @req.upon(:response) {|response| self.load_photos(response) } + + @element.listen(:click) { |element,event| self.clicked(element,event)} self.load_initial_photos end def load_initial_photos @req.execute({:url => '/ajax/1.html'}) end def hide_loader - @element['#loading'].styles[:display] = 'none' + @loader.styles[:display] = 'none' end def show_loader - @element['#loading'].styles[:display] = 'block' + @loader.styles[:display] = 'block' end def load_photos(response) - puts response @photo_container.empty! - @photo_container.insert(response[:text]) + @photo_container.html = response.text + end + + def show_photo(location) + a = location.properties[:src].split('/') + a[2] = 'full' + a = a.join('/') + @photo_container.empty! + @photo_container.insert(Element.new('div', {:class => 'full photo'}).insert(Element.new('img', {:src => a}))) + end + + def page_to(location) + @req.execute({:url => location.properties[:href]}) + @element['.pagination .current'].first.remove_class('current') + location.parent.add_class('current') + end + + def clicked(element,event) + event.kill! + container = event.target.parent.parent + if(container.has_class?('pages')) + self.page_to(event.target) + elsif(container.has_class?('photo')) + self.show_photo(event.target) + end end end Document.ready? do Document['.photo_wrapper'].each do |e| PhotoBucket.new(e) end end \ No newline at end of file diff --git a/facebook_photos/stylesheets/fb.css b/facebook_photos/stylesheets/fb.css index d9eb72f..8cd18b7 100644 --- a/facebook_photos/stylesheets/fb.css +++ b/facebook_photos/stylesheets/fb.css @@ -1,94 +1,120 @@ body { font-family:"lucida grande",tahoma,verdana,arial,sans-serif; font-size:11px; text-align:left; } h3 { margin:0; padding:0; padding-left:12px; color:#333333; font-size:13px; } h3 span { color:#6F6F6F; font-size:11px; font-weight:normal; padding:3px 3px 2px; } .info { margin:0; padding:0; width:100%; } .about { float:left; width:49%; } .pagination { float:right; width:50%; font-size:11px; } .pagination ul { padding:0; margin:0; float:right; list-style-image:none; list-style-position:outside; list-style-type:none; } .pagination li { display:inline; float:left; } .pagination a { display:block; border-bottom:2px solid #fff; padding:3px 3px 2px; color:#3B5998; cursor:pointer; outline-style:none; text-decoration:none; } .pagination .current a { border-bottom:2px solid #3B5998; padding-left:2px; padding-right:2px; } .pagination a:hover { background:#3B5998 none repeat scroll 0 0; border-bottom:1px solid #3B5998; border-color:#D8DFEA #D8DFEA #3B5998; color:#FFFFFF; text-decoration:none; } .photo_wrapper { width:750px; } .photo_table { background:#F7F7F7 none repeat scroll 0 0; border:1px solid #BBBBBB; margin:0 0 20px; overflow:hidden; padding:0; position:relative; + padding:0 0 0 12px; width:750px; - height:461px; } + +.photo_table div.photo { + float:left; + width:148px; + height:149px; + padding:10px 0; +} + +.photo_table div.photo { + text-align: center; +} + +.photo_table div.photo.full { + width:100%; + height:100%; + float:left; + padding:10px 0; +} + +.photo_table div.photo img{ + border:1px solid #3B5998; + padding: 4px; + background-color: #fff; +} + #loading { margin:0 auto; margin-top:25%; width:20px; + z-index:2; } .clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix { display: inline-block; }
trek/red-sample-apps
e86d7e01995b4cc32e28e22abc0ba8d754862229
added fourth ajax page
diff --git a/facebook_photos/ajax/4.html b/facebook_photos/ajax/4.html new file mode 100644 index 0000000..b338aeb --- /dev/null +++ b/facebook_photos/ajax/4.html @@ -0,0 +1,5 @@ +<div class='photo'><div></div></div> +<div class='photo'><div></div></div> +<div class='photo'><div></div></div> +<div class='photo'><div></div></div> +<div class='photo'><div></div></div> \ No newline at end of file
trek/red-sample-apps
918df49966eaa789000948698bdd50d37e31012d
naming scheme for photos, thumbnail added
diff --git a/facebook_photos/images/full/n2203865_44699938_683.jpg b/facebook_photos/images/full/j_01.jpg similarity index 100% rename from facebook_photos/images/full/n2203865_44699938_683.jpg rename to facebook_photos/images/full/j_01.jpg diff --git a/facebook_photos/images/full/n2210434_36361375_607.jpg b/facebook_photos/images/full/j_02.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_36361375_607.jpg rename to facebook_photos/images/full/j_02.jpg diff --git a/facebook_photos/images/full/n2210434_38361011_4955.jpg b/facebook_photos/images/full/j_03.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_38361011_4955.jpg rename to facebook_photos/images/full/j_03.jpg diff --git a/facebook_photos/images/full/n2210434_41501426_6677.jpg b/facebook_photos/images/full/j_04.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501426_6677.jpg rename to facebook_photos/images/full/j_04.jpg diff --git a/facebook_photos/images/full/n2210434_41501427_9275.jpg b/facebook_photos/images/full/j_05.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501427_9275.jpg rename to facebook_photos/images/full/j_05.jpg diff --git a/facebook_photos/images/full/n2210434_41501429_4021.jpg b/facebook_photos/images/full/j_06.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501429_4021.jpg rename to facebook_photos/images/full/j_06.jpg diff --git a/facebook_photos/images/full/n2210434_41501430_6077.jpg b/facebook_photos/images/full/j_07.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501430_6077.jpg rename to facebook_photos/images/full/j_07.jpg diff --git a/facebook_photos/images/full/n2210434_41501431_8794.jpg b/facebook_photos/images/full/j_08.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501431_8794.jpg rename to facebook_photos/images/full/j_08.jpg diff --git a/facebook_photos/images/full/n2210434_41501435_7215.jpg b/facebook_photos/images/full/j_09.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501435_7215.jpg rename to facebook_photos/images/full/j_09.jpg diff --git a/facebook_photos/images/full/n2210434_41501436_9498.jpg b/facebook_photos/images/full/j_10.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501436_9498.jpg rename to facebook_photos/images/full/j_10.jpg diff --git a/facebook_photos/images/full/n2210434_41501464_6598.jpg b/facebook_photos/images/full/j_11.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501464_6598.jpg rename to facebook_photos/images/full/j_11.jpg diff --git a/facebook_photos/images/full/n2210434_41501465_8969.jpg b/facebook_photos/images/full/j_12.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501465_8969.jpg rename to facebook_photos/images/full/j_12.jpg diff --git a/facebook_photos/images/full/n2210434_41501474_8874.jpg b/facebook_photos/images/full/j_13.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41501474_8874.jpg rename to facebook_photos/images/full/j_13.jpg diff --git a/facebook_photos/images/full/n2210434_41502802_8983.jpg b/facebook_photos/images/full/j_14.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41502802_8983.jpg rename to facebook_photos/images/full/j_14.jpg diff --git a/facebook_photos/images/full/n2210434_41966118_9749.jpg b/facebook_photos/images/full/j_15.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_41966118_9749.jpg rename to facebook_photos/images/full/j_15.jpg diff --git a/facebook_photos/images/full/n2210434_42069245_8853.jpg b/facebook_photos/images/full/j_16.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42069245_8853.jpg rename to facebook_photos/images/full/j_16.jpg diff --git a/facebook_photos/images/full/n2210434_42069246_3637.jpg b/facebook_photos/images/full/j_17.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42069246_3637.jpg rename to facebook_photos/images/full/j_17.jpg diff --git a/facebook_photos/images/full/n2210434_42090638_512.jpg b/facebook_photos/images/full/j_18.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090638_512.jpg rename to facebook_photos/images/full/j_18.jpg diff --git a/facebook_photos/images/full/n2210434_42090639_4578.jpg b/facebook_photos/images/full/j_19.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090639_4578.jpg rename to facebook_photos/images/full/j_19.jpg diff --git a/facebook_photos/images/full/n2210434_42090640_7719.jpg b/facebook_photos/images/full/j_20.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090640_7719.jpg rename to facebook_photos/images/full/j_20.jpg diff --git a/facebook_photos/images/full/n2210434_42090641_758.jpg b/facebook_photos/images/full/j_21.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090641_758.jpg rename to facebook_photos/images/full/j_21.jpg diff --git a/facebook_photos/images/full/n2210434_42090647_1079.jpg b/facebook_photos/images/full/j_22.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090647_1079.jpg rename to facebook_photos/images/full/j_22.jpg diff --git a/facebook_photos/images/full/n2210434_42090655_9588.jpg b/facebook_photos/images/full/j_23.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090655_9588.jpg rename to facebook_photos/images/full/j_23.jpg diff --git a/facebook_photos/images/full/n2210434_42090671_6824.jpg b/facebook_photos/images/full/j_24.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42090671_6824.jpg rename to facebook_photos/images/full/j_24.jpg diff --git a/facebook_photos/images/full/n2210434_42161616_3183.jpg b/facebook_photos/images/full/j_25.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42161616_3183.jpg rename to facebook_photos/images/full/j_25.jpg diff --git a/facebook_photos/images/full/n2210434_42416842_238.jpg b/facebook_photos/images/full/j_26.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42416842_238.jpg rename to facebook_photos/images/full/j_26.jpg diff --git a/facebook_photos/images/full/n2210434_42627691_7453.jpg b/facebook_photos/images/full/j_27.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627691_7453.jpg rename to facebook_photos/images/full/j_27.jpg diff --git a/facebook_photos/images/full/n2210434_42627692_7487.jpg b/facebook_photos/images/full/j_28.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627692_7487.jpg rename to facebook_photos/images/full/j_28.jpg diff --git a/facebook_photos/images/full/n2210434_42627698_1034.jpg b/facebook_photos/images/full/j_29.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627698_1034.jpg rename to facebook_photos/images/full/j_29.jpg diff --git a/facebook_photos/images/full/n2210434_42627718_9316.jpg b/facebook_photos/images/full/j_30.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627718_9316.jpg rename to facebook_photos/images/full/j_30.jpg diff --git a/facebook_photos/images/full/n2210434_42627720_5029.jpg b/facebook_photos/images/full/j_31.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627720_5029.jpg rename to facebook_photos/images/full/j_31.jpg diff --git a/facebook_photos/images/full/n2210434_42627722_9448.jpg b/facebook_photos/images/full/j_32.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627722_9448.jpg rename to facebook_photos/images/full/j_32.jpg diff --git a/facebook_photos/images/full/n2210434_42627723_6444.jpg b/facebook_photos/images/full/j_33.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627723_6444.jpg rename to facebook_photos/images/full/j_33.jpg diff --git a/facebook_photos/images/full/n2210434_42627741_6066.jpg b/facebook_photos/images/full/j_34.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627741_6066.jpg rename to facebook_photos/images/full/j_34.jpg diff --git a/facebook_photos/images/full/n2210434_42627746_2515.jpg b/facebook_photos/images/full/j_35.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627746_2515.jpg rename to facebook_photos/images/full/j_35.jpg diff --git a/facebook_photos/images/full/n2210434_42627755_6759.jpg b/facebook_photos/images/full/j_36.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627755_6759.jpg rename to facebook_photos/images/full/j_36.jpg diff --git a/facebook_photos/images/full/n2210434_42627938_7785.jpg b/facebook_photos/images/full/j_37.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_42627938_7785.jpg rename to facebook_photos/images/full/j_37.jpg diff --git a/facebook_photos/images/full/n2210434_44563405_9172.jpg b/facebook_photos/images/full/j_38.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563405_9172.jpg rename to facebook_photos/images/full/j_38.jpg diff --git a/facebook_photos/images/full/n2210434_44563407_2119.jpg b/facebook_photos/images/full/j_39.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563407_2119.jpg rename to facebook_photos/images/full/j_39.jpg diff --git a/facebook_photos/images/full/n2210434_44563408_4988.jpg b/facebook_photos/images/full/j_40.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563408_4988.jpg rename to facebook_photos/images/full/j_40.jpg diff --git a/facebook_photos/images/full/n2210434_44563409_7746.jpg b/facebook_photos/images/full/j_41.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563409_7746.jpg rename to facebook_photos/images/full/j_41.jpg diff --git a/facebook_photos/images/full/n2210434_44563419_6601.jpg b/facebook_photos/images/full/j_42.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563419_6601.jpg rename to facebook_photos/images/full/j_42.jpg diff --git a/facebook_photos/images/full/n2210434_44563421_9241.jpg b/facebook_photos/images/full/j_43.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563421_9241.jpg rename to facebook_photos/images/full/j_43.jpg diff --git a/facebook_photos/images/full/n2210434_44563423_4953.jpg b/facebook_photos/images/full/j_44.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563423_4953.jpg rename to facebook_photos/images/full/j_44.jpg diff --git a/facebook_photos/images/full/n2210434_44563424_7730.jpg b/facebook_photos/images/full/j_45.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563424_7730.jpg rename to facebook_photos/images/full/j_45.jpg diff --git a/facebook_photos/images/full/n2210434_44563425_487.jpg b/facebook_photos/images/full/j_46.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563425_487.jpg rename to facebook_photos/images/full/j_46.jpg diff --git a/facebook_photos/images/full/n2210434_44563426_3136.jpg b/facebook_photos/images/full/j_47.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563426_3136.jpg rename to facebook_photos/images/full/j_47.jpg diff --git a/facebook_photos/images/full/n2210434_44563428_8573.jpg b/facebook_photos/images/full/j_48.jpg similarity index 100% rename from facebook_photos/images/full/n2210434_44563428_8573.jpg rename to facebook_photos/images/full/j_48.jpg diff --git a/facebook_photos/images/full/n2306318_48612987_9521.jpg b/facebook_photos/images/full/j_49.jpg similarity index 100% rename from facebook_photos/images/full/n2306318_48612987_9521.jpg rename to facebook_photos/images/full/j_49.jpg diff --git a/facebook_photos/images/full/n2306318_48612988_9841.jpg b/facebook_photos/images/full/j_50.jpg similarity index 100% rename from facebook_photos/images/full/n2306318_48612988_9841.jpg rename to facebook_photos/images/full/j_50.jpg diff --git a/facebook_photos/images/tiny/j_01_tn.jpg b/facebook_photos/images/tiny/j_01_tn.jpg new file mode 100644 index 0000000..5e76fd4 Binary files /dev/null and b/facebook_photos/images/tiny/j_01_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_02_tn.jpg b/facebook_photos/images/tiny/j_02_tn.jpg new file mode 100644 index 0000000..a57d736 Binary files /dev/null and b/facebook_photos/images/tiny/j_02_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_03_tn.jpg b/facebook_photos/images/tiny/j_03_tn.jpg new file mode 100644 index 0000000..24c1ef1 Binary files /dev/null and b/facebook_photos/images/tiny/j_03_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_04_tn.jpg b/facebook_photos/images/tiny/j_04_tn.jpg new file mode 100644 index 0000000..bbc7474 Binary files /dev/null and b/facebook_photos/images/tiny/j_04_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_05_tn.jpg b/facebook_photos/images/tiny/j_05_tn.jpg new file mode 100644 index 0000000..f0cfe2d Binary files /dev/null and b/facebook_photos/images/tiny/j_05_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_06_tn.jpg b/facebook_photos/images/tiny/j_06_tn.jpg new file mode 100644 index 0000000..6395e7e Binary files /dev/null and b/facebook_photos/images/tiny/j_06_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_07_tn.jpg b/facebook_photos/images/tiny/j_07_tn.jpg new file mode 100644 index 0000000..6889091 Binary files /dev/null and b/facebook_photos/images/tiny/j_07_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_08_tn.jpg b/facebook_photos/images/tiny/j_08_tn.jpg new file mode 100644 index 0000000..6b50505 Binary files /dev/null and b/facebook_photos/images/tiny/j_08_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_09_tn.jpg b/facebook_photos/images/tiny/j_09_tn.jpg new file mode 100644 index 0000000..eb74048 Binary files /dev/null and b/facebook_photos/images/tiny/j_09_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_10_tn.jpg b/facebook_photos/images/tiny/j_10_tn.jpg new file mode 100644 index 0000000..000cb1d Binary files /dev/null and b/facebook_photos/images/tiny/j_10_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_11_tn.jpg b/facebook_photos/images/tiny/j_11_tn.jpg new file mode 100644 index 0000000..366b6fb Binary files /dev/null and b/facebook_photos/images/tiny/j_11_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_12_tn.jpg b/facebook_photos/images/tiny/j_12_tn.jpg new file mode 100644 index 0000000..4b95dd5 Binary files /dev/null and b/facebook_photos/images/tiny/j_12_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_13_tn.jpg b/facebook_photos/images/tiny/j_13_tn.jpg new file mode 100644 index 0000000..f622686 Binary files /dev/null and b/facebook_photos/images/tiny/j_13_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_14_tn.jpg b/facebook_photos/images/tiny/j_14_tn.jpg new file mode 100644 index 0000000..ce078c6 Binary files /dev/null and b/facebook_photos/images/tiny/j_14_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_15_tn.jpg b/facebook_photos/images/tiny/j_15_tn.jpg new file mode 100644 index 0000000..7e4e6da Binary files /dev/null and b/facebook_photos/images/tiny/j_15_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_16_tn.jpg b/facebook_photos/images/tiny/j_16_tn.jpg new file mode 100644 index 0000000..8343e4a Binary files /dev/null and b/facebook_photos/images/tiny/j_16_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_17_tn.jpg b/facebook_photos/images/tiny/j_17_tn.jpg new file mode 100644 index 0000000..012c7dc Binary files /dev/null and b/facebook_photos/images/tiny/j_17_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_18_tn.jpg b/facebook_photos/images/tiny/j_18_tn.jpg new file mode 100644 index 0000000..4e3cff3 Binary files /dev/null and b/facebook_photos/images/tiny/j_18_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_19_tn.jpg b/facebook_photos/images/tiny/j_19_tn.jpg new file mode 100644 index 0000000..1ba4377 Binary files /dev/null and b/facebook_photos/images/tiny/j_19_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_20_tn.jpg b/facebook_photos/images/tiny/j_20_tn.jpg new file mode 100644 index 0000000..318ae76 Binary files /dev/null and b/facebook_photos/images/tiny/j_20_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_21_tn.jpg b/facebook_photos/images/tiny/j_21_tn.jpg new file mode 100644 index 0000000..f02e913 Binary files /dev/null and b/facebook_photos/images/tiny/j_21_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_22_tn.jpg b/facebook_photos/images/tiny/j_22_tn.jpg new file mode 100644 index 0000000..c6f11a9 Binary files /dev/null and b/facebook_photos/images/tiny/j_22_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_23_tn.jpg b/facebook_photos/images/tiny/j_23_tn.jpg new file mode 100644 index 0000000..dcd441e Binary files /dev/null and b/facebook_photos/images/tiny/j_23_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_24_tn.jpg b/facebook_photos/images/tiny/j_24_tn.jpg new file mode 100644 index 0000000..020adb3 Binary files /dev/null and b/facebook_photos/images/tiny/j_24_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_25_tn.jpg b/facebook_photos/images/tiny/j_25_tn.jpg new file mode 100644 index 0000000..e4370e4 Binary files /dev/null and b/facebook_photos/images/tiny/j_25_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_26_tn.jpg b/facebook_photos/images/tiny/j_26_tn.jpg new file mode 100644 index 0000000..ba109b3 Binary files /dev/null and b/facebook_photos/images/tiny/j_26_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_27_tn.jpg b/facebook_photos/images/tiny/j_27_tn.jpg new file mode 100644 index 0000000..cadbf7b Binary files /dev/null and b/facebook_photos/images/tiny/j_27_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_28_tn.jpg b/facebook_photos/images/tiny/j_28_tn.jpg new file mode 100644 index 0000000..6d36eaa Binary files /dev/null and b/facebook_photos/images/tiny/j_28_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_29_tn.jpg b/facebook_photos/images/tiny/j_29_tn.jpg new file mode 100644 index 0000000..6776bf3 Binary files /dev/null and b/facebook_photos/images/tiny/j_29_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_30_tn.jpg b/facebook_photos/images/tiny/j_30_tn.jpg new file mode 100644 index 0000000..eced3b1 Binary files /dev/null and b/facebook_photos/images/tiny/j_30_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_31_tn.jpg b/facebook_photos/images/tiny/j_31_tn.jpg new file mode 100644 index 0000000..73924bf Binary files /dev/null and b/facebook_photos/images/tiny/j_31_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_32_tn.jpg b/facebook_photos/images/tiny/j_32_tn.jpg new file mode 100644 index 0000000..ef547cb Binary files /dev/null and b/facebook_photos/images/tiny/j_32_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_33_tn.jpg b/facebook_photos/images/tiny/j_33_tn.jpg new file mode 100644 index 0000000..b23ac22 Binary files /dev/null and b/facebook_photos/images/tiny/j_33_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_34_tn.jpg b/facebook_photos/images/tiny/j_34_tn.jpg new file mode 100644 index 0000000..ecfb60b Binary files /dev/null and b/facebook_photos/images/tiny/j_34_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_35_tn.jpg b/facebook_photos/images/tiny/j_35_tn.jpg new file mode 100644 index 0000000..437898c Binary files /dev/null and b/facebook_photos/images/tiny/j_35_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_36_tn.jpg b/facebook_photos/images/tiny/j_36_tn.jpg new file mode 100644 index 0000000..95f750c Binary files /dev/null and b/facebook_photos/images/tiny/j_36_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_37_tn.jpg b/facebook_photos/images/tiny/j_37_tn.jpg new file mode 100644 index 0000000..33f9d07 Binary files /dev/null and b/facebook_photos/images/tiny/j_37_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_38_tn.jpg b/facebook_photos/images/tiny/j_38_tn.jpg new file mode 100644 index 0000000..4df2c73 Binary files /dev/null and b/facebook_photos/images/tiny/j_38_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_39_tn.jpg b/facebook_photos/images/tiny/j_39_tn.jpg new file mode 100644 index 0000000..5f9b7f3 Binary files /dev/null and b/facebook_photos/images/tiny/j_39_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_40_tn.jpg b/facebook_photos/images/tiny/j_40_tn.jpg new file mode 100644 index 0000000..e566a46 Binary files /dev/null and b/facebook_photos/images/tiny/j_40_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_41_tn.jpg b/facebook_photos/images/tiny/j_41_tn.jpg new file mode 100644 index 0000000..15720f2 Binary files /dev/null and b/facebook_photos/images/tiny/j_41_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_42_tn.jpg b/facebook_photos/images/tiny/j_42_tn.jpg new file mode 100644 index 0000000..b24f104 Binary files /dev/null and b/facebook_photos/images/tiny/j_42_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_43_tn.jpg b/facebook_photos/images/tiny/j_43_tn.jpg new file mode 100644 index 0000000..64dfd3d Binary files /dev/null and b/facebook_photos/images/tiny/j_43_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_44_tn.jpg b/facebook_photos/images/tiny/j_44_tn.jpg new file mode 100644 index 0000000..268b0a9 Binary files /dev/null and b/facebook_photos/images/tiny/j_44_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_45_tn.jpg b/facebook_photos/images/tiny/j_45_tn.jpg new file mode 100644 index 0000000..b775ab3 Binary files /dev/null and b/facebook_photos/images/tiny/j_45_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_46_tn.jpg b/facebook_photos/images/tiny/j_46_tn.jpg new file mode 100644 index 0000000..1ca50f4 Binary files /dev/null and b/facebook_photos/images/tiny/j_46_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_47_tn.jpg b/facebook_photos/images/tiny/j_47_tn.jpg new file mode 100644 index 0000000..172fa70 Binary files /dev/null and b/facebook_photos/images/tiny/j_47_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_48_tn.jpg b/facebook_photos/images/tiny/j_48_tn.jpg new file mode 100644 index 0000000..aa3125e Binary files /dev/null and b/facebook_photos/images/tiny/j_48_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_49_tn.jpg b/facebook_photos/images/tiny/j_49_tn.jpg new file mode 100644 index 0000000..67e3ee3 Binary files /dev/null and b/facebook_photos/images/tiny/j_49_tn.jpg differ diff --git a/facebook_photos/images/tiny/j_50_tn.jpg b/facebook_photos/images/tiny/j_50_tn.jpg new file mode 100644 index 0000000..5bb2a3f Binary files /dev/null and b/facebook_photos/images/tiny/j_50_tn.jpg differ
trek/red-sample-apps
3d23dc63dc5369d3615400d9efc9112aa5ab815a
added full sized image samples
diff --git a/facebook_photos/images/full/n2203865_44699938_683.jpg b/facebook_photos/images/full/n2203865_44699938_683.jpg new file mode 100644 index 0000000..226e572 Binary files /dev/null and b/facebook_photos/images/full/n2203865_44699938_683.jpg differ diff --git a/facebook_photos/images/full/n2210434_36361375_607.jpg b/facebook_photos/images/full/n2210434_36361375_607.jpg new file mode 100644 index 0000000..24c98a9 Binary files /dev/null and b/facebook_photos/images/full/n2210434_36361375_607.jpg differ diff --git a/facebook_photos/images/full/n2210434_38361011_4955.jpg b/facebook_photos/images/full/n2210434_38361011_4955.jpg new file mode 100644 index 0000000..f29cc10 Binary files /dev/null and b/facebook_photos/images/full/n2210434_38361011_4955.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501426_6677.jpg b/facebook_photos/images/full/n2210434_41501426_6677.jpg new file mode 100644 index 0000000..f10a76d Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501426_6677.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501427_9275.jpg b/facebook_photos/images/full/n2210434_41501427_9275.jpg new file mode 100644 index 0000000..67ff4ea Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501427_9275.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501429_4021.jpg b/facebook_photos/images/full/n2210434_41501429_4021.jpg new file mode 100644 index 0000000..7661a27 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501429_4021.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501430_6077.jpg b/facebook_photos/images/full/n2210434_41501430_6077.jpg new file mode 100644 index 0000000..cd5dd9e Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501430_6077.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501431_8794.jpg b/facebook_photos/images/full/n2210434_41501431_8794.jpg new file mode 100644 index 0000000..c1003e5 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501431_8794.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501435_7215.jpg b/facebook_photos/images/full/n2210434_41501435_7215.jpg new file mode 100644 index 0000000..410bee6 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501435_7215.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501436_9498.jpg b/facebook_photos/images/full/n2210434_41501436_9498.jpg new file mode 100644 index 0000000..227be04 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501436_9498.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501464_6598.jpg b/facebook_photos/images/full/n2210434_41501464_6598.jpg new file mode 100644 index 0000000..b81753e Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501464_6598.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501465_8969.jpg b/facebook_photos/images/full/n2210434_41501465_8969.jpg new file mode 100644 index 0000000..d6bf00c Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501465_8969.jpg differ diff --git a/facebook_photos/images/full/n2210434_41501474_8874.jpg b/facebook_photos/images/full/n2210434_41501474_8874.jpg new file mode 100644 index 0000000..78d29a4 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41501474_8874.jpg differ diff --git a/facebook_photos/images/full/n2210434_41502802_8983.jpg b/facebook_photos/images/full/n2210434_41502802_8983.jpg new file mode 100644 index 0000000..cd019b0 Binary files /dev/null and b/facebook_photos/images/full/n2210434_41502802_8983.jpg differ diff --git a/facebook_photos/images/full/n2210434_41966118_9749.jpg b/facebook_photos/images/full/n2210434_41966118_9749.jpg new file mode 100644 index 0000000..a2d260b Binary files /dev/null and b/facebook_photos/images/full/n2210434_41966118_9749.jpg differ diff --git a/facebook_photos/images/full/n2210434_42069245_8853.jpg b/facebook_photos/images/full/n2210434_42069245_8853.jpg new file mode 100644 index 0000000..8d286c5 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42069245_8853.jpg differ diff --git a/facebook_photos/images/full/n2210434_42069246_3637.jpg b/facebook_photos/images/full/n2210434_42069246_3637.jpg new file mode 100644 index 0000000..3dd5e72 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42069246_3637.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090638_512.jpg b/facebook_photos/images/full/n2210434_42090638_512.jpg new file mode 100644 index 0000000..de01dbe Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090638_512.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090639_4578.jpg b/facebook_photos/images/full/n2210434_42090639_4578.jpg new file mode 100644 index 0000000..8520604 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090639_4578.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090640_7719.jpg b/facebook_photos/images/full/n2210434_42090640_7719.jpg new file mode 100644 index 0000000..0a0137d Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090640_7719.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090641_758.jpg b/facebook_photos/images/full/n2210434_42090641_758.jpg new file mode 100644 index 0000000..a40b2d7 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090641_758.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090647_1079.jpg b/facebook_photos/images/full/n2210434_42090647_1079.jpg new file mode 100644 index 0000000..2c72477 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090647_1079.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090655_9588.jpg b/facebook_photos/images/full/n2210434_42090655_9588.jpg new file mode 100644 index 0000000..364de1f Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090655_9588.jpg differ diff --git a/facebook_photos/images/full/n2210434_42090671_6824.jpg b/facebook_photos/images/full/n2210434_42090671_6824.jpg new file mode 100644 index 0000000..25d617a Binary files /dev/null and b/facebook_photos/images/full/n2210434_42090671_6824.jpg differ diff --git a/facebook_photos/images/full/n2210434_42161616_3183.jpg b/facebook_photos/images/full/n2210434_42161616_3183.jpg new file mode 100644 index 0000000..602a8ea Binary files /dev/null and b/facebook_photos/images/full/n2210434_42161616_3183.jpg differ diff --git a/facebook_photos/images/full/n2210434_42416842_238.jpg b/facebook_photos/images/full/n2210434_42416842_238.jpg new file mode 100644 index 0000000..443ca68 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42416842_238.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627691_7453.jpg b/facebook_photos/images/full/n2210434_42627691_7453.jpg new file mode 100644 index 0000000..30cfd9b Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627691_7453.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627692_7487.jpg b/facebook_photos/images/full/n2210434_42627692_7487.jpg new file mode 100644 index 0000000..24e6606 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627692_7487.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627698_1034.jpg b/facebook_photos/images/full/n2210434_42627698_1034.jpg new file mode 100644 index 0000000..fe17b91 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627698_1034.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627718_9316.jpg b/facebook_photos/images/full/n2210434_42627718_9316.jpg new file mode 100644 index 0000000..38070b3 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627718_9316.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627720_5029.jpg b/facebook_photos/images/full/n2210434_42627720_5029.jpg new file mode 100644 index 0000000..7415b9e Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627720_5029.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627722_9448.jpg b/facebook_photos/images/full/n2210434_42627722_9448.jpg new file mode 100644 index 0000000..4a34370 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627722_9448.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627723_6444.jpg b/facebook_photos/images/full/n2210434_42627723_6444.jpg new file mode 100644 index 0000000..e88ed0d Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627723_6444.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627741_6066.jpg b/facebook_photos/images/full/n2210434_42627741_6066.jpg new file mode 100644 index 0000000..dcfa602 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627741_6066.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627746_2515.jpg b/facebook_photos/images/full/n2210434_42627746_2515.jpg new file mode 100644 index 0000000..dac470f Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627746_2515.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627755_6759.jpg b/facebook_photos/images/full/n2210434_42627755_6759.jpg new file mode 100644 index 0000000..3b5098a Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627755_6759.jpg differ diff --git a/facebook_photos/images/full/n2210434_42627938_7785.jpg b/facebook_photos/images/full/n2210434_42627938_7785.jpg new file mode 100644 index 0000000..ec59fd7 Binary files /dev/null and b/facebook_photos/images/full/n2210434_42627938_7785.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563405_9172.jpg b/facebook_photos/images/full/n2210434_44563405_9172.jpg new file mode 100644 index 0000000..cac21d3 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563405_9172.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563407_2119.jpg b/facebook_photos/images/full/n2210434_44563407_2119.jpg new file mode 100644 index 0000000..1ca9c25 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563407_2119.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563408_4988.jpg b/facebook_photos/images/full/n2210434_44563408_4988.jpg new file mode 100644 index 0000000..8ab2f0c Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563408_4988.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563409_7746.jpg b/facebook_photos/images/full/n2210434_44563409_7746.jpg new file mode 100644 index 0000000..c51f070 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563409_7746.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563419_6601.jpg b/facebook_photos/images/full/n2210434_44563419_6601.jpg new file mode 100644 index 0000000..29d717a Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563419_6601.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563421_9241.jpg b/facebook_photos/images/full/n2210434_44563421_9241.jpg new file mode 100644 index 0000000..716f9d6 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563421_9241.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563423_4953.jpg b/facebook_photos/images/full/n2210434_44563423_4953.jpg new file mode 100644 index 0000000..0235935 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563423_4953.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563424_7730.jpg b/facebook_photos/images/full/n2210434_44563424_7730.jpg new file mode 100644 index 0000000..cc347f9 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563424_7730.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563425_487.jpg b/facebook_photos/images/full/n2210434_44563425_487.jpg new file mode 100644 index 0000000..58e8579 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563425_487.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563426_3136.jpg b/facebook_photos/images/full/n2210434_44563426_3136.jpg new file mode 100644 index 0000000..413e819 Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563426_3136.jpg differ diff --git a/facebook_photos/images/full/n2210434_44563428_8573.jpg b/facebook_photos/images/full/n2210434_44563428_8573.jpg new file mode 100644 index 0000000..9eb1e9d Binary files /dev/null and b/facebook_photos/images/full/n2210434_44563428_8573.jpg differ diff --git a/facebook_photos/images/full/n2306318_48612987_9521.jpg b/facebook_photos/images/full/n2306318_48612987_9521.jpg new file mode 100644 index 0000000..1807378 Binary files /dev/null and b/facebook_photos/images/full/n2306318_48612987_9521.jpg differ diff --git a/facebook_photos/images/full/n2306318_48612988_9841.jpg b/facebook_photos/images/full/n2306318_48612988_9841.jpg new file mode 100644 index 0000000..1f51eba Binary files /dev/null and b/facebook_photos/images/full/n2306318_48612988_9841.jpg differ
jmettraux/ruote-cukes
b712ccb6f0db8f46eca8f2587bbb8def1b32741a
#proceed replaced #reply for StorageParticipant
diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 918cdc0..39db02c 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,213 +1,213 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end def self.workitem if wi = @vars['workitem'] return wi end wi = @vars['storage_participant'].first @vars['workitem'] = wi end end # # re-opening the cucumber table class to add a fancy to_hash method # class Cucumber::Ast::Table def to_hash self.raw.inject({}) do |h, (k, v)| h[k] = (Rufus::Json.decode(v) rescue v) h end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new( Ruote::Worker.new( Ruote::HashStorage.new( 's_logger' => [ 'ruote/log/test_logger', 'Ruote::TestLogger' ]))) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # LAUNCH Given /the initial fields are$/ do |table| Ruote::Cukes.launch_fields = table.to_hash end Given /the initial variables are (.+)$/ do |table| Ruote::Cukes.launch_variables = table.to_hash end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # WORKITEMS -When /^I reply with the workitem$/ do +When /^I proceed with the workitem$/ do - Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) + Ruote::Cukes.storage_participant.proceed(Ruote::Cukes.workitem) Ruote::Cukes.workitem = nil end When /^I update the workitem with$/ do |table| Ruote::Cukes.workitem.fields.merge!(table.to_hash) end -When /^I reply$/ do +When /^I proceed$/ do sleep 0.100 # give some time to the engine - Ruote::Cukes.storage_participant.reply( + Ruote::Cukes.storage_participant.proceed( Ruote::Cukes.storage_participant.all.first) end Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end Then /^the workitem (?:fields )?should include$/ do |table| fields = table.to_hash assert_nil fields.find { |k, v| Ruote::Cukes.workitem.fields[k] != v } end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end Then /^the process should be over$/ do sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.engine.context.logger.log.find do |r| r['action'] == 'terminated' && r['wfid'] == Ruote::Cukes.last_wfid end assert_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end
jmettraux/ruote-cukes
755299bbaddf2a3ac2e68abc0c75f913c5ca68b2
release 2.1.9
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 9bbf8fd..f771d0c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,8 +1,8 @@ = ruote-cukes - CHANGELOG.txt -== ruote-cukes - 2.1.8 not yet released +== ruote-cukes - 2.1.9 released 2010/06/14 - initial release diff --git a/Rakefile b/Rakefile index 2a7a3e3..8e5cf52 100644 --- a/Rakefile +++ b/Rakefile @@ -1,43 +1,43 @@ require 'lib/ruote/cukes/version.rb' require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.version = Ruote::Cukes::VERSION gem.name = 'ruote-cukes' gem.summary = 'cucumber helpers for testing ruote definitions and participants' gem.description = %{ cucumber helpers (steps) for testing ruote process definitions and participants } gem.email = '[email protected]' gem.homepage = 'http://ruote.rubyforge.org' gem.authors = [ 'John Mettraux' ] gem.rubyforge_project = 'ruote' #gem.test_file = 'test/test.rb' - gem.add_dependency 'ruote', '>= 2.1.7' + gem.add_dependency 'ruote', '>= 2.1.9' gem.add_dependency 'cucumber' gem.add_development_dependency 'rake' gem.add_development_dependency 'jeweler' # Gem::Specification http://www.rubygems.org/read/chapter/20 end Jeweler::GemcutterTasks.new rescue LoadError puts 'Jeweler (or a dependency) not available. Install it with: gem install jeweler' end require 'rake/clean' CLEAN.include('pkg') task :default => [ :clean ] diff --git a/lib/ruote/cukes/version.rb b/lib/ruote/cukes/version.rb index f7a08bb..07029a2 100644 --- a/lib/ruote/cukes/version.rb +++ b/lib/ruote/cukes/version.rb @@ -1,8 +1,8 @@ module Ruote module Cukes - VERSION = '2.1.7' + VERSION = '2.1.9' end end
jmettraux/ruote-cukes
8096de02c1cb0e1a652949cc9eef094ab4535b69
Then the process should be over : better impl
diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index e2d857b..918cdc0 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,209 +1,213 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end def self.workitem if wi = @vars['workitem'] return wi end wi = @vars['storage_participant'].first @vars['workitem'] = wi end end # # re-opening the cucumber table class to add a fancy to_hash method # class Cucumber::Ast::Table def to_hash self.raw.inject({}) do |h, (k, v)| h[k] = (Rufus::Json.decode(v) rescue v) h end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = - Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) + Ruote::Engine.new( + Ruote::Worker.new( + Ruote::HashStorage.new( + 's_logger' => [ 'ruote/log/test_logger', 'Ruote::TestLogger' ]))) +end + + +# +# PARTICIPANTS + +Given /the catch[- ]?all participant is registered/ do + + Ruote::Cukes.storage_participant = + Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) + + Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context + # due to a bug in ruote 2.1.7, remove when 2.1.8 is out +end + +Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| + + sleep 0.100 # give some time to the engine + + Ruote::Cukes.workitem = + Ruote::Cukes.storage_participant.by_participant(pname).first end # # LAUNCH Given /the initial fields are$/ do |table| Ruote::Cukes.launch_fields = table.to_hash end Given /the initial variables are (.+)$/ do |table| Ruote::Cukes.launch_variables = table.to_hash end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end -# -# PARTICIPANTS - -Given /the catch[- ]?all participant is registered/ do - - Ruote::Cukes.storage_participant = - Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) - - Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context - # due to a bug in ruote 2.1.7, remove when 2.1.8 is out -end - -Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| - - sleep 0.100 # give some time to the engine - - Ruote::Cukes.workitem = - Ruote::Cukes.storage_participant.by_participant(pname).first -end - - # # WORKITEMS When /^I reply with the workitem$/ do Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) Ruote::Cukes.workitem = nil end When /^I update the workitem with$/ do |table| Ruote::Cukes.workitem.fields.merge!(table.to_hash) end When /^I reply$/ do sleep 0.100 # give some time to the engine Ruote::Cukes.storage_participant.reply( Ruote::Cukes.storage_participant.all.first) end Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end Then /^the workitem (?:fields )?should include$/ do |table| fields = table.to_hash assert_nil fields.find { |k, v| Ruote::Cukes.workitem.fields[k] != v } end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end Then /^the process should be over$/ do - # TODO : check that the process has RUN, the assertion is currently - # OK with processes that never ran. - sleep 0.100 # give some time to the engine + assert_not_nil Ruote::Cukes.engine.context.logger.log.find do |r| + r['action'] == 'terminated' && r['wfid'] == Ruote::Cukes.last_wfid + end + assert_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end
jmettraux/ruote-cukes
3f10e2f0032b3a407c77f38a6928b6c84e069f0b
changelog in
diff --git a/CHANGELOG.txt b/CHANGELOG.txt new file mode 100644 index 0000000..9bbf8fd --- /dev/null +++ b/CHANGELOG.txt @@ -0,0 +1,8 @@ + += ruote-cukes - CHANGELOG.txt + + +== ruote-cukes - 2.1.8 not yet released + +- initial release +
jmettraux/ruote-cukes
d679915d8239f29b5281536d33c57c7b539190ff
forgetting wi when replying and fetching it automatically
diff --git a/TODO.txt b/TODO.txt index 6b44283..dcd1919 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,4 +1,7 @@ +[o] use tables for field input +[o] "When I update the workitem with" should do storage_participant.first if + there is no workitem present + [ ] something about participants -[ ] use tables for field input diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index d673177..e2d857b 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,197 +1,209 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end + + def self.workitem + + if wi = @vars['workitem'] + return wi + end + + wi = @vars['storage_participant'].first + + @vars['workitem'] = wi + end end # # re-opening the cucumber table class to add a fancy to_hash method # class Cucumber::Ast::Table def to_hash self.raw.inject({}) do |h, (k, v)| h[k] = (Rufus::Json.decode(v) rescue v) h end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are$/ do |table| Ruote::Cukes.launch_fields = table.to_hash end Given /the initial variables are (.+)$/ do |table| Ruote::Cukes.launch_variables = table.to_hash end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS When /^I reply with the workitem$/ do Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) + Ruote::Cukes.workitem = nil end When /^I update the workitem with$/ do |table| Ruote::Cukes.workitem.fields.merge!(table.to_hash) end When /^I reply$/ do sleep 0.100 # give some time to the engine Ruote::Cukes.storage_participant.reply( Ruote::Cukes.storage_participant.all.first) end Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end Then /^the workitem (?:fields )?should include$/ do |table| fields = table.to_hash assert_nil fields.find { |k, v| Ruote::Cukes.workitem.fields[k] != v } end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end Then /^the process should be over$/ do # TODO : check that the process has RUN, the assertion is currently # OK with processes that never ran. sleep 0.100 # give some time to the engine assert_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end
jmettraux/ruote-cukes
7d93405880e6ab33f557ddc9a3ce7e57ef734514
Then the process should be over
diff --git a/features/over.feature b/features/over.feature new file mode 100644 index 0000000..c268735 --- /dev/null +++ b/features/over.feature @@ -0,0 +1,13 @@ + +Feature: When I launch + + of course, launch may be a Given or a When + + Scenario: from alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow at flows/a.rb + Then the process should reach alpha + When I reply + Then the process should be over + diff --git a/flows/a.rb b/flows/a.rb new file mode 100644 index 0000000..7d23a83 --- /dev/null +++ b/flows/a.rb @@ -0,0 +1,8 @@ + +# +# a tiny process with only a stop to participant alpha +# +Ruote.process_definition do + alpha +end + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index c37e386..d673177 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,179 +1,197 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # re-opening the cucumber table class to add a fancy to_hash method # class Cucumber::Ast::Table def to_hash self.raw.inject({}) do |h, (k, v)| h[k] = (Rufus::Json.decode(v) rescue v) h end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are$/ do |table| Ruote::Cukes.launch_fields = table.to_hash end Given /the initial variables are (.+)$/ do |table| Ruote::Cukes.launch_variables = table.to_hash end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS -Then /I should have a workitem/ do - - assert_not_nil Ruote::Cukes.workitem -end - When /^I reply with the workitem$/ do Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) end When /^I update the workitem with$/ do |table| Ruote::Cukes.workitem.fields.merge!(table.to_hash) end +When /^I reply$/ do + + sleep 0.100 # give some time to the engine + + Ruote::Cukes.storage_participant.reply( + Ruote::Cukes.storage_participant.all.first) +end + +Then /I should have a workitem/ do + + assert_not_nil Ruote::Cukes.workitem +end + Then /^the workitem (?:fields )?should include$/ do |table| fields = table.to_hash assert_nil fields.find { |k, v| Ruote::Cukes.workitem.fields[k] != v } end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end +Then /^the process should be over$/ do + + # TODO : check that the process has RUN, the assertion is currently + # OK with processes that never ran. + + sleep 0.100 # give some time to the engine + + assert_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) +end +
jmettraux/ruote-cukes
a51617c394aeb109c6d287187b0495fd032b4eb3
including a scenario example in the readme
diff --git a/README.rdoc b/README.rdoc index 80d39e8..f2a2d1d 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,38 +1,55 @@ = ruote-cukes Cucumber helpers (steps) for testing ruote process definitions and participants. - INSERT SAMPLE FEATURE HERE + Scenario: alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow + """ + Ruote.process_definition do + sequence do + alpha + participant :ref => '${f:next}' + end + end + """ + Then the process should reach alpha + When I get the first workitem of participant alpha + And I update the workitem with + | next | charly | + And I reply with the workitem + Then the process should reach charly Look at features/ for the whole range of examples. == using them gem install ruote-cukes then make sure to include require 'ruote-cukes' in your feature support or step definitions. == running the example features Make sure the ruote and cucumber gems are installed and run cucumber == author John Mettraux http://jmettraux.wordpress.com == license MIT diff --git a/features/whole.feature b/features/whole.feature new file mode 100644 index 0000000..2f85fc0 --- /dev/null +++ b/features/whole.feature @@ -0,0 +1,24 @@ + +Feature: ruote-cukes features + + showing a rather complete example + + Scenario: alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow + """ + Ruote.process_definition do + sequence do + alpha + participant :ref => '${f:next}' + end + end + """ + Then the process should reach alpha + When I get the first workitem of participant alpha + And I update the workitem with + | next | charly | + And I reply with the workitem + Then the process should reach charly +
jmettraux/ruote-cukes
5dadf7d802356577450f52392c0568fb4bcda4d5
using cucumber tables for fields and variables
diff --git a/features/basic.feature b/features/basic.feature index d3a3926..4e70339 100644 --- a/features/basic.feature +++ b/features/basic.feature @@ -1,15 +1,14 @@ Feature: basic a basic feature example Scenario: from a to b Given I have a ruote engine - And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow at flows/a_to_b.rb When I get the first workitem of participant alpha Then I should have a workitem And the process should be alive And the process should have no errors diff --git a/features/embedded.feature b/features/embedded.feature index f3f99bd..cc424b3 100644 --- a/features/embedded.feature +++ b/features/embedded.feature @@ -1,21 +1,20 @@ Feature: I launch the flow the process definition is embedded in the feature Scenario: alpha to bravo Given I have a ruote engine - And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow """ Ruote.process_definition do sequence do alpha bravo end end """ When I get the first workitem of participant alpha Then I should have a workitem diff --git a/features/initial_fields.feature b/features/initial_fields.feature new file mode 100644 index 0000000..bc89af7 --- /dev/null +++ b/features/initial_fields.feature @@ -0,0 +1,17 @@ + +Feature: When the initial fields are + + using a cucumber table to set the initial fields of a workitem (launchitem) + + Scenario: alpha to bravo + Given I have a ruote engine + And the initial fields are + | customer | Alain-san | + | company | super asia exchange | + And the catchall participant is registered + And I launch the flow at flows/a_to_b.rb + When I get the first workitem of participant alpha + Then the workitem should include + | customer | Alain-san | + | company | super asia exchange | + diff --git a/features/update.feature b/features/update.feature index c320d34..e74d034 100644 --- a/features/update.feature +++ b/features/update.feature @@ -1,16 +1,18 @@ Feature: When I update the workitem with changing the fields (payload) of a workitem Scenario: alpha to bravo Given I have a ruote engine And the catchall participant is registered When I launch the flow at flows/a_to_b.rb Then the process should reach alpha When I get the first workitem of alpha - And I update the workitem with "customer":"Alf" + And I update the workitem with + | customer | Alf | And I reply with the workitem Then the process should reach bravo - And the workitem should include "customer":"Alf" + And the workitem should include + | customer | Alf | diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 079c4f6..c37e386 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,173 +1,179 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' +# # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end +end - def self.parse_json (s) +# +# re-opening the cucumber table class to add a fancy to_hash method +# +class Cucumber::Ast::Table - s = "{#{s}}" unless s.match(/^{.+}$/) + def to_hash - Rufus::Json.decode(s) + self.raw.inject({}) do |h, (k, v)| + h[k] = (Rufus::Json.decode(v) rescue v) + h + end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH -Given /the initial fields are (.+)$/ do |fields| +Given /the initial fields are$/ do |table| - Ruote::Cukes.launch_fields = Ruote::Cukes.parse_json(fields) + Ruote::Cukes.launch_fields = table.to_hash end -Given /the initial variables are (.+)$/ do |variables| +Given /the initial variables are (.+)$/ do |table| - Ruote::Cukes.launch_variables = Ruote::Cukes.parse_json(variables) + Ruote::Cukes.launch_variables = table.to_hash end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end When /^I reply with the workitem$/ do Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) end -When /^I update the workitem with (.+)$/ do |fields| - - fields = Ruote::Cukes.parse_json(fields) +When /^I update the workitem with$/ do |table| - Ruote::Cukes.workitem.fields.merge!(fields) + Ruote::Cukes.workitem.fields.merge!(table.to_hash) end -Then /^the workitem (?:fields )?should include (.+)$/ do |fields| +Then /^the workitem (?:fields )?should include$/ do |table| - fields = Ruote::Cukes.parse_json(fields) + fields = table.to_hash assert_nil fields.find { |k, v| Ruote::Cukes.workitem.fields[k] != v } end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end
jmettraux/ruote-cukes
34fbdff6b4d08deaba86e1683529c85e6ae5dc3a
Then the workitem should include 'this and that field'
diff --git a/TODO.txt b/TODO.txt index 23fa3a3..6b44283 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,3 +1,4 @@ [ ] something about participants +[ ] use tables for field input diff --git a/features/update.feature b/features/update.feature new file mode 100644 index 0000000..c320d34 --- /dev/null +++ b/features/update.feature @@ -0,0 +1,16 @@ + +Feature: When I update the workitem with + + changing the fields (payload) of a workitem + + Scenario: alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow at flows/a_to_b.rb + Then the process should reach alpha + When I get the first workitem of alpha + And I update the workitem with "customer":"Alf" + And I reply with the workitem + Then the process should reach bravo + And the workitem should include "customer":"Alf" + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index bfedc0d..079c4f6 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,153 +1,173 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end + + def self.parse_json (s) + + s = "{#{s}}" unless s.match(/^{.+}$/) + + Rufus::Json.decode(s) + end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| - fields = "{#{fields}}" unless fields.match(/^{.+}$/) - - Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) + Ruote::Cukes.launch_fields = Ruote::Cukes.parse_json(fields) end -Given /the initial variables are (.+)$/ do |vars| - - vars = "{#{vars}}" unless vars.match(/^{.+}$/) +Given /the initial variables are (.+)$/ do |variables| - Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) + Ruote::Cukes.launch_variables = Ruote::Cukes.parse_json(variables) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end When /^I reply with the workitem$/ do Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) end +When /^I update the workitem with (.+)$/ do |fields| + + fields = Ruote::Cukes.parse_json(fields) + + Ruote::Cukes.workitem.fields.merge!(fields) +end + +Then /^the workitem (?:fields )?should include (.+)$/ do |fields| + + fields = Ruote::Cukes.parse_json(fields) + + assert_nil fields.find { |k, v| + Ruote::Cukes.workitem.fields[k] != v + } +end + + # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end
jmettraux/ruote-cukes
b3be15ebd1a833d08d8bc69f99f6ae152d34e3a3
from example_features/ to features/ (examples are specs)
diff --git a/CREDITS.txt b/CREDITS.txt index 6fae079..9438316 100644 --- a/CREDITS.txt +++ b/CREDITS.txt @@ -1,8 +1,11 @@ = CREDITS.txt John Mettraux - http://jmettraux.wordpress.com Nicholas Faiz - http://github.com/biv Kenneth Kalmer - http://github.com/kennethkalmer + +Many thanks to the authors of Cucumber : http://cukes.info/ + diff --git a/README.rdoc b/README.rdoc index b1f4620..80d39e8 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,15 +1,38 @@ = ruote-cukes -cucumber helpers (steps) for testing ruote process definitions and participants. +Cucumber helpers (steps) for testing ruote process definitions and participants. + INSERT SAMPLE FEATURE HERE -== running the example +Look at features/ for the whole range of examples. - cucumber example_features/ + +== using them + + gem install ruote-cukes + +then make sure to include + + require 'ruote-cukes' + +in your feature support or step definitions. + + +== running the example features + +Make sure the ruote and cucumber gems are installed and run + + cucumber + + +== author + +John Mettraux +http://jmettraux.wordpress.com == license MIT diff --git a/example_features/flow.feature b/features/basic.feature similarity index 68% rename from example_features/flow.feature rename to features/basic.feature index ce41353..d3a3926 100644 --- a/example_features/flow.feature +++ b/features/basic.feature @@ -1,15 +1,15 @@ -Feature: running the flow +Feature: basic - My flow should deliver workitems to the first participant in the flow + a basic feature example Scenario: from a to b Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered - And I launch the flow at example_flows/a_to_b.rb + And I launch the flow at flows/a_to_b.rb When I get the first workitem of participant alpha Then I should have a workitem And the process should be alive And the process should have no errors diff --git a/example_features/embedded_flow.feature b/features/embedded.feature similarity index 78% rename from example_features/embedded_flow.feature rename to features/embedded.feature index e1763c4..f3f99bd 100644 --- a/example_features/embedded_flow.feature +++ b/features/embedded.feature @@ -1,21 +1,21 @@ -Feature: running the flow +Feature: I launch the flow - whatever... + the process definition is embedded in the feature - Scenario: from a to b + Scenario: alpha to bravo Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow """ Ruote.process_definition do sequence do alpha bravo end end """ When I get the first workitem of participant alpha Then I should have a workitem diff --git a/example_features/continuing.feature b/features/reply.feature similarity index 57% rename from example_features/continuing.feature rename to features/reply.feature index 3d35d6d..449c666 100644 --- a/example_features/continuing.feature +++ b/features/reply.feature @@ -1,14 +1,14 @@ -Feature: no sleep till bravo +Feature: When I reply with the workitem - till bravo + a step definition for letting a workitem resume in its flow - Scenario: from alpha to bravo + Scenario: alpha to bravo Given I have a ruote engine And the catchall participant is registered - When I launch the flow at example_flows/a_to_b.rb + When I launch the flow at flows/a_to_b.rb Then the process should reach alpha When I get the first workitem of alpha And I reply with the workitem Then the process should reach bravo diff --git a/example_features/step_definitions/requiring.rb b/features/step_definitions/requiring.rb similarity index 100% rename from example_features/step_definitions/requiring.rb rename to features/step_definitions/requiring.rb diff --git a/example_features/when_i_launch.feature b/features/when.feature similarity index 62% rename from example_features/when_i_launch.feature rename to features/when.feature index b86980c..8ced8c4 100644 --- a/example_features/when_i_launch.feature +++ b/features/when.feature @@ -1,12 +1,12 @@ -Feature: when I launch... +Feature: When I launch - A long time ago in a galaxy far, far away + of course, launch may be a Given or a When Scenario: from alpha to bravo Given I have a ruote engine And the catchall participant is registered - When I launch the flow at example_flows/a_to_b.rb + When I launch the flow at flows/a_to_b.rb Then the process should reach alpha And the process should reach participant alpha diff --git a/example_flows/a_to_b.rb b/flows/a_to_b.rb similarity index 100% rename from example_flows/a_to_b.rb rename to flows/a_to_b.rb
jmettraux/ruote-cukes
26303455be64a11a533fb4415d15150bcf1acc8a
When I reply with the workitem
diff --git a/example_features/continuing.feature b/example_features/continuing.feature new file mode 100644 index 0000000..3d35d6d --- /dev/null +++ b/example_features/continuing.feature @@ -0,0 +1,14 @@ + +Feature: no sleep till bravo + + till bravo + + Scenario: from alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow at example_flows/a_to_b.rb + Then the process should reach alpha + When I get the first workitem of alpha + And I reply with the workitem + Then the process should reach bravo + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 288fba9..bfedc0d 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,148 +1,153 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end +When /^I reply with the workitem$/ do + + Ruote::Cukes.storage_participant.reply(Ruote::Cukes.workitem) +end + # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end
jmettraux/ruote-cukes
c25a604710abde39bcfa55485bd9596f6353d415
using non-capturing groups for participants
diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 869aa9b..288fba9 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,148 +1,148 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end -Given /I get the first workitem of participant (.+)$/ do |pname| +Given /I get the first workitem of (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end -Then /^the process should reach (participant )?(.+)$/ do |_, pname| +Then /^the process should reach (?:participant )?(.+)$/ do |pname| sleep 0.100 # give some time to the engine assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end
jmettraux/ruote-cukes
802fb0eeaf77d2a5b097965a8ee8ba6946aca6bc
setting the context
diff --git a/example_features/when_i_launch.feature b/example_features/when_i_launch.feature index da24f55..b86980c 100644 --- a/example_features/when_i_launch.feature +++ b/example_features/when_i_launch.feature @@ -1,12 +1,12 @@ Feature: when I launch... - somewhere in a distant galaxy + A long time ago in a galaxy far, far away Scenario: from alpha to bravo Given I have a ruote engine And the catchall participant is registered When I launch the flow at example_flows/a_to_b.rb Then the process should reach alpha And the process should reach participant alpha
jmettraux/ruote-cukes
e36ae70e63e2b16bc08f8e12fd288af5b1b63a79
giving some time to the engine
diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index cfacefd..869aa9b 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,144 +1,148 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end Given /I get the first workitem of participant (.+)$/ do |pname| + sleep 0.100 # give some time to the engine + Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end Then /^the process should reach (participant )?(.+)$/ do |_, pname| + sleep 0.100 # give some time to the engine + assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname } end
jmettraux/ruote-cukes
42b5e687617b6d48b806e0cf95696120343e95a5
Then the process should reach participant alpha
diff --git a/example_features/when_i_launch.feature b/example_features/when_i_launch.feature new file mode 100644 index 0000000..da24f55 --- /dev/null +++ b/example_features/when_i_launch.feature @@ -0,0 +1,12 @@ + +Feature: when I launch... + + somewhere in a distant galaxy + + Scenario: from alpha to bravo + Given I have a ruote engine + And the catchall participant is registered + When I launch the flow at example_flows/a_to_b.rb + Then the process should reach alpha + And the process should reach participant alpha + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 09a646d..cfacefd 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,137 +1,144 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end -When /I get the first workitem of participant (.+)$/ do |pname| +Given /I get the first workitem of participant (.+)$/ do |pname| Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end # # PROCESSES Then /^the process should be alive$/ do assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) end Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end +Then /^the process should reach (participant )?(.+)$/ do |_, pname| + + assert_not_nil Ruote::Cukes.storage_participant.all.find { |wi| + wi.fei.wfid == Ruote::Cukes.last_wfid && wi.participant_name == pname + } +end +
jmettraux/ruote-cukes
90828791576e6c6ea40afeab51e13bc6a2938c08
and a TODO file
diff --git a/TODO.txt b/TODO.txt new file mode 100644 index 0000000..23fa3a3 --- /dev/null +++ b/TODO.txt @@ -0,0 +1,3 @@ + +[ ] something about participants +
jmettraux/ruote-cukes
2974b75580c4100d29f35f9b5a985755b0c2e598
CREDITS.txt
diff --git a/CREDITS.txt b/CREDITS.txt new file mode 100644 index 0000000..6fae079 --- /dev/null +++ b/CREDITS.txt @@ -0,0 +1,8 @@ + += CREDITS.txt + +John Mettraux - http://jmettraux.wordpress.com + +Nicholas Faiz - http://github.com/biv +Kenneth Kalmer - http://github.com/kennethkalmer +
jmettraux/ruote-cukes
b42f24dfa6f7d00b78d556e63f00454f5fd9be89
Then the process should be alive
diff --git a/example_features/embedded_flow.feature b/example_features/embedded_flow.feature index 8bb7848..e1763c4 100644 --- a/example_features/embedded_flow.feature +++ b/example_features/embedded_flow.feature @@ -1,21 +1,21 @@ Feature: running the flow - In order to blah + whatever... Scenario: from a to b Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow """ Ruote.process_definition do sequence do alpha bravo end end """ When I get the first workitem of participant alpha Then I should have a workitem diff --git a/example_features/flow.feature b/example_features/flow.feature index be1d379..ce41353 100644 --- a/example_features/flow.feature +++ b/example_features/flow.feature @@ -1,14 +1,15 @@ Feature: running the flow - In order to blah + My flow should deliver workitems to the first participant in the flow Scenario: from a to b Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow at example_flows/a_to_b.rb When I get the first workitem of participant alpha Then I should have a workitem + And the process should be alive And the process should have no errors diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index f4b90a7..09a646d 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,132 +1,137 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end When /I get the first workitem of participant (.+)$/ do |pname| Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end # # PROCESSES +Then /^the process should be alive$/ do + + assert_not_nil Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid) +end + Then /^the process should have no errors$/ do assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors end
jmettraux/ruote-cukes
3049c4e8137c9ec29824baf94bbacf57b45d3e5e
Then the process should have no errors
diff --git a/example_features/flow.feature b/example_features/flow.feature index 0447f36..be1d379 100644 --- a/example_features/flow.feature +++ b/example_features/flow.feature @@ -1,13 +1,14 @@ Feature: running the flow In order to blah Scenario: from a to b Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered And I launch the flow at example_flows/a_to_b.rb When I get the first workitem of participant alpha Then I should have a workitem + And the process should have no errors diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index a6999b4..f4b90a7 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,123 +1,132 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end Given /I launch the flow$/ do |process_definition| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( process_definition, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end When /I get the first workitem of participant (.+)$/ do |pname| Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end + +# +# PROCESSES + +Then /^the process should have no errors$/ do + + assert_equal [], Ruote::Cukes.engine.process(Ruote::Cukes.last_wfid).errors +end +
jmettraux/ruote-cukes
fd32bd062cebec9bc27cf7224eb1d8bfa754f4bf
embedded process definitions (as strings) are OK
diff --git a/example_features/embedded_flow.feature b/example_features/embedded_flow.feature new file mode 100644 index 0000000..8bb7848 --- /dev/null +++ b/example_features/embedded_flow.feature @@ -0,0 +1,21 @@ + +Feature: running the flow + + In order to blah + + Scenario: from a to b + Given I have a ruote engine + And the initial fields are "customer":"Alain" + And the catchall participant is registered + And I launch the flow + """ + Ruote.process_definition do + sequence do + alpha + bravo + end + end + """ + When I get the first workitem of participant alpha + Then I should have a workitem + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 93a1323..a6999b4 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,115 +1,123 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'test/unit/assertions' include Test::Unit::Assertions # not sure about that for now... require 'json' require 'ruote' require 'ruote/cukes/version' # a variable container in a singleton, or something like that # module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, Ruote::Cukes.launch_variables || {}) end +Given /I launch the flow$/ do |process_definition| + + Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( + process_definition, + Ruote::Cukes.launch_fields || {}, + Ruote::Cukes.launch_variables || {}) +end + # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end When /I get the first workitem of participant (.+)$/ do |pname| Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do assert_not_nil Ruote::Cukes.workitem end
jmettraux/ruote-cukes
9fe9ec875c1e2e4f056de0b0a453bc3bf847888e
initial example feature 100% green
diff --git a/Gemfile b/Gemfile deleted file mode 100644 index 2b4c1ee..0000000 --- a/Gemfile +++ /dev/null @@ -1,6 +0,0 @@ - -source 'http://gemcutter.org' - -gem 'cucumber' -gem 'ruote' - diff --git a/README.rdoc b/README.rdoc index 42ba4ad..b1f4620 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,7 +1,15 @@ = ruote-cukes +cucumber helpers (steps) for testing ruote process definitions and participants. + + +== running the example + + cucumber example_features/ + + == license MIT diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..2a7a3e3 --- /dev/null +++ b/Rakefile @@ -0,0 +1,43 @@ + +require 'lib/ruote/cukes/version.rb' + +require 'rubygems' +require 'rake' + + +begin + + require 'jeweler' + + Jeweler::Tasks.new do |gem| + + gem.version = Ruote::Cukes::VERSION + gem.name = 'ruote-cukes' + gem.summary = 'cucumber helpers for testing ruote definitions and participants' + gem.description = %{ +cucumber helpers (steps) for testing ruote process definitions and participants + } + gem.email = '[email protected]' + gem.homepage = 'http://ruote.rubyforge.org' + gem.authors = [ 'John Mettraux' ] + gem.rubyforge_project = 'ruote' + #gem.test_file = 'test/test.rb' + + gem.add_dependency 'ruote', '>= 2.1.7' + gem.add_dependency 'cucumber' + + gem.add_development_dependency 'rake' + gem.add_development_dependency 'jeweler' + + # Gem::Specification http://www.rubygems.org/read/chapter/20 + end + Jeweler::GemcutterTasks.new +rescue LoadError + puts 'Jeweler (or a dependency) not available. Install it with: gem install jeweler' +end + +require 'rake/clean' +CLEAN.include('pkg') + +task :default => [ :clean ] + diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 47ff77c..93a1323 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,108 +1,115 @@ #-- # Copyright (c) 2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ +require 'test/unit/assertions' +include Test::Unit::Assertions + # not sure about that for now... + require 'json' require 'ruote' +require 'ruote/cukes/version' + # a variable container in a singleton, or something like that # -module Ruote -module Cukes +module Ruote::Cukes def self.method_missing (m, *args) m = m.to_s if args.size == 1 && mm = m.match(/^(.+)=$/) (@vars ||= {})[mm[1]] = args.first elsif args.size == 0 (@vars ||= {})[m] else super end end end -end # # ENGINE Given /I have a ruote engine/ do Ruote::Cukes.engine = Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) end # # LAUNCH Given /the initial fields are (.+)$/ do |fields| fields = "{#{fields}}" unless fields.match(/^{.+}$/) Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) end Given /the initial variables are (.+)$/ do |vars| vars = "{#{vars}}" unless vars.match(/^{.+}$/) Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) end Given /I launch the flow at (.+)$/ do |path| Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( path, Ruote::Cukes.launch_fields || {}, - Ruote::Cukes.lannch_variables || {}) + Ruote::Cukes.launch_variables || {}) end # # PARTICIPANTS Given /the catch[- ]?all participant is registered/ do Ruote::Cukes.storage_participant = Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) + + Ruote::Cukes.storage_participant.context = Ruote::Cukes.engine.context + # due to a bug in ruote 2.1.7, remove when 2.1.8 is out end When /I get the first workitem of participant (.+)$/ do |pname| Ruote::Cukes.workitem = Ruote::Cukes.storage_participant.by_participant(pname).first end # # WORKITEMS Then /I should have a workitem/ do - Ruote::Cukes.workitem.should.not.be.nil + assert_not_nil Ruote::Cukes.workitem end diff --git a/lib/ruote/cukes/version.rb b/lib/ruote/cukes/version.rb new file mode 100644 index 0000000..f7a08bb --- /dev/null +++ b/lib/ruote/cukes/version.rb @@ -0,0 +1,8 @@ + +module Ruote +module Cukes + + VERSION = '2.1.7' +end +end + diff --git a/ruote-cukes.gemspec b/ruote-cukes.gemspec new file mode 100644 index 0000000..b67e4dc --- /dev/null +++ b/ruote-cukes.gemspec @@ -0,0 +1,59 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{ruote-cukes} + s.version = "2.1.7" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["John Mettraux"] + s.date = %q{2010-03-05} + s.description = %q{ +cucumber helpers (steps) for testing ruote process definitions and participants + } + s.email = %q{[email protected]} + s.extra_rdoc_files = [ + "README.rdoc" + ] + s.files = [ + ".rvmrc", + "README.rdoc", + "Rakefile", + "example_features/flow.feature", + "example_features/step_definitions/requiring.rb", + "example_flows/a_to_b.rb", + "lib/ruote/cukes.rb", + "lib/ruote/cukes/version.rb" + ] + s.homepage = %q{http://ruote.rubyforge.org} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubyforge_project = %q{ruote} + s.rubygems_version = %q{1.3.6} + s.summary = %q{cucumber helpers for testing ruote definitions and participants} + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then + s.add_runtime_dependency(%q<ruote>, [">= 2.1.7"]) + s.add_runtime_dependency(%q<cucumber>, [">= 0"]) + s.add_development_dependency(%q<rake>, [">= 0"]) + s.add_development_dependency(%q<jeweler>, [">= 0"]) + else + s.add_dependency(%q<ruote>, [">= 2.1.7"]) + s.add_dependency(%q<cucumber>, [">= 0"]) + s.add_dependency(%q<rake>, [">= 0"]) + s.add_dependency(%q<jeweler>, [">= 0"]) + end + else + s.add_dependency(%q<ruote>, [">= 2.1.7"]) + s.add_dependency(%q<cucumber>, [">= 0"]) + s.add_dependency(%q<rake>, [">= 0"]) + s.add_dependency(%q<jeweler>, [">= 0"]) + end +end +
jmettraux/ruote-cukes
fbc641f94e0c9931aad20ae352ce8b1cb4a2e2e6
placing all in a single ruote/cukes.rb file
diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..42ba4ad --- /dev/null +++ b/README.rdoc @@ -0,0 +1,7 @@ + += ruote-cukes + +== license + +MIT + diff --git a/example_features/flow.feature b/example_features/flow.feature index 52876a9..0447f36 100644 --- a/example_features/flow.feature +++ b/example_features/flow.feature @@ -1,13 +1,13 @@ Feature: running the flow In order to blah Scenario: from a to b Given I have a ruote engine And the initial fields are "customer":"Alain" And the catchall participant is registered - And I launch the flow at example_features/flows/a_to_b.rb + And I launch the flow at example_flows/a_to_b.rb When I get the first workitem of participant alpha Then I should have a workitem diff --git a/example_features/flows/a_to_b.rb b/example_flows/a_to_b.rb similarity index 100% rename from example_features/flows/a_to_b.rb rename to example_flows/a_to_b.rb diff --git a/lib/ruote/cukes.rb b/lib/ruote/cukes.rb index 3faa6fc..47ff77c 100644 --- a/lib/ruote/cukes.rb +++ b/lib/ruote/cukes.rb @@ -1,10 +1,108 @@ +#-- +# Copyright (c) 2010, John Mettraux, [email protected] +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# Made in Japan. +#++ + require 'json' require 'ruote' -require 'ruote/cukes/vars' -require 'ruote/cukes/engine' -require 'ruote/cukes/launch' -require 'ruote/cukes/participants' -require 'ruote/cukes/workitems' + +# a variable container in a singleton, or something like that +# +module Ruote +module Cukes + + def self.method_missing (m, *args) + m = m.to_s + if args.size == 1 && mm = m.match(/^(.+)=$/) + (@vars ||= {})[mm[1]] = args.first + elsif args.size == 0 + (@vars ||= {})[m] + else + super + end + end +end +end + + +# +# ENGINE + +Given /I have a ruote engine/ do + + Ruote::Cukes.engine = + Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) +end + + +# +# LAUNCH + +Given /the initial fields are (.+)$/ do |fields| + + fields = "{#{fields}}" unless fields.match(/^{.+}$/) + + Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) +end + +Given /the initial variables are (.+)$/ do |vars| + + vars = "{#{vars}}" unless vars.match(/^{.+}$/) + + Ruote::Cukes.launch_variables = Rufus::Json.decode(vars) +end + +Given /I launch the flow at (.+)$/ do |path| + + Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( + path, + Ruote::Cukes.launch_fields || {}, + Ruote::Cukes.lannch_variables || {}) +end + + +# +# PARTICIPANTS + +Given /the catch[- ]?all participant is registered/ do + + Ruote::Cukes.storage_participant = + Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) +end + +When /I get the first workitem of participant (.+)$/ do |pname| + + Ruote::Cukes.workitem = + Ruote::Cukes.storage_participant.by_participant(pname).first +end + + +# +# WORKITEMS + +Then /I should have a workitem/ do + + Ruote::Cukes.workitem.should.not.be.nil +end diff --git a/lib/ruote/cukes/engine.rb b/lib/ruote/cukes/engine.rb deleted file mode 100644 index 6ee6d15..0000000 --- a/lib/ruote/cukes/engine.rb +++ /dev/null @@ -1,31 +0,0 @@ -#-- -# Copyright (c) 2010, John Mettraux, [email protected] -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Made in Japan. -#++ - - -Given /I have a ruote engine/ do - - Ruote::Cukes.engine = - Ruote::Engine.new(Ruote::Worker.new(Ruote::HashStorage.new())) -end - diff --git a/lib/ruote/cukes/launch.rb b/lib/ruote/cukes/launch.rb deleted file mode 100644 index d5d0351..0000000 --- a/lib/ruote/cukes/launch.rb +++ /dev/null @@ -1,40 +0,0 @@ -#-- -# Copyright (c) 2010, John Mettraux, [email protected] -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Made in Japan. -#++ - - -Given /the initial fields are (.+)$/ do |fields| - - fields = "{#{fields}}" unless fields.match(/^{.+}$/) - - Ruote::Cukes.launch_fields = Rufus::Json.decode(fields) -end - -Given /I launch the flow at (.+)$/ do |path| - - Ruote::Cukes.last_wfid = Ruote::Cukes.engine.launch( - path, - Ruote::Cukes.launch_fields || {}, - Ruote::Cukes.lannch_variables || {}) -end - diff --git a/lib/ruote/cukes/participants.rb b/lib/ruote/cukes/participants.rb deleted file mode 100644 index 3cd4ab6..0000000 --- a/lib/ruote/cukes/participants.rb +++ /dev/null @@ -1,37 +0,0 @@ -#-- -# Copyright (c) 2010, John Mettraux, [email protected] -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Made in Japan. -#++ - - -Given /the catch[- ]?all participant is registered/ do - - Ruote::Cukes.storage_participant = - Ruote::Cukes.engine.register_participant('.+', Ruote::StorageParticipant) -end - -When /I get the first workitem of participant (.+)$/ do |pname| - - Ruote::Cukes.workitem = - Ruote::Cukes.storage_participant.by_participant(pname).first -end - diff --git a/lib/ruote/cukes/vars.rb b/lib/ruote/cukes/vars.rb deleted file mode 100644 index 201a03c..0000000 --- a/lib/ruote/cukes/vars.rb +++ /dev/null @@ -1,41 +0,0 @@ -#-- -# Copyright (c) 2010, John Mettraux, [email protected] -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Made in Japan. -#++ - - -module Ruote -module Cukes - - def self.method_missing (m, *args) - m = m.to_s - if args.size == 1 && mm = m.match(/^(.+)=$/) - (@vars ||= {})[mm[1]] = args.first - elsif args.size == 0 - (@vars ||= {})[m] - else - super - end - end -end -end - diff --git a/lib/ruote/cukes/workitems.rb b/lib/ruote/cukes/workitems.rb deleted file mode 100644 index 5ce0d17..0000000 --- a/lib/ruote/cukes/workitems.rb +++ /dev/null @@ -1,30 +0,0 @@ -#-- -# Copyright (c) 2010, John Mettraux, [email protected] -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Made in Japan. -#++ - - -Then /I should have a workitem/ do - - Ruote::Cukes.workitem.should.not.be.nil -end -
Rainer/scm-visualizer
4d7432bb28d753de18769b1652d7073e48683670
glip and git support
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f268c6c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "glip"] + path = glip + url = http://github.com/patrikf/glip.git diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0017ff1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + +GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + +NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/glip b/glip new file mode 160000 index 0000000..6291efe --- /dev/null +++ b/glip @@ -0,0 +1 @@ +Subproject commit 6291efee820b81b15d9789285a5f6a90a5bf4152
Rainer/scm-visualizer
be639640ba6103c309886f9eab63f2095993ec97
Multiple config support
diff --git a/conf/config.php.template b/conf/config.php.template index 8e567ad..0f43d9e 100644 --- a/conf/config.php.template +++ b/conf/config.php.template @@ -1,20 +1,52 @@ <?php +require_once('lib/config_object.php'); +/// Configuration is stored in a named array +$conf=array(); + // Choose type of scm (git,svn,....) // There needs to be a class in the lib folder to handle the scm commands! // Read lib/scm-interface.php for interface definition -$scm_type='svn'; -$scm_username='USERNAME'; -$scm_password='PASSWORD'; -$scm_url='http://URL.TLD/PROJECT'; -$scm_limit=1000; // max number of commits -$scm_getpaths=false; // get all modified paths -> slow but needed for calc_files +$c=new config_object; + +$c->scm_type='svn'; +$c->scm_username=''; +$c->scm_password=''; +$c->scm_url=''; +$c->scm_limit=10000; // max number of commits +$c->scm_getpaths=false; // get all modified paths -> needed for calc_files + +// Calculation plugin +$c->calc_type='commit'; + +// Visualization plugin +$c->visual_type='standard'; +$c->visual_width=800; +$c->visual_height=200; +$c->visual_fontsize=4; +$c->visual_header=''; // leave empty for calc based setting + +// add to config +$conf["svn"]=$c; + +// git +$c=new config_object; + +$c->scm_type='git'; +$c->scm_username=''; +$c->scm_password=''; +$c->scm_url=''; +$c->scm_limit=10000; // max number of commits +$c->scm_getpaths=false; // get all modified paths -> needed for calc_files // Calculation plugin -$calc_type="commit"; +$c->calc_type='commit'; // Visualization plugin -$visual_type="standard"; -$visual_width=400; -$visual_height=80; -$visual_fontsize=6; -$visual_header=''; // leave empty for calc based setting +$c->visual_type='standard'; +$c->visual_width=800; +$c->visual_height=200; +$c->visual_fontsize=4; +$c->visual_header=''; // leave empty for calc based setting + +// add to config +$conf["git"]=$c; diff --git a/index.html b/index.html index a1efc0c..7e65a0a 100644 --- a/index.html +++ b/index.html @@ -1,15 +1,24 @@ <html> <head> <title>scm-visualizer</title> </head> <body> -Visualization of commits in an scm<br> +Visualization of commits in a svn scm<br> <br> By commit:<br> <img src="plot.php" alt="by commit"><br> By author:<br> <img src="plot.php?calc_type=author" alt="by commit"><br> By files:<br> <img src="plot.php?calc_type=files" alt="by changed files"><br> +<br> +Visualization of commits in a git scm<br> +<br> +By commit:<br> +<img src="plot.php?conf=git" alt="by commit"><br> +By author:<br> +<img src="plot.php?conf=git&calc_type=author" alt="by commit"><br> +By files:<br> +<img src="plot.php?conf=git&calc_type=files" alt="by changed files"><br> </body> </html> diff --git a/plot.php b/plot.php index b926bc7..6016d08 100644 --- a/plot.php +++ b/plot.php @@ -1,52 +1,87 @@ <?php // Config check if (!file_exists('conf/config.php')) { die('You need to create conf/config.php from template conf/config.php.template!'); } // require config require_once('conf/config.php'); +// Which config should be used? +if (array_key_exists('conf', $_GET)) +{ + $useconf=$_GET['conf']; +} else { + // No config object given -> use first one + if (count($conf>1)) + { + $useconf=key($conf); + } else { + die('Not configured! Please check your configuration!'); + } +} + +// Get config vars +if (array_key_exists($useconf,$conf)) +{ + $scm_type=$conf[$useconf]->scm_type; + $scm_username=$conf[$useconf]->scm_username; + $scm_password=$conf[$useconf]->scm_password; + $scm_url=$conf[$useconf]->scm_url; + $scm_limit=$conf[$useconf]->scm_limit; + $scm_getpaths=$conf[$useconf]->scm_getpaths; + + $calc_type=$conf[$useconf]->calc_type; + + $visual_type=$conf[$useconf]->visual_type; + $visual_width=$conf[$useconf]->visual_width; + $visual_height=$conf[$useconf]->visual_height; + $visual_fontsize=$conf[$useconf]->visual_fontsize; + $visual_header=$conf[$useconf]->visual_header; +} else { + die('Config object '.$useconf.' not found!'); +} + // Read url options if (array_key_exists('calc_type', $_GET)) { $calc_type=$_GET['calc_type']; if ($calc_type=='files') { $scm_getpaths=true; } } // get scm management class require_once('lib/scm_' . $scm_type . '.php'); // Calculator require_once('lib/calc_' . $calc_type . '.php'); // Visualizer require_once('lib/visual_' . $visual_type . '.php'); // login $scm=new scm; $scm::Login(); // get data $log=$scm::GetLog(); // calculate $calc=new calc; $data=$calc->Calculate($log); // Get header text if ($visual_header=='') { $visual_header=$calc->GetHeader(); } // visualize $visual=new visual; $visual->CreatePng($data); ?>
Rainer/scm-visualizer
23b07da4b2bac310ee5cca17a638f9ff1b31f1c7
Bugfix get paths bei svn für calc_files, Sortierung korrigiert
diff --git a/index.html b/index.html index 6178368..a1efc0c 100644 --- a/index.html +++ b/index.html @@ -1,13 +1,15 @@ <html> <head> <title>scm-visualizer</title> </head> <body> Visualization of commits in an scm<br> <br> By commit:<br> <img src="plot.php" alt="by commit"><br> By author:<br> <img src="plot.php?calc_type=author" alt="by commit"><br> +By files:<br> +<img src="plot.php?calc_type=files" alt="by changed files"><br> </body> </html> diff --git a/lib/calc_author.php b/lib/calc_author.php index 9e97fa6..0f3e650 100644 --- a/lib/calc_author.php +++ b/lib/calc_author.php @@ -1,30 +1,35 @@ <?php require_once('calc_interface.php'); // Calculate visualdata class calc implements calc_interface { // Calculate public function Calculate($log) { $data=array(); foreach ($log as $ent) { // Add commit to date $author=$ent->scm_author; if (array_key_exists($author, $data)) { $data[$author] += 1; } else { $data[$author] = 1; } } + + // Sort array + ksort($data); + + // Return data return $data; } // Header text public function GetHeader() { return "Visualized by number of commits by author"; } } diff --git a/lib/calc_files.php b/lib/calc_files.php new file mode 100644 index 0000000..a48bc92 --- /dev/null +++ b/lib/calc_files.php @@ -0,0 +1,56 @@ +<?php +require_once('calc_interface.php'); + +// Calculate visualdata +class calc implements calc_interface +{ + // Calculate + public function Calculate($log) + { + $data=array(); + foreach ($log as $ent) + { + // Add commit to date + $date=$ent->scm_date; + if (array_key_exists($date, $data)) + { + $data[$date] += $ent->scm_files; + } else { + $data[$date] = $ent->scm_files; + } + } + + // get first entry + reset($data); + $first=DateTime::createFromFormat('Ymd', key($data)); + + // Get last entry + end($data); + $last=DateTime::createFromFormat('Ymd', key($data)); + + // Create missing date values + $current=$first; + $day=new DateInterval('P1D'); + while ($current<$last) { + $curd=$current->format('Ymd'); + if (!array_key_exists($curd, $data)) + { + $data[$curd]=0; + } + // get next date + $current=$current->add($day); + } + + // Sort by key + ksort($data); + + // Return sorted result + return $data; + } + + // Header text + public function GetHeader() + { + return "Visualized by number of changed files per date"; + } +} diff --git a/lib/scm_svn.php b/lib/scm_svn.php index 61985a8..94524c4 100644 --- a/lib/scm_svn.php +++ b/lib/scm_svn.php @@ -1,55 +1,55 @@ <?php require_once('scm_interface.php'); require_once('scm_logentry.php'); // svn scm class class scm implements scm_interface { // Login public function Login() { global $scm_username,$scm_password; // do login svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, $scm_username); svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, $scm_password); } // get log public function GetLog() { global $scm_url,$scm_getpaths,$scm_limit; // Set flags $flags = 0; - if (!$scm_getpaths) + if ($scm_getpaths) { $flags=$flags|SVN_DISCOVER_CHANGED_PATHS; } // get log $svnlog=svn_log($scm_url,SVN_REVISION_INITIAL,SVN_REVISION_HEAD,$scm_limit,$flags); $returnarray=array(); foreach ($svnlog as $ent) { if (array_key_exists('paths',$ent)) { $files = count($ent['paths']); } else { $files = 0; } // Get date and time $date=substr($ent['date'],0,4).substr($ent['date'],5,2).substr($ent['date'],8,2); $time=substr($ent['date'],11,8); $aent = new scm_logentry($ent['rev'], $ent['author'], $date, $time, $files, $ent['msg']); $returnarray[] = $aent; } $svnlog=null; // quick and dirty return $returnarray; } } diff --git a/lib/visual_standard.php b/lib/visual_standard.php index 04c1855..4e5fad8 100644 --- a/lib/visual_standard.php +++ b/lib/visual_standard.php @@ -1,110 +1,114 @@ <?php require_once('visual_interface.php'); // Standard visualization class visual implements visual_interface { public function CreatePng($data) { global $visual_width, $visual_height, $visual_header; // Create image $img = imagecreate($visual_width,$visual_height); // set some colors $background = imagecolorallocate( $img, 220, 220, 220 ); $text_color = imagecolorallocate( $img, 0, 0, 0 ); $line_color = imagecolorallocate( $img, 128, 255, 0 ); $plot_color = imagecolorallocate( $img, 180, 180, 0 ); // get min and max $min = 0; $max = max($data); + // Avoid DIV + if ($max==0) $max=1; + // number of entries $numentries=count($data); // Fonts $font_header=2; $font_mark=1; $font_footer=1; // Font dimensions $fontheight_header=imagefontheight($font_header); $fontheight_mark=imagefontheight($font_mark); $fontheight_footer=imagefontheight($font_footer); // set borders $border=20; $bordertop=4+$fontheight_header; $borderbottom=4+$fontheight_footer; // Get maxX and maxY $maxX=$visual_width-2*$border-2; $maxY=$visual_height-$bordertop-$borderbottom-2; $singlesizeX=$maxX/$numentries; //$singlesizeY=$maxy/$max; // Header centerd $text_width = imagefontwidth($font_header)*strlen($visual_header); $center = ceil($visual_width / 2); $x = $center - (ceil($text_width/2)); // Write header imagestring($img, $font_header, $x, 2, $visual_header, $text_color); // min and max commit lines imageline($img, $border, $bordertop, $visual_width-$border, $bordertop, $line_color); imageline($img, $border, $visual_height-$borderbottom, $visual_width-$border, $visual_height-$borderbottom, $line_color); // min and max values imagestring($img, $font_mark, $border-$fontheight_mark/2, $bordertop-$fontheight_mark/2, $max, $text_color); - imagestring($img, $font_mark, $border-$fontheight_mark/2, $visual_height-$border-$fontheight_mark/2, $min, $text_color); + imagestring($img, $font_mark, $border-$fontheight_mark/2, $visual_height-$borderbottom-$fontheight_mark/2, $min, $text_color); // process entries $i=0; $lastX=0; // End of last footer foreach ($data as $key=>$c) { // get x coordinates $sx=$border+$i*$singlesizeX+2; $ex=$sx+$singlesizeX; // get y coordinates $sy=$bordertop+$maxY-(($c*$maxY)/$max)+2; $ey=$bordertop+$maxY; // plot rectangle imagefilledrectangle($img, $sx, $sy, $ex, $ey, $plot_color); // next $i++; // set footer if it does not overwrite existing one if ($sx>$lastX+5) { $footertextwidth=imagefontwidth($font_footer)*strlen($key); if ($sx+$footertextwidth<$border+$maxX) { $lastX=$sx+$footertextwidth; imagestring($img, $font_footer, $sx, $ey+4, $key, $text_color); } } } // set image header header('Content-type: image/png'); // Create png imagepng($img); + // deallocate colors imagecolordeallocate($img, $line_color); imagecolordeallocate($img, $text_color); imagecolordeallocate($img, $plot_color); imagecolordeallocate($img, $background); // cleanup memory imagedestroy($img); } } diff --git a/plot.php b/plot.php index bea080d..b926bc7 100644 --- a/plot.php +++ b/plot.php @@ -1,48 +1,52 @@ <?php // Config check if (!file_exists('conf/config.php')) { die('You need to create conf/config.php from template conf/config.php.template!'); } // require config require_once('conf/config.php'); // Read url options if (array_key_exists('calc_type', $_GET)) { $calc_type=$_GET['calc_type']; + if ($calc_type=='files') + { + $scm_getpaths=true; + } } // get scm management class require_once('lib/scm_' . $scm_type . '.php'); // Calculator require_once('lib/calc_' . $calc_type . '.php'); // Visualizer require_once('lib/visual_' . $visual_type . '.php'); // login $scm=new scm; $scm::Login(); // get data $log=$scm::GetLog(); // calculate $calc=new calc; $data=$calc->Calculate($log); // Get header text if ($visual_header=='') { $visual_header=$calc->GetHeader(); } // visualize $visual=new visual; $visual->CreatePng($data); ?>
Rainer/scm-visualizer
d87fb4fe61207bd196f0c71bca322fd18fbb9d59
calc-commit Datumslücken gefüllt
diff --git a/lib/calc_commit.php b/lib/calc_commit.php index a161036..d6c9d30 100644 --- a/lib/calc_commit.php +++ b/lib/calc_commit.php @@ -1,31 +1,56 @@ <?php require_once('calc_interface.php'); // Calculate visualdata class calc implements calc_interface { // Calculate public function Calculate($log) { $data=array(); foreach ($log as $ent) { // Add commit to date $date=$ent->scm_date; if (array_key_exists($date, $data)) { $data[$date] += 1; } else { $data[$date] = 1; } } - // TODO: fillup dates here - no commit on a date within min and max will result in a wrong graph + + // get first entry + reset($data); + $first=DateTime::createFromFormat('Ymd', key($data)); + + // Get last entry + end($data); + $last=DateTime::createFromFormat('Ymd', key($data)); + + // Create missing date values + $current=$first; + $day=new DateInterval('P1D'); + while ($current<$last) { + $curd=$current->format('Ymd'); + if (!array_key_exists($curd, $data)) + { + $data[$curd]=0; + } + // get next date + $current=$current->add($day); + } + + // Sort by key + ksort($data); + + // Return sorted result return $data; } // Header text public function GetHeader() { return "Visualized by number of commits per date"; } }
Rainer/scm-visualizer
4b073825bbfc291defde06b94fbaebff812bf420
Initial version of scm-visualizer
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..92bfeac --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +conf/config.php diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..2c0f3fe --- /dev/null +++ b/README.txt @@ -0,0 +1,11 @@ +Author: Andreas Rehm <[email protected]> +Licensed by GPLv2 + +scm-visualizer + +PHP scripts to visualize source code management commits. You can write libraries to connect to any scm. Subversion and git will be provided. + +You can although change the library for calculation and the library for creating the graph. + +URL overrides will be implemented. Existing overrides: +calc_type= you can switch the calc_type with the url (e.g. commit or author) diff --git a/conf/config.php.template b/conf/config.php.template new file mode 100644 index 0000000..8e567ad --- /dev/null +++ b/conf/config.php.template @@ -0,0 +1,20 @@ +<?php +// Choose type of scm (git,svn,....) +// There needs to be a class in the lib folder to handle the scm commands! +// Read lib/scm-interface.php for interface definition +$scm_type='svn'; +$scm_username='USERNAME'; +$scm_password='PASSWORD'; +$scm_url='http://URL.TLD/PROJECT'; +$scm_limit=1000; // max number of commits +$scm_getpaths=false; // get all modified paths -> slow but needed for calc_files + +// Calculation plugin +$calc_type="commit"; + +// Visualization plugin +$visual_type="standard"; +$visual_width=400; +$visual_height=80; +$visual_fontsize=6; +$visual_header=''; // leave empty for calc based setting diff --git a/index.html b/index.html new file mode 100644 index 0000000..6178368 --- /dev/null +++ b/index.html @@ -0,0 +1,13 @@ +<html> +<head> +<title>scm-visualizer</title> +</head> +<body> +Visualization of commits in an scm<br> +<br> +By commit:<br> +<img src="plot.php" alt="by commit"><br> +By author:<br> +<img src="plot.php?calc_type=author" alt="by commit"><br> +</body> +</html> diff --git a/lib/calc_author.php b/lib/calc_author.php new file mode 100644 index 0000000..9e97fa6 --- /dev/null +++ b/lib/calc_author.php @@ -0,0 +1,30 @@ +<?php +require_once('calc_interface.php'); + +// Calculate visualdata +class calc implements calc_interface +{ + // Calculate + public function Calculate($log) + { + $data=array(); + foreach ($log as $ent) + { + // Add commit to date + $author=$ent->scm_author; + if (array_key_exists($author, $data)) + { + $data[$author] += 1; + } else { + $data[$author] = 1; + } + } + return $data; + } + + // Header text + public function GetHeader() + { + return "Visualized by number of commits by author"; + } +} diff --git a/lib/calc_commit.php b/lib/calc_commit.php new file mode 100644 index 0000000..a161036 --- /dev/null +++ b/lib/calc_commit.php @@ -0,0 +1,31 @@ +<?php +require_once('calc_interface.php'); + +// Calculate visualdata +class calc implements calc_interface +{ + // Calculate + public function Calculate($log) + { + $data=array(); + foreach ($log as $ent) + { + // Add commit to date + $date=$ent->scm_date; + if (array_key_exists($date, $data)) + { + $data[$date] += 1; + } else { + $data[$date] = 1; + } + } + // TODO: fillup dates here - no commit on a date within min and max will result in a wrong graph + return $data; + } + + // Header text + public function GetHeader() + { + return "Visualized by number of commits per date"; + } +} diff --git a/lib/calc_interface.php b/lib/calc_interface.php new file mode 100644 index 0000000..c55ae4a --- /dev/null +++ b/lib/calc_interface.php @@ -0,0 +1,13 @@ +<?php +// There must be the following values +//$calc_type='commit'; + +// Interface definition for scm access +interface calc_interface +{ + // Calculate + public function Calculate($log); + + // Get header text + public function GetHeader(); +} diff --git a/lib/scm_interface.php b/lib/scm_interface.php new file mode 100644 index 0000000..1379c5f --- /dev/null +++ b/lib/scm_interface.php @@ -0,0 +1,22 @@ +<?php +// There must be the following values +//$scm_type='svn'; +//$scm_user='username'; +//$scm_pass='password' +//$scm_url='http://my.url/repopath' + +// Interface definition for scm access +interface scm_interface +{ + + // Login + public function Login(); + + // get log + // should return an array of scm_logentry + public function GetLog(); + + // get diff + + // get stats +} diff --git a/lib/scm_logentry.php b/lib/scm_logentry.php new file mode 100644 index 0000000..b800745 --- /dev/null +++ b/lib/scm_logentry.php @@ -0,0 +1,27 @@ +<?php +// scm logentry class interface +class scm_logentry +{ + // id + public $scm_id; + // user + public $scm_author; + // date + public $scm_date; + // time + public $scm_time; + // number of files + public $scm_files; + // logentry + public $scm_log; + + public function __construct($id='', $author='', $date='', $time=time, $files=0, $log='') + { + $this->scm_id=$id; + $this->scm_author=$author; + $this->scm_date=$date; + $this->scm_time=$time; + $this->scm_files=$files; + $this->scm_log=$log; + } +} diff --git a/lib/scm_svn.php b/lib/scm_svn.php new file mode 100644 index 0000000..61985a8 --- /dev/null +++ b/lib/scm_svn.php @@ -0,0 +1,55 @@ +<?php +require_once('scm_interface.php'); +require_once('scm_logentry.php'); + +// svn scm class +class scm implements scm_interface +{ + // Login + public function Login() + { + global $scm_username,$scm_password; + + // do login + svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, $scm_username); + svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, $scm_password); + } + + // get log + public function GetLog() + { + global $scm_url,$scm_getpaths,$scm_limit; + + // Set flags + $flags = 0; + if (!$scm_getpaths) + { + $flags=$flags|SVN_DISCOVER_CHANGED_PATHS; + } + + // get log + $svnlog=svn_log($scm_url,SVN_REVISION_INITIAL,SVN_REVISION_HEAD,$scm_limit,$flags); + + $returnarray=array(); + + foreach ($svnlog as $ent) + { + if (array_key_exists('paths',$ent)) + { + $files = count($ent['paths']); + } else { + $files = 0; + } + // Get date and time + $date=substr($ent['date'],0,4).substr($ent['date'],5,2).substr($ent['date'],8,2); + $time=substr($ent['date'],11,8); + $aent = new scm_logentry($ent['rev'], $ent['author'], $date, $time, $files, $ent['msg']); + + $returnarray[] = $aent; + } + $svnlog=null; + + // quick and dirty + return $returnarray; + } +} diff --git a/lib/visual_interface.php b/lib/visual_interface.php new file mode 100644 index 0000000..3bca78d --- /dev/null +++ b/lib/visual_interface.php @@ -0,0 +1,10 @@ +<?php +// There must be the following values +//$visual_type='standard'; + +// Interface definition for scm access +interface visual_interface +{ + // Login + public function CreatePng($data); +} diff --git a/lib/visual_standard.php b/lib/visual_standard.php new file mode 100644 index 0000000..04c1855 --- /dev/null +++ b/lib/visual_standard.php @@ -0,0 +1,110 @@ +<?php +require_once('visual_interface.php'); + +// Standard visualization +class visual implements visual_interface +{ + public function CreatePng($data) + { + global $visual_width, $visual_height, $visual_header; + + // Create image + $img = imagecreate($visual_width,$visual_height); + + // set some colors + $background = imagecolorallocate( $img, 220, 220, 220 ); + $text_color = imagecolorallocate( $img, 0, 0, 0 ); + $line_color = imagecolorallocate( $img, 128, 255, 0 ); + $plot_color = imagecolorallocate( $img, 180, 180, 0 ); + + // get min and max + $min = 0; + $max = max($data); + + // number of entries + $numentries=count($data); + + // Fonts + $font_header=2; + $font_mark=1; + $font_footer=1; + + // Font dimensions + $fontheight_header=imagefontheight($font_header); + $fontheight_mark=imagefontheight($font_mark); + $fontheight_footer=imagefontheight($font_footer); + + // set borders + $border=20; + $bordertop=4+$fontheight_header; + $borderbottom=4+$fontheight_footer; + + // Get maxX and maxY + $maxX=$visual_width-2*$border-2; + $maxY=$visual_height-$bordertop-$borderbottom-2; + $singlesizeX=$maxX/$numentries; + //$singlesizeY=$maxy/$max; + + // Header centerd + $text_width = imagefontwidth($font_header)*strlen($visual_header); + $center = ceil($visual_width / 2); + $x = $center - (ceil($text_width/2)); + + // Write header + imagestring($img, $font_header, $x, 2, $visual_header, $text_color); + + // min and max commit lines + imageline($img, $border, $bordertop, $visual_width-$border, $bordertop, $line_color); + imageline($img, $border, $visual_height-$borderbottom, $visual_width-$border, $visual_height-$borderbottom, $line_color); + + // min and max values + imagestring($img, $font_mark, $border-$fontheight_mark/2, $bordertop-$fontheight_mark/2, $max, $text_color); + imagestring($img, $font_mark, $border-$fontheight_mark/2, $visual_height-$border-$fontheight_mark/2, $min, $text_color); + + // process entries + $i=0; + $lastX=0; // End of last footer + + foreach ($data as $key=>$c) + { + // get x coordinates + $sx=$border+$i*$singlesizeX+2; + $ex=$sx+$singlesizeX; + + // get y coordinates + $sy=$bordertop+$maxY-(($c*$maxY)/$max)+2; + $ey=$bordertop+$maxY; + + // plot rectangle + imagefilledrectangle($img, $sx, $sy, $ex, $ey, $plot_color); + + // next + $i++; + + // set footer if it does not overwrite existing one + if ($sx>$lastX+5) + { + $footertextwidth=imagefontwidth($font_footer)*strlen($key); + if ($sx+$footertextwidth<$border+$maxX) + { + $lastX=$sx+$footertextwidth; + imagestring($img, $font_footer, $sx, $ey+4, $key, $text_color); + } + } + } + + // set image header + header('Content-type: image/png'); + + // Create png + imagepng($img); + // deallocate colors + imagecolordeallocate($img, $line_color); + imagecolordeallocate($img, $text_color); + imagecolordeallocate($img, $plot_color); + imagecolordeallocate($img, $background); + + // cleanup memory + imagedestroy($img); + } +} diff --git a/plot.php b/plot.php new file mode 100644 index 0000000..bea080d --- /dev/null +++ b/plot.php @@ -0,0 +1,48 @@ +<?php + +// Config check +if (!file_exists('conf/config.php')) +{ + die('You need to create conf/config.php from template conf/config.php.template!'); +} + +// require config +require_once('conf/config.php'); + +// Read url options +if (array_key_exists('calc_type', $_GET)) +{ + $calc_type=$_GET['calc_type']; +} + +// get scm management class +require_once('lib/scm_' . $scm_type . '.php'); + +// Calculator +require_once('lib/calc_' . $calc_type . '.php'); + +// Visualizer +require_once('lib/visual_' . $visual_type . '.php'); + +// login +$scm=new scm; +$scm::Login(); + +// get data +$log=$scm::GetLog(); + +// calculate +$calc=new calc; +$data=$calc->Calculate($log); + +// Get header text +if ($visual_header=='') +{ + $visual_header=$calc->GetHeader(); +} + +// visualize +$visual=new visual; +$visual->CreatePng($data); + +?>
tredoe/wizard
758f783eb056e7412c11c0e69a93f9d8d144e03b
Remove ioutil for v1.16
diff --git a/config.go b/config.go index 5ce5058..3e027c1 100644 --- a/config.go +++ b/config.go @@ -1,223 +1,222 @@ // Copyright 2010 Jonas mg // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package wizard import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" "strings" "text/template" "github.com/tredoe/dat/valid" "gopkg.in/yaml.v1" ) // Conf represents the configuration of the project. type Conf struct { Project string Program string // to lower case License string Author string Email string VCS string Org string // the author develops the program for an organization Import string // To get data from user configuration; then is sent to ImportPaths ImportPaths []string // To pass to templates ImportPath string Comment string FullLicense string GNUextra string ProjectHeader string Year int } // SetNames sets names for both project and program. // // A program name is named as the project name but in lower case. func (c *Conf) SetNames() error { c.Project = strings.TrimSpace(c.Project) c.Program = strings.ToLower(c.Project) // To remove them from the program name, if any. reStart1 := regexp.MustCompile(`^go-`) reStart2 := regexp.MustCompile(`^go`) reEnd1 := regexp.MustCompile(`-go$`) reEnd2 := regexp.MustCompile(`go$`) if reStart1.MatchString(c.Program) { c.Program = reStart1.ReplaceAllString(c.Program, "") } else if reStart2.MatchString(c.Program) { c.Program = reStart2.ReplaceAllString(c.Program, "") } else if reEnd1.MatchString(c.Program) { c.Program = reEnd1.ReplaceAllString(c.Program, "") } else if reEnd2.MatchString(c.Program) { c.Program = reEnd2.ReplaceAllString(c.Program, "") } return nil } // // == User configuration // AddConfig creates the user configuration file. func (cfg *Conf) AddConfig() error { tmpl := template.Must(template.New("Config").Parse(tmplUserConfig)) home := os.Getenv("HOME") if home == "" { return errors.New("could not add user configuration file because $HOME is not set") } file, err := createFile(filepath.Join(home, _USER_CONFIG)) if err != nil { return err } cfg.ImportPath = strings.Join(cfg.ImportPaths, ":") if err := tmpl.Execute(file, cfg); err != nil { return fmt.Errorf("execution failed: %s", err) } return nil } // UserConfig loads configuration per user, if any. func (c *Conf) UserConfig() error { home := os.Getenv("HOME") if home == "" { return fmt.Errorf("environment variable $HOME is not set") } pathUserConfig := filepath.Join(home, _USER_CONFIG) // To know if the file exist. switch info, err := os.Stat(pathUserConfig); { case os.IsNotExist(err): return nil case !info.Mode().IsRegular(): return fmt.Errorf("expected regular file: %s", _USER_CONFIG) } - data, err := ioutil.ReadFile(pathUserConfig) + data, err := os.ReadFile(pathUserConfig) if err != nil { return err } cfg := Conf{} if err = yaml.Unmarshal([]byte(data), &cfg); err != nil { return fmt.Errorf("error parsing configuration: %s", err) } // == Get values if c.Org == "" && cfg.Org != "" { c.Org = cfg.Org } if c.Author == "" && cfg.Author != "" { c.Author = cfg.Author } if c.Email == "" && cfg.Email != "" { c.Email = cfg.Email } if c.License == "" && cfg.License != "" { c.License = cfg.License } if c.VCS == "" && cfg.VCS != "" { c.VCS = cfg.VCS } if len(c.ImportPaths) == 0 && cfg.Import != "" { c.ImportPaths = strings.Split(cfg.Import, ":") } return nil } // == Checking // // PreCheck checks the initial configuration, setting some values. func (c *Conf) PreCheck(interactive, addConfig bool) error { var required []string if !interactive { if !addConfig { if err := c.SetNames(); err != nil { return err } } // == Necessary fields if addConfig { required = []string{c.Author, c.Email, c.License, c.VCS} } else { required = []string{c.Project, c.Program, c.License, c.Author, c.Email, c.VCS} } for _, v := range required { if v == "" { return errors.New("missing required field") } } } // == Maps // License if c.License != "" { c.License = strings.ToLower(c.License) if _, ok := ListLowerLicense[c.License]; !ok { return fmt.Errorf("unavailable license: %q", c.License) } } // VCS if c.VCS != "" { c.VCS = strings.ToLower(c.VCS) if _, ok := ListVCS[c.VCS]; !ok { return fmt.Errorf("unavailable VCS: %q", c.VCS) } } return nil } // PostCheck checks and sets to be run after of.get configuration. func (c *Conf) PostCheck(interactive, addConfig bool) error { // Email if !interactive { _, err := valid.Email(). SetScheme(valid.NewScheme().Required()). Check(c.Email) if err != nil { return err } } c.Email = fmt.Sprintf("%s <%s>", c.Author, strings.Replace(c.Email, "@", " AT ", -1)) // Adds extra fields to pass to templates. if !addConfig { c.ProjectHeader = strings.Repeat(_HEADER_CHAR, len(c.Project)) if c.License != "none" { c.FullLicense = ListLicense[ListLowerLicense[c.License]] } } return nil } diff --git a/util.go b/util.go index aa522eb..9a5e47a 100644 --- a/util.go +++ b/util.go @@ -1,69 +1,68 @@ // Copyright 2010 Jonas mg // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package wizard import ( "bufio" "fmt" - "io/ioutil" "os" "path/filepath" ) // copyFile copies a file from source to destination. func copyFile(destination, source string) error { - src, err := ioutil.ReadFile(source) + src, err := os.ReadFile(source) if err != nil { return fmt.Errorf("copy error reading: %s", err) } - err = ioutil.WriteFile(destination, src, _FILE_PERM) + err = os.WriteFile(destination, src, _FILE_PERM) if err != nil { return fmt.Errorf("copy error writing: %s", err) } return nil } // createFile creates a file. func createFile(dst string) (*os.File, error) { file, err := os.Create(dst) if err != nil { return nil, fmt.Errorf("file error: %s", err) } if err = file.Chmod(_FILE_PERM); err != nil { return nil, fmt.Errorf("file error: %s", err) } return file, nil } // getProjectName returns the project name from Readme file. // It should be in the first line. func getProjectName() (string, error) { info, err := os.Stat(_README) if os.IsNotExist(err) { info, err = os.Stat(filepath.Join("..", _README)) if os.IsNotExist(err) { return "", fmt.Errorf("file %s not found", _README) } } file, err := os.Open(info.Name()) if err != nil { return "", err } defer file.Close() buf := bufio.NewReader(file) line, _, err := buf.ReadLine() if err != nil { return "", err } return string(line), nil }
tredoe/wizard
ad923d89d19bf330c97c38dd4edc5c8bec646538
Initial
diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..1a575d3 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,16 @@ +# Authors + +This is the official list of authors for copyright purposes. +This file is distinct from the 'CONTRIBUTORS' file. See the latter for an explanation. + +Names should be added to this file as: + + Name or Organization <email address> / (url address) + +(The email address is not required for organizations) + +Please keep the list sorted. + +## Code + +* Jonas mg (https://github.com/tredoe) \ No newline at end of file diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..879ecc2 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,18 @@ +# Contributors + +This is the official list of people who can contribute (and typically +have contributed) to the repository. + +The 'AUTHORS' file lists the copyright holders; this file lists people. For +example, the employees of an organization are listed here but not in 'AUTHORS', +because the organization holds the copyright. + +Names should be added to this file as: + + Name <email address> / (url address) + +Please keep the list sorted. + +## Code + +* Jonas mg (https://github.com/tredoe) \ No newline at end of file diff --git a/LICENSE-MPL.txt b/LICENSE-MPL.txt new file mode 100644 index 0000000..52d1351 --- /dev/null +++ b/LICENSE-MPL.txt @@ -0,0 +1,374 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..8c32b96 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +Gowizard +======== +Tool to create skeleton of Go projects. + +[Documentation online](http://godoc.org/github.com/tredoe/wizard/gowizard) + +#### Maintenance of programs + +Copyright notices only need the year when the file was created, so don't add new +years. + + +## Installation + + go get github.com/tredoe/wizard/gowizard + +To only install the package, which could be used by a Go IDE: + + go get github.com/tredoe/wizard + +## License + +Unless otherwise noted: + ++ The source files are distributed under the *Mozilla Public License, version 2.0* + diff --git a/config.go b/config.go new file mode 100644 index 0000000..5ce5058 --- /dev/null +++ b/config.go @@ -0,0 +1,223 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package wizard + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "regexp" + "strings" + "text/template" + + "github.com/tredoe/dat/valid" + "gopkg.in/yaml.v1" +) + +// Conf represents the configuration of the project. +type Conf struct { + Project string + Program string // to lower case + License string + Author string + Email string + VCS string + Org string // the author develops the program for an organization + Import string // To get data from user configuration; then is sent to ImportPaths + ImportPaths []string + + // To pass to templates + ImportPath string + Comment string + FullLicense string + GNUextra string + ProjectHeader string + Year int +} + +// SetNames sets names for both project and program. +// +// A program name is named as the project name but in lower case. +func (c *Conf) SetNames() error { + c.Project = strings.TrimSpace(c.Project) + c.Program = strings.ToLower(c.Project) + + // To remove them from the program name, if any. + reStart1 := regexp.MustCompile(`^go-`) + reStart2 := regexp.MustCompile(`^go`) + reEnd1 := regexp.MustCompile(`-go$`) + reEnd2 := regexp.MustCompile(`go$`) + + if reStart1.MatchString(c.Program) { + c.Program = reStart1.ReplaceAllString(c.Program, "") + } else if reStart2.MatchString(c.Program) { + c.Program = reStart2.ReplaceAllString(c.Program, "") + } else if reEnd1.MatchString(c.Program) { + c.Program = reEnd1.ReplaceAllString(c.Program, "") + } else if reEnd2.MatchString(c.Program) { + c.Program = reEnd2.ReplaceAllString(c.Program, "") + } + + return nil +} + +// +// == User configuration + +// AddConfig creates the user configuration file. +func (cfg *Conf) AddConfig() error { + tmpl := template.Must(template.New("Config").Parse(tmplUserConfig)) + + home := os.Getenv("HOME") + if home == "" { + return errors.New("could not add user configuration file because $HOME is not set") + } + + file, err := createFile(filepath.Join(home, _USER_CONFIG)) + if err != nil { + return err + } + + cfg.ImportPath = strings.Join(cfg.ImportPaths, ":") + + if err := tmpl.Execute(file, cfg); err != nil { + return fmt.Errorf("execution failed: %s", err) + } + return nil +} + +// UserConfig loads configuration per user, if any. +func (c *Conf) UserConfig() error { + home := os.Getenv("HOME") + if home == "" { + return fmt.Errorf("environment variable $HOME is not set") + } + + pathUserConfig := filepath.Join(home, _USER_CONFIG) + + // To know if the file exist. + switch info, err := os.Stat(pathUserConfig); { + case os.IsNotExist(err): + return nil + case !info.Mode().IsRegular(): + return fmt.Errorf("expected regular file: %s", _USER_CONFIG) + } + + data, err := ioutil.ReadFile(pathUserConfig) + if err != nil { + return err + } + + cfg := Conf{} + if err = yaml.Unmarshal([]byte(data), &cfg); err != nil { + return fmt.Errorf("error parsing configuration: %s", err) + } + + // == Get values + + if c.Org == "" && cfg.Org != "" { + c.Org = cfg.Org + } + if c.Author == "" && cfg.Author != "" { + c.Author = cfg.Author + } + if c.Email == "" && cfg.Email != "" { + c.Email = cfg.Email + } + if c.License == "" && cfg.License != "" { + c.License = cfg.License + } + if c.VCS == "" && cfg.VCS != "" { + c.VCS = cfg.VCS + } + if len(c.ImportPaths) == 0 && cfg.Import != "" { + c.ImportPaths = strings.Split(cfg.Import, ":") + } + + return nil +} + +// == Checking +// + +// PreCheck checks the initial configuration, setting some values. +func (c *Conf) PreCheck(interactive, addConfig bool) error { + var required []string + + if !interactive { + if !addConfig { + if err := c.SetNames(); err != nil { + return err + } + } + + // == Necessary fields + if addConfig { + required = []string{c.Author, c.Email, c.License, c.VCS} + } else { + required = []string{c.Project, c.Program, c.License, c.Author, + c.Email, c.VCS} + } + + for _, v := range required { + if v == "" { + return errors.New("missing required field") + } + } + } + + // == Maps + + // License + if c.License != "" { + c.License = strings.ToLower(c.License) + + if _, ok := ListLowerLicense[c.License]; !ok { + return fmt.Errorf("unavailable license: %q", c.License) + } + } + + // VCS + if c.VCS != "" { + c.VCS = strings.ToLower(c.VCS) + + if _, ok := ListVCS[c.VCS]; !ok { + return fmt.Errorf("unavailable VCS: %q", c.VCS) + } + } + + return nil +} + +// PostCheck checks and sets to be run after of.get configuration. +func (c *Conf) PostCheck(interactive, addConfig bool) error { + // Email + if !interactive { + _, err := valid.Email(). + SetScheme(valid.NewScheme().Required()). + Check(c.Email) + if err != nil { + return err + } + } + + c.Email = fmt.Sprintf("%s <%s>", + c.Author, strings.Replace(c.Email, "@", " AT ", -1)) + + // Adds extra fields to pass to templates. + if !addConfig { + c.ProjectHeader = strings.Repeat(_HEADER_CHAR, len(c.Project)) + + if c.License != "none" { + c.FullLicense = ListLicense[ListLowerLicense[c.License]] + } + } + + return nil +} diff --git a/data/AGPL.txt b/data/AGPL.txt new file mode 100644 index 0000000..a871fcf --- /dev/null +++ b/data/AGPL.txt @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<http://www.gnu.org/licenses/>. + diff --git a/data/Apache.txt b/data/Apache.txt new file mode 100644 index 0000000..57bc88a --- /dev/null +++ b/data/Apache.txt @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/data/CC0.txt b/data/CC0.txt new file mode 100644 index 0000000..71d5e8e --- /dev/null +++ b/data/CC0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL + SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT + RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" + BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS + DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS + LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE + INFORMATION OR WORKS PROVIDED HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of authorship +and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific works +("Commons") that the public can reliably and without fear of later claims of +infringement build upon, modify, incorporate in other works, reuse and +redistribute as freely as possible in any form whatsoever and for any purposes, +including without limitation commercial purposes. These owners may contribute to +the Commons to promote the ideal of a free culture and the further production of +creative, cultural and scientific works, or to gain reputation or greater +distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of +additional consideration or compensation, the person associating CC0 with a Work +(the "Affirmer"), to the extent that he or she is an owner of Copyright and +Related Rights in the Work, voluntarily elects to apply CC0 to the Work and +publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and Related +Rights"). Copyright and Related Rights include, but are not limited to, the +following: + + 1. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + 2. moral rights retained by the original author(s) and/or performer(s); + + 3. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + 4. rights protecting against unfair competition in regards to a Work, subject + to the limitations in paragraph 4(a), below; + + 5. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + 6. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + 7. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and +Related Rights and associated claims and causes of action, whether now known or +unknown (including existing as well as future claims and causes of action), in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit +of each member of the public at large and to the detriment of Affirmer's heirs +and successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public as +contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, non +transferable, non sublicensable, non exclusive, irrevocable and unconditional +license to exercise Affirmer's Copyright and Related Rights in the Work (i) in +all territories worldwide, (ii) for the maximum duration provided by applicable +law or treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional purposes +(the "License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any reason +be judged legally invalid or ineffective under applicable law, such partial +invalidity or ineffectiveness shall not invalidate the remainder of the License, +and in such case Affirmer hereby affirms that he or she will not (i) exercise +any of his or her remaining Copyright and Related Rights in the Work or (ii) +assert any associated claims and causes of action with respect to the Work, in +either case contrary to Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + 1. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + 2. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or other + defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + 3. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions or + other rights required for any use of the Work. + + 4. Affirmer understands and acknowledges that Creative Commons is not a party + to this document and has no duty or obligation with respect to this CC0 or + use of the Work. + diff --git a/data/GPL.txt b/data/GPL.txt new file mode 100644 index 0000000..10926e8 --- /dev/null +++ b/data/GPL.txt @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. + diff --git a/data/MPL.txt b/data/MPL.txt new file mode 100644 index 0000000..52d1351 --- /dev/null +++ b/data/MPL.txt @@ -0,0 +1,374 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + diff --git a/gowizard/doc.go b/gowizard/doc.go new file mode 100644 index 0000000..dce192f --- /dev/null +++ b/gowizard/doc.go @@ -0,0 +1,37 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* +Command gowizard creates the base for new Go projects, adds the license header +to source code files, and creates a file ignore for the VCS given. + +The file ignore has been configured to ignore files finished in "~" (used like +backups in Unix), the ones started with "." (hidden files in Unix), and the +ones started with "_" to have files that don't be committed. It also ignores +files got from compiling and linking. + + +Configuration + +To don't repeat the same every time you create a project, you could use an user +configuration file in your home directory to have values by default. + + gowizard -i -cfg + +Create project + +By default, the program name (flag *-program*) is named as the project name but +in lower case, and removing the name "Go" of the prefix and suffix. + +The flag -import is the import path of your project, but you must substitute the +project name by "$" since Gowizard uses it to add the name automatically. For +example: *github.com/tredoe/$* + +The way fastest and simple to create it, is using the interactive mode: + + gowizard -i +*/ +package main diff --git a/gowizard/gowizard.go b/gowizard/gowizard.go new file mode 100644 index 0000000..4446774 --- /dev/null +++ b/gowizard/gowizard.go @@ -0,0 +1,313 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package main + +import ( + "flag" + "fmt" + "os" + "strings" + + "github.com/tredoe/dat/question" + "github.com/tredoe/dat/valid" + "github.com/tredoe/goutil/cmdutil" + "github.com/tredoe/wizard" +) + +type importPaths []string + +func (i *importPaths) String() string { + if len(*i) == 0 { + return `""` + } + return fmt.Sprint(*i) +} + +func (i *importPaths) Set(value string) error { + *i = make([]string, 0) + + for _, v := range strings.Split(value, ":") { + *i = append(*i, strings.TrimSpace(v)) + } + return nil +} + +var fImportPath importPaths + +func init() { + flag.Var(&fImportPath, "import", "base of import path (i.e. github.com/tredoe); colon-separated list") +} + +// * * * + +func usage() { + fmt.Fprintf(os.Stderr, `Usage: gowizard -i [-cfg] + +`) + flag.PrintDefaults() + os.Exit(2) +} + +func main() { + cfg, err := initConfig() + if err != nil { + cmdutil.Fatal(err) + } + if cfg == nil { + os.Exit(0) + } + + p, err := wizard.NewProject(cfg) + if err != nil { + cmdutil.Fatal(err) + } + + if err = p.Create(); err != nil { + cmdutil.Fatal(err) + } +} + +// * * * + +// initConfig loads configuration from flags and user configuration. +// Returns the configuration to nil when it is used the flag "cfg". +func initConfig() (*wizard.Conf, error) { + var ( + fName = flag.String("name", "", "project name") + fLicense = flag.String("license", "", "license covering the program") + fAuthor = flag.String("author", "", "author's name") + fEmail = flag.String("email", "", "author's email") + fVCS = flag.String("vcs", "", "version control system") + fOrg = flag.String("org", "", "organization holder of the copyright") + + fConfig = flag.Bool("cfg", false, "add the user configuration file") + fInteractive = flag.Bool("i", false, "interactive mode") + + // Listing + fListLicense = flag.Bool("ll", false, "list the available licenses (for license flag)") + fListVCS = flag.Bool("lv", false, "list the available version control systems (for vcs flag)") + ) + + // == Parse the flags + flag.Usage = usage + flag.Parse() + + if flag.NFlag() == 0 { + usage() + } + + // == Listing + if *fListLicense { + maxLen := 0 + for _, v := range wizard.ListLicenseSorted { + if len(v) > maxLen { + maxLen = len(v) + } + } + + fmt.Print(" = Licenses\n\n") + for _, v := range wizard.ListLicenseSorted { + fmt.Printf(" %s: %s%s\n", + v, strings.Repeat(" ", maxLen-len(v)), wizard.ListLicense[v], + ) + } + } + if *fListVCS { + maxLen := 0 + for _, v := range wizard.ListVCSsorted { + if len(v) > maxLen { + maxLen = len(v) + } + } + + fmt.Print(" = Version control systems\n\n") + for _, v := range wizard.ListVCSsorted { + fmt.Printf(" %s: %s%s\n", + v, strings.Repeat(" ", maxLen-len(v)), wizard.ListVCS[v], + ) + } + } + + if *fListLicense || *fListVCS { + return nil, nil + } + + var err error + cfg := &wizard.Conf{ + Program: *fName, + License: *fLicense, + Author: *fAuthor, + Email: *fEmail, + VCS: *fVCS, + ImportPaths: fImportPath, + Org: *fOrg, + } + + // Get configuration per user, if any. + if !*fConfig { + if err = cfg.UserConfig(); err != nil { + return nil, err + } + } + cfg.Project = *fName + + if err = cfg.PreCheck(*fInteractive, *fConfig); err != nil { + return nil, err + } + // Interactive mode + if *fInteractive { + if err = interactive(cfg, *fConfig); err != nil { + return nil, err + } + } + if err = cfg.PostCheck(*fInteractive, *fConfig); err != nil { + return nil, err + } + + // Add configuration. + if *fConfig && *fInteractive { + cfg.AddConfig() + return nil, nil + } + + return cfg, nil +} + +// interactive uses the interactive mode. +func interactive(c *wizard.Conf, addConfig bool) (err error) { + var sFlags []string + var msg string + + // == Sorted flags + if addConfig { + msg = "New configuration" + sFlags = []string{"author", "email", "license", "vcs", "import", "org"} + } else { + msg = "New project" + sFlags = []string{ + "name", + "org", + "author", + "email", + "license", + "vcs", + "import", + } + } + + q := question.New() + defer func() { + err2 := q.Restore() + if err2 != nil && err == nil { + err = err2 + } + }() + + fmt.Printf("\n = Gowizard :: %s\n\n", msg) + + for _, k := range sFlags { + f := flag.Lookup(k) + + if strings.Contains(f.Usage, ";") { + f.Usage = strings.SplitN(f.Usage, ";", 2)[0] + } + f.Usage = strings.ToUpper(string(f.Usage[0])) + f.Usage[1:] + + switch k { + case "name": + q.Prompt(f.Usage, + valid.String().SetStringCheck(valid.S_Strict), + valid.NewScheme().Required().SetDefault(c.Project), + ) + c.Project, err = q.ReadString() + + if err = c.SetNames(); err != nil { + return err + } + case "org": + isOrg := true + + if c.Org == "" { + q.Prompt("Is for an organization?", + valid.Bool(), + valid.NewScheme().SetDefault(false), + ) + isOrg, err = q.ReadBool() + } + + if isOrg { + q.Prompt(f.Usage, + valid.String(), + valid.NewScheme().Required().SetDefault(c.Org), + ) + c.Org, err = q.ReadString() + } + case "author": + q.Prompt(f.Usage, + valid.String().SetStringCheck(valid.S_Strict), + valid.NewScheme().Required().SetDefault(c.Author), + ) + c.Author, err = q.ReadString() + case "email": + q.Prompt(f.Usage, + valid.Email(), + valid.NewScheme().Required().SetDefault(c.Email), + ) + c.Email, err = q.ReadString() + case "license": + q.Prompt(f.Usage, + valid.String(), + valid.NewScheme().SetDefault(wizard.ListLowerLicense[c.License]), + ) + c.License, err = q.ChoiceString(wizard.ListLicenseSorted) + // It is got in upper case + c.License = strings.ToLower(c.License) + case "vcs": + q.Prompt(f.Usage, + valid.String(), + valid.NewScheme().SetDefault(c.VCS), + ) + c.VCS, err = q.ChoiceString(wizard.ListVCSsorted) + case "import": + if addConfig { + q.Prompt(f.Usage, + valid.String(), + valid.NewScheme().Required(), + ) + c.ImportPaths, err = q.ReadStringSlice() + + } else if len(c.ImportPaths) == 0 { + tmp := "" + + q.Prompt(f.Usage, + valid.String(), + nil, + ) + tmp, err = q.ReadString() + + if tmp != "" { + c.ImportPaths = make([]string, 1) + c.ImportPaths[0] = tmp + } + + } else { + q.Prompt(f.Usage, + valid.String(), + valid.NewScheme().SetDefault(c.ImportPaths[0]), + ) + c.ImportPaths[0], err = q.ChoiceString(c.ImportPaths) + } + } + + if err != nil { + return err + } + } + + fmt.Println() + return nil +} diff --git a/template.go b/template.go new file mode 100644 index 0000000..4b60c9d --- /dev/null +++ b/template.go @@ -0,0 +1,350 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package wizard + +import ( + "fmt" + "path/filepath" + "strings" + "text/template" + "time" +) + +// Copyright +const ( + tmplCopyright = `Copyright {{.Year}} {{.Author}}` + tmplCopyleft = `Written in {{.Year}} by {{.Author}}` + + tmplOrgCopyright = `Copyright {{.Year}} The {{.Project}} Authors` + tmplOrgCopyleft = `Written in {{.Year}} by the {{.Project}} Authors` +) + +// Licenses +const ( + tmplNone = `{{.Comment}} {{template "Copyright" .}} +` + + tmplApache = `{{.Comment}} {{template "Copyright" .}} +{{.Comment}} +{{.Comment}} Licensed under the Apache License, Version 2.0 (the "License"); +{{.Comment}} you may not use this file except in compliance with the License. +{{.Comment}} You may obtain a copy of the License at +{{.Comment}} +{{.Comment}} http://www.apache.org/licenses/LICENSE-2.0 +{{.Comment}} +{{.Comment}} Unless required by applicable law or agreed to in writing, software +{{.Comment}} distributed under the License is distributed on an "AS IS" BASIS, +{{.Comment}} WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +{{.Comment}} See the License for the specific language governing permissions and +{{.Comment}} limitations under the License. +` + + tmplGNU = `{{.Comment}} {{template "Copyright" .}} +{{.Comment}} +{{.Comment}} This program is free software: you can redistribute it and/or modify +{{.Comment}} it under the terms of the GNU {{with .GNUextra}}{{.}} {{end}}General Public License as published by +{{.Comment}} the Free Software Foundation, either version 3 of the License, or +{{.Comment}} (at your option) any later version. +{{.Comment}} +{{.Comment}} This program is distributed in the hope that it will be useful, +{{.Comment}} but WITHOUT ANY WARRANTY; without even the implied warranty of +{{.Comment}} MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +{{.Comment}} GNU {{with .GNUextra}}{{.}} {{end}}General Public License for more details. +{{.Comment}} +{{.Comment}} You should have received a copy of the GNU {{with .GNUextra}}{{.}} {{end}}General Public License +{{.Comment}} along with this program. If not, see <http://www.gnu.org/licenses/>. +` + + tmplMPL = `{{.Comment}} {{template "Copyright" .}} +{{.Comment}} +{{.Comment}} This Source Code Form is subject to the terms of the Mozilla Public +{{.Comment}} License, v. 2.0. If a copy of the MPL was not distributed with this +{{.Comment}} file, You can obtain one at http://mozilla.org/MPL/2.0/. +` + + tmplCC0 = `{{.Comment}} {{template "Copyright" .}} +{{.Comment}} +{{.Comment}} To the extent possible under law, the author(s) have waived all copyright +{{.Comment}} and related or neighboring rights to this work to the public domain worldwide. +{{.Comment}} This software is distributed without any warranty. +{{.Comment}} +{{.Comment}} You should have received a copy of the CC0 Public Domain Dedication along +{{.Comment}} with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. +` +) + +// Base of source files +const ( + tmplGo = `{{template "Header" .}} +package {{.Program}} + +import ( + +) + + +` + + tmplTest = `{{template "Header" .}} +package {{.Program}} + +import "testing" + +func Test(t *testing.T) { + +} +` + + tmplExample = `{{template "Header" .}} +package {{.Program}}_test + +import ( + "fmt" + + "{{.ImportPath}}" +) + +func Example() { + fmt.Println() + // Output: + // +} +` +) + +// User configuration +const tmplUserConfig = ` +org: {{.Org}} +author: {{.Author}} +email: {{.Email}} +license: {{.License}} +vcs: {{.VCS}} +import: {{.ImportPath}} +` + +// Ignore file for VCS +const hgIgnoreTop = "syntax: glob\n" + +var tmplIgnore = `## Special files +*~ +[._]* + +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.[ao] +*.so +*.dll + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo?.* + +_testmain.go + +# Compiled Go source +*.exe +*.test +*.prof + +## Data +*.bin + +## Packages +# It's better to unpack these files and commit the raw source since +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +## Logs and databases +*.db +*.log +*.sql +*.sqlite + +## OS generated files +Icon? + +# * * * +{{.Program}} +` + +// Information files +const ( + tmplAuthors = ` +This is the official list of **{{.Project}}** authors for copyright purposes. +This file is distinct from the 'CONTRIBUTORS' file. See the latter for an explanation. + +Names should be added to this file as: + + Name or Organization <email address> + +(The email address is not required for organizations) + +Please keep the list sorted. +* * * + +{{with .Org}}{{.}}{{else}}{{.Email}}{{end}} + +` + + tmplContributors = ` +This is the official list of people who can contribute (and typically have +contributed) code to the **{{.Project}}** repository. + +The 'AUTHORS' file lists the copyright holders; this file lists people. For +example, the employees of an organization are listed here but not in 'AUTHORS', +because the organization holds the copyright. + +Names should be added to this file as: + + Name <email address> + +Please keep the list sorted. +* * * + +{{.Email}} + +` + + tmplChangelog = ` +This file documents the changes in **{{.Project}}** versions that are listed below. + +Items should be added to this file as: + + #### YYYY-MM-DD Release + One change. + Other change. + +* * * + + +` + + tmplReadme = `{{.Project}} +{{.ProjectHeader}} +<< PROJECT SYNOPSIS >> + +[Documentation online](http://godoc.org/{{with .ImportPath}}{{.}}{{else}}<< IMPORT PATH >>{{end}}) + +## Installation + + go get {{with .ImportPath}}{{.}}{{else}}<< IMPORT PATH >>{{end}} +{{if .FullLicense}} +## License + +Unless otherwise noted: + ++ The source files are distributed under the *{{.FullLicense}}* +{{end}} +* * * +*Generated by [Gowizard](https://github.com/tredoe/wizard)* +` +) + +// * * * + +// parseFromFile renders the template "src", creating a file in "dst". +func (p *project) parseFromFile(dst, src string) error { + file, err := createFile(dst) + if err != nil { + return err + } + + p.tmpl, err = p.tmpl.ParseFiles(src) + if err != nil { + return fmt.Errorf("parsing error: %s", err) + } + if err = p.tmpl.ExecuteTemplate(file, filepath.Base(src), p.cfg); err != nil { + return fmt.Errorf("execution failed: %s", err) + } + + return nil +} + +// parseFromVar renders the template "tmplName" to the file "dst". +func (p *project) parseFromVar(dst string, tmplName string) error { + file, err := createFile(dst) + if err != nil { + return err + } + + if err = p.tmpl.ExecuteTemplate(file, tmplName, p.cfg); err != nil { + return fmt.Errorf("execution failed: %s", err) + } + return nil +} + +// parseLicense parses the license header. +// charComment is the character used to comment in code files. +func (p *project) parseLicense(charComment string) { + licenseName := strings.Split(p.cfg.License, "-")[0] + tmplHeader := "" + + p.cfg.Comment = charComment + p.cfg.Year = time.Now().Year() + + switch licenseName { + case "mpl": + tmplHeader = tmplMPL + case "apache": + tmplHeader = tmplApache + case "cc0": + tmplHeader = tmplCC0 + case "gpl", "agpl": + tmplHeader = tmplGNU + + if licenseName == "agpl" { + p.cfg.GNUextra = "Affero" + } + case "none": + tmplHeader = tmplNone + } + + p.tmpl = template.Must(p.tmpl.New("Header").Parse(tmplHeader)) + + if licenseName != "cc0" { + if p.cfg.Org == "" { + p.tmpl = template.Must(p.tmpl.New("Copyright").Parse(tmplCopyright)) + } else { + p.tmpl = template.Must(p.tmpl.New("Copyright").Parse(tmplOrgCopyright)) + } + } else { + if p.cfg.Org == "" { + p.tmpl = template.Must(p.tmpl.New("Copyright").Parse(tmplCopyleft)) + } else { + p.tmpl = template.Must(p.tmpl.New("Copyright").Parse(tmplOrgCopyleft)) + } + } +} + +// parseProject parses the templates for the project. +func (p *project) parseProject() { + p.tmpl = template.Must(p.tmpl.New("Authors").Parse(tmplAuthors)) + p.tmpl = template.Must(p.tmpl.New("Contributors").Parse(tmplContributors)) + p.tmpl = template.Must(p.tmpl.New("Changelog").Parse(tmplChangelog)) + p.tmpl = template.Must(p.tmpl.New("Readme").Parse(tmplReadme)) + p.tmpl = template.Must(p.tmpl.New("Go").Parse(tmplGo)) + p.tmpl = template.Must(p.tmpl.New("Test").Parse(tmplTest)) + p.tmpl = template.Must(p.tmpl.New("Example").Parse(tmplExample)) + + // == Ignore file + if p.cfg.VCS == "hg" { + tmplIgnore = hgIgnoreTop + tmplIgnore + } + p.tmpl = template.Must(p.tmpl.New("Ignore").Parse(tmplIgnore)) +} diff --git a/util.go b/util.go new file mode 100644 index 0000000..aa522eb --- /dev/null +++ b/util.go @@ -0,0 +1,69 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package wizard + +import ( + "bufio" + "fmt" + "io/ioutil" + "os" + "path/filepath" +) + +// copyFile copies a file from source to destination. +func copyFile(destination, source string) error { + src, err := ioutil.ReadFile(source) + if err != nil { + return fmt.Errorf("copy error reading: %s", err) + } + + err = ioutil.WriteFile(destination, src, _FILE_PERM) + if err != nil { + return fmt.Errorf("copy error writing: %s", err) + } + + return nil +} + +// createFile creates a file. +func createFile(dst string) (*os.File, error) { + file, err := os.Create(dst) + if err != nil { + return nil, fmt.Errorf("file error: %s", err) + } + if err = file.Chmod(_FILE_PERM); err != nil { + return nil, fmt.Errorf("file error: %s", err) + } + + return file, nil +} + +// getProjectName returns the project name from Readme file. +// It should be in the first line. +func getProjectName() (string, error) { + info, err := os.Stat(_README) + if os.IsNotExist(err) { + info, err = os.Stat(filepath.Join("..", _README)) + if os.IsNotExist(err) { + return "", fmt.Errorf("file %s not found", _README) + } + } + + file, err := os.Open(info.Name()) + if err != nil { + return "", err + } + defer file.Close() + + buf := bufio.NewReader(file) + line, _, err := buf.ReadLine() + + if err != nil { + return "", err + } + return string(line), nil +} diff --git a/wizard.go b/wizard.go new file mode 100644 index 0000000..09cff90 --- /dev/null +++ b/wizard.go @@ -0,0 +1,190 @@ +// Copyright 2010 Jonas mg +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// Package wizard enables to create the base of new Go projects. +package wizard + +import ( + "fmt" + "go/build" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "text/template" +) + +const ( + // Permissions + _DIR_PERM = 0755 + _FILE_PERM = 0644 + + _COMMENT_CHAR = "//" // For comments in source code files + _HEADER_CHAR = "=" // Header under the project name + + // Subdirectory where is installed through "go get" + _DATA_PATH = "github.com/tredoe/wizard/data" + + _README = "README.md" + _USER_CONFIG = ".gowizard" // Configuration file per user +) + +// Version control systems (VCS) +var ( + ListVCSsorted = []string{"bzr", "git", "hg", "none"} + + ListVCS = map[string]string{ + "bzr": "Bazaar", + "git": "Git", + "hg": "Mercurial", + "none": "none", + } + + /*// VCS configuration files + listConfigVCS = map[string]string{ + "bzr": ".bzr/branch/branch.conf", + "git": ".git/config", + "hg": ".hg/hgrc", + }*/ +) + +// Available licenses +var ( + ListLicenseSorted = []string{"AGPL", "Apache", "CC0", "GPL", "MPL", "none"} + + ListLicense = map[string]string{ + "AGPL": "GNU Affero General Public License, version 3 or later", + "Apache": "Apache License, version 2.0", + "CC0": "Creative Commons CC0, version 1.0 Universal", + "GPL": "GNU General Public License, version 3 or later", + "MPL": "Mozilla Public License, version 2.0", + "none": "proprietary license", + } + ListLowerLicense = map[string]string{ + "agpl": "AGPL", + "apache": "Apache", + "cc0": "CC0", + "gpl": "GPL", + "mpl": "MPL", + "none": "none", + } +) + +// project represents all information to create a project. +type project struct { + dataDir string // directory with templates + tmpl *template.Template // set of templates + cfg *Conf +} + +// NewProject initializes information for a new project. +func NewProject(cfg *Conf) (*project, error) { + // To get the path of the templates directory. + pkg, err := build.Import(_DATA_PATH, build.Default.GOPATH, build.FindOnly) + if err != nil { + return nil, fmt.Errorf("NewProject: data directory not found: %s", err) + } + + return &project{pkg.Dir, new(template.Template), cfg}, nil +} + +// Create creates a new project. +func (p *project) Create() (err error) { + dirs := []string{ + p.cfg.Program, + filepath.Join(p.cfg.Program, "doc"), + filepath.Join(p.cfg.Program, "testdata"), + } + for _, v := range dirs { + if err = os.Mkdir(v, _DIR_PERM); err != nil { + return fmt.Errorf("directory error: %s", err) + } + } + + p.parseLicense(_COMMENT_CHAR) + p.parseProject() + + if len(p.cfg.ImportPaths) != 0 { + p.cfg.ImportPath = path.Join(p.cfg.ImportPaths[0], p.cfg.Program) + } + + // Render project files + + err = p.parseFromVar(filepath.Join(p.cfg.Program, p.cfg.Program)+".go", "Go") + if err != nil { + return err + } + err = p.parseFromVar(filepath.Join(p.cfg.Program, "_"+p.cfg.Program)+"_test.go", "Test") + if err != nil { + return err + } + err = p.parseFromVar(filepath.Join(p.cfg.Program, "_example_test.go"), "Example") + if err != nil { + return err + } + + // Add license file + + if p.cfg.License != "none" { + license := ListLowerLicense[p.cfg.License] + licenseDst := filepath.Join(p.cfg.Program, "LICENSE-"+license+".txt") + + err = copyFile(licenseDst, filepath.Join(p.dataDir, license+".txt")) + if err != nil { + return err + } + } + + // Render common files + + err = p.parseFromVar(filepath.Join(p.cfg.Program, _README), "Readme") + if err != nil { + return err + } + err = p.parseFromVar(filepath.Join(p.cfg.Program, "CONTRIBUTORS.txt.md"), "Contributors") + if err != nil { + return err + } + err = p.parseFromVar(filepath.Join(dirs[1], "_changelog.txt.md"), "Changelog") + if err != nil { + return err + } + + // The file AUTHORS is for copyright holders. + if p.cfg.License != "cc0" { + err = p.parseFromVar(filepath.Join(p.cfg.Program, "AUTHORS.txt.md"), "Authors") + if err != nil { + return err + } + } + + // == VCS + + if p.cfg.VCS != "none" { + ignoreFile := "." + p.cfg.VCS + "ignore" + if err = p.parseFromVar(filepath.Join(p.cfg.Program, ignoreFile), + "Ignore"); err != nil { + return err + } + + // Initialize VCS + out, err := exec.Command(p.cfg.VCS, "init", p.cfg.Program).CombinedOutput() + if err != nil { + return err + } + if out != nil { + out_ := string(out) + if wd, err := os.Getwd(); err == nil { + out_ = strings.Replace(out_, wd+string(os.PathSeparator), "", 1) + } + + fmt.Print(out_) + } + } + + return nil +}
PercyPeng/AndroidProxyDaemon
de9ed1cc5c657194cebba8ab932659337fd81045
Add README
diff --git a/README b/README new file mode 100644 index 0000000..01f9f0c --- /dev/null +++ b/README @@ -0,0 +1,7 @@ +This shows how to set proxy in Android. + +Like http Proxy,Socket Proxy,etc + +There including two methords to set proxy: +one is set the property of the Dalvik VM. +The other is new a Proxy() when open the url connection.
hgwr/dicbutton
77d17c984e8aa719eba801a614e11161ee6bc7ef
*** empty log message ***
diff --git a/build.sh b/build.sh index 27c13b3..91441b1 100644 --- a/build.sh +++ b/build.sh @@ -1,23 +1,23 @@ #!/bin/bash CHROME=/opt/google/chrome/google-chrome APP=dicbutton if [ \! -d build ]; then mkdir build fi git status echo " " echo -n "(build.sh) Continue ? (yes/No): " read ans if [ "$ans" != 'yes' ]; then echo "abort" exit fi git archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - -rm build/adb/.gitignore -rm build/adb/build.sh +rm "build/${APP}/.gitignore" +rm "build/${APP}/build.sh" echo $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem"
hgwr/dicbutton
dac3ad59f3f2cf3b265cf25069b2137e1f20870b
*** empty log message ***
diff --git a/manifest.json b/manifest.json index 46c3788..f9dbec2 100644 --- a/manifest.json +++ b/manifest.json @@ -1,12 +1,12 @@ { "name": "dicbutton", - "version": "0.2.1", + "version": "0.2.2", "description": "Adding Useful Buttons to Google Search", "update_url": "http://www.moreslowly.jp/chrome/extensions/dicbutton/updates.xml", "content_scripts": [ { "js": [ "dicbutton.js" ], "matches": [ "http://www.google.com/search*", "http://www.google.co.jp/search*" ], "run_at": "document_start" } ] }
hgwr/dicbutton
e56ce2ef9546b49c22f64975e309b2d4de131c8b
*** empty log message ***
diff --git a/dicbutton.js b/dicbutton.js index bd17288..8af13b3 100644 --- a/dicbutton.js +++ b/dicbutton.js @@ -1,57 +1,63 @@ // http://www.ohmiyapatriots.com/blog/2007/07/04/greasemonkey%E3%81%AE%E9%96%8B%E7%99%BA%E3%82%92%E3%81%BE%E3%81%A8%E3%82%81%E3%81%A6%E3%81%BF%E3%82%8B/ function getFirstElementByXPath(xpath, node) { node = node || document; var result = document.evaluate(xpath, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return result.singleNodeValue ? result.singleNodeValue : null; } function appendButton(name, value, listener, accessKey) { var nb = document.createElement("input"); var td = document.createElement("td"); nb.type = "button"; nb.name = name; nb.value = value; nb.accessKey = accessKey; nb.addEventListener("click", listener, true); td.appendChild(nb); getFirstElementByXPath('//form[@action="/search"]//tr').appendChild(td); return nb; } function onAlcClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://eow.alc.co.jp/" + q + "/UTF-8/"; } function onYdClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://dic.yahoo.co.jp/dsearch?enc=UTF-8&p=" + q + "&stype=0&dtype=2"; } function onWikipediaClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://ja.wikipedia.org/wiki/%E7%89%B9%E5%88%A5:Search?search=" + q; } function onWikipediaEnglishClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://en.wikipedia.org/wiki/Special:Search?search=" + q; } +function onGoogleEnglishClicked(e) { + var q = getFirstElementByXPath('//input[@name="q"]').value; + location.href = "http://www.google.com/search?complete=1&hl=en&safe=off&aq=f&q=" + q; +} + document.addEventListener("DOMContentLoaded", function () { + appendButton("engG", "G英", onGoogleEnglishClicked, "g"); appendButton("alcG", "ALC", onAlcClicked, "a"); appendButton("ydG", "Y辞", onYdClicked, "y"); appendButton("wikipediaG", "W", onWikipediaClicked, "w"); appendButton("wikipediaEnG", "W英", onWikipediaEnglishClicked, "e"); // フォーカスが document の外にあっても、 shift + alt + / でフィールドに戻る // getFirstElementByXPath('//input[@name="q"]').accessKey = "/"; でだめだったので、 // button を通すようにした。 var nb = appendButton("focusG", "", function (e) { getFirstElementByXPath('//input[@name="q"]').focus(); }, "/"); nb.style.height = "0px"; nb.style.width = "0px"; nb.style.border = "0px solid #fff"; });
hgwr/dicbutton
e10a395f49aeda6a10cfd9b40ac158e45008fa66
*** empty log message ***
diff --git a/build.sh b/build.sh index 3806ede..27c13b3 100644 --- a/build.sh +++ b/build.sh @@ -1,23 +1,23 @@ #!/bin/bash CHROME=/opt/google/chrome/google-chrome APP=dicbutton if [ \! -d build ]; then mkdir build fi git status echo " " echo -n "(build.sh) Continue ? (yes/No): " read ans if [ "$ans" != 'yes' ]; then echo "abort" exit fi -git-archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - +git archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - rm build/adb/.gitignore rm build/adb/build.sh echo $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem"
hgwr/dicbutton
d459261283d2d0e5a164c801daeecf4f0c8f14b2
Google の検索結果のページが変更されたことに対応
diff --git a/dicbutton.js b/dicbutton.js index 43b5e11..bd17288 100644 --- a/dicbutton.js +++ b/dicbutton.js @@ -1,55 +1,57 @@ // http://www.ohmiyapatriots.com/blog/2007/07/04/greasemonkey%E3%81%AE%E9%96%8B%E7%99%BA%E3%82%92%E3%81%BE%E3%81%A8%E3%82%81%E3%81%A6%E3%81%BF%E3%82%8B/ function getFirstElementByXPath(xpath, node) { node = node || document; var result = document.evaluate(xpath, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return result.singleNodeValue ? result.singleNodeValue : null; } function appendButton(name, value, listener, accessKey) { var nb = document.createElement("input"); + var td = document.createElement("td"); nb.type = "button"; nb.name = name; nb.value = value; nb.accessKey = accessKey; nb.addEventListener("click", listener, true); - getFirstElementByXPath('//input[@type="submit"]').parentNode.appendChild(nb); + td.appendChild(nb); + getFirstElementByXPath('//form[@action="/search"]//tr').appendChild(td); return nb; } function onAlcClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://eow.alc.co.jp/" + q + "/UTF-8/"; } function onYdClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://dic.yahoo.co.jp/dsearch?enc=UTF-8&p=" + q + "&stype=0&dtype=2"; } function onWikipediaClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://ja.wikipedia.org/wiki/%E7%89%B9%E5%88%A5:Search?search=" + q; } function onWikipediaEnglishClicked(e) { var q = getFirstElementByXPath('//input[@name="q"]').value; location.href = "http://en.wikipedia.org/wiki/Special:Search?search=" + q; } document.addEventListener("DOMContentLoaded", function () { appendButton("alcG", "ALC", onAlcClicked, "a"); appendButton("ydG", "Y辞", onYdClicked, "y"); appendButton("wikipediaG", "W", onWikipediaClicked, "w"); appendButton("wikipediaEnG", "W英", onWikipediaEnglishClicked, "e"); // フォーカスが document の外にあっても、 shift + alt + / でフィールドに戻る // getFirstElementByXPath('//input[@name="q"]').accessKey = "/"; でだめだったので、 // button を通すようにした。 var nb = appendButton("focusG", "", function (e) { getFirstElementByXPath('//input[@name="q"]').focus(); }, "/"); nb.style.height = "0px"; nb.style.width = "0px"; nb.style.border = "0px solid #fff"; });
hgwr/dicbutton
72381854494749ba055061a429ee9ebd92481003
*** empty log message ***
diff --git a/build.sh b/build.sh index 1dd86e2..3806ede 100644 --- a/build.sh +++ b/build.sh @@ -1,11 +1,23 @@ #!/bin/bash CHROME=/opt/google/chrome/google-chrome APP=dicbutton if [ \! -d build ]; then mkdir build fi +git status +echo " " +echo -n "(build.sh) Continue ? (yes/No): " +read ans +if [ "$ans" != 'yes' ]; then + echo "abort" + exit +fi + git-archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - -# $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem" +rm build/adb/.gitignore +rm build/adb/build.sh + +echo $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem"
hgwr/dicbutton
11147f97a33243050161eadbc4ac4fd2611a726d
*** empty log message ***
diff --git a/build.sh b/build.sh index 75b16d4..1dd86e2 100644 --- a/build.sh +++ b/build.sh @@ -1,11 +1,11 @@ #!/bin/bash CHROME=/opt/google/chrome/google-chrome APP=dicbutton -if [ -d build ]; then +if [ \! -d build ]; then mkdir build fi git-archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - # $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem"
hgwr/dicbutton
013f0f37af57fb480016bf3b9781dfe2698e1587
*** empty log message ***
diff --git a/manifest.json b/manifest.json index c8810d0..89a8e0e 100644 --- a/manifest.json +++ b/manifest.json @@ -1,12 +1,12 @@ { "name": "dicbutton", - "version": "0.1", + "version": "0.2", "description": "Adding Useful Buttons to Google Search", "update_url": "http://www.moreslowly.jp/chrome/extensions/dicbutton/updates.xml", "content_scripts": [ { "js": [ "dicbutton.js" ], "matches": [ "http://www.google.com/search*", "http://www.google.co.jp/search*" ], "run_at": "document_start" } ] }
hgwr/dicbutton
5710dea1c545c44ddbaf68bbe9a574f49288725a
*** empty log message ***
diff --git a/.gitignore b/.gitignore index 4d2077a..72370ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *~ *_flymake.js +build/*
hgwr/dicbutton
5a0932f33c5a45c45983fa1004ef33a184e1f122
*** empty log message ***
diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..75b16d4 --- /dev/null +++ b/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +CHROME=/opt/google/chrome/google-chrome +APP=dicbutton + +if [ -d build ]; then + mkdir build +fi + +git-archive --format=tar --prefix="build/${APP}/" HEAD | tar xvf - +# $CHROME --pack-extension="build/${APP}" --pack-extension-key="../${APP}.pem"
hgwr/dicbutton
6df9c6f50e30ac37ceaeae7d22481867562491f2
*** empty log message ***
diff --git a/manifest.json b/manifest.json index f0f1fc8..c8810d0 100644 --- a/manifest.json +++ b/manifest.json @@ -1,12 +1,12 @@ { "name": "dicbutton", "version": "0.1", - "description": "Add dictionary buttons to Google home page", + "description": "Adding Useful Buttons to Google Search", "update_url": "http://www.moreslowly.jp/chrome/extensions/dicbutton/updates.xml", "content_scripts": [ { "js": [ "dicbutton.js" ], "matches": [ "http://www.google.com/search*", "http://www.google.co.jp/search*" ], "run_at": "document_start" } ] }
hgwr/dicbutton
6f3b25df5c50e91fe3ec1b98c7725ce5ce924ba8
*** empty log message ***
diff --git a/manifest.json b/manifest.json index c031d7a..f0f1fc8 100644 --- a/manifest.json +++ b/manifest.json @@ -1,11 +1,12 @@ { "name": "dicbutton", "version": "0.1", "description": "Add dictionary buttons to Google home page", + "update_url": "http://www.moreslowly.jp/chrome/extensions/dicbutton/updates.xml", "content_scripts": [ { "js": [ "dicbutton.js" ], "matches": [ "http://www.google.com/search*", "http://www.google.co.jp/search*" ], "run_at": "document_start" } ] }
hgwr/dicbutton
a282150cab678b950ea4c542ae984c495e828a37
initial version
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d2077a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*~ +*_flymake.js diff --git a/dicbutton.js b/dicbutton.js new file mode 100644 index 0000000..43b5e11 --- /dev/null +++ b/dicbutton.js @@ -0,0 +1,55 @@ +// http://www.ohmiyapatriots.com/blog/2007/07/04/greasemonkey%E3%81%AE%E9%96%8B%E7%99%BA%E3%82%92%E3%81%BE%E3%81%A8%E3%82%81%E3%81%A6%E3%81%BF%E3%82%8B/ +function getFirstElementByXPath(xpath, node) { + node = node || document; + var result = document.evaluate(xpath, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); + return result.singleNodeValue ? result.singleNodeValue : null; +} + +function appendButton(name, value, listener, accessKey) { + var nb = document.createElement("input"); + nb.type = "button"; + nb.name = name; + nb.value = value; + nb.accessKey = accessKey; + nb.addEventListener("click", listener, true); + getFirstElementByXPath('//input[@type="submit"]').parentNode.appendChild(nb); + return nb; +} + +function onAlcClicked(e) { + var q = getFirstElementByXPath('//input[@name="q"]').value; + location.href = "http://eow.alc.co.jp/" + q + "/UTF-8/"; +} + +function onYdClicked(e) { + var q = getFirstElementByXPath('//input[@name="q"]').value; + location.href = "http://dic.yahoo.co.jp/dsearch?enc=UTF-8&p=" + q + "&stype=0&dtype=2"; +} + +function onWikipediaClicked(e) { + var q = getFirstElementByXPath('//input[@name="q"]').value; + location.href = "http://ja.wikipedia.org/wiki/%E7%89%B9%E5%88%A5:Search?search=" + q; +} + +function onWikipediaEnglishClicked(e) { + var q = getFirstElementByXPath('//input[@name="q"]').value; + location.href = "http://en.wikipedia.org/wiki/Special:Search?search=" + q; +} + +document.addEventListener("DOMContentLoaded", + function () { + appendButton("alcG", "ALC", onAlcClicked, "a"); + appendButton("ydG", "Y辞", onYdClicked, "y"); + appendButton("wikipediaG", "W", onWikipediaClicked, "w"); + appendButton("wikipediaEnG", "W英", onWikipediaEnglishClicked, "e"); + + // フォーカスが document の外にあっても、 shift + alt + / でフィールドに戻る + // getFirstElementByXPath('//input[@name="q"]').accessKey = "/"; でだめだったので、 + // button を通すようにした。 + var nb = appendButton("focusG", "", function (e) { + getFirstElementByXPath('//input[@name="q"]').focus(); + }, "/"); + nb.style.height = "0px"; + nb.style.width = "0px"; + nb.style.border = "0px solid #fff"; + }); diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..c031d7a --- /dev/null +++ b/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "dicbutton", + "version": "0.1", + "description": "Add dictionary buttons to Google home page", + "content_scripts": [ { + "js": [ "dicbutton.js" ], + "matches": [ "http://www.google.com/search*", + "http://www.google.co.jp/search*" ], + "run_at": "document_start" + } ] +}
shahriarhaque/kobalt
745c35a86f8a24580e2e95a0baf15e3faf414354
initial import
diff --git a/ChangeLog.txt b/ChangeLog.txt new file mode 100644 index 0000000..3c7be76 --- /dev/null +++ b/ChangeLog.txt @@ -0,0 +1,126 @@ +22/03/2010 Shahriar Haque <[email protected]> + +* Refactor + 1) Moved the lighting, network and physics packages to the + experimental package. + + 2) Moved all tester-related graphics to the tester/resources. + +18/12/2008 Shahriar Haque <[email protected]> + +* AbstractGame.java + 1) In the main game loop, the time interval between each iteration is + calculated. This value is available staticly to all classes through + a variable called interval. + +* GameEntity.java / AdvancedGameEntity.java + 1) x and y coordinates have been changed to be of double type. All + drawing and bounding operations now cast x and y before using them. + + 2) x_velocity and y_velocity will, from now on, indicate velocities + in pixels per second. The update method has been changed to reflect + this change of semantics. Instead of directly incrementing x and y + with x_velocity and y_velocity, the increments are linearly + interpolated using the value of interval from the AbstractGame class. + + 3) A field called UPDATE_INTERVAL has been added to the class. This + variable indicates how often to advance to the next frame. The update + method has been updated to calculate the time elapsed since the last + update. If this time is greater than or equal to the UPDATE_INTERVAL, + the frame is advanced to the next one. + +* Utilities.java + 1) Added flipVertical and flipHorizontal methods. Each method has two + versions. One operates on a single BufferedImage, the other on an array + of BufferedImages. + +* FadeEffect.java (new) + 1) This class can render fade in or fade out animations on a given + BufferedImage or a GameEntity for a given duration. Once started + the effects will continue till the set duration. After that a done + flag becomes true. This is how a calling class knows when the + animation has ended. An instance of this class can be reset to + prepare for another run of animation. + +* BlurEffect.java (new) + 1) This class contains a static applyEffect method that renders a + blurred version of the given BufferedImage or the current frame of + the given GameEntity. The class, by default, uses a built-in 3x3 + kernel for the operation. However, this kernel and its dimensions + can be changed. However, this class can currently only accept square + matrices as kernels. + +06/12/2008 Shahriar Haque <[email protected]> + +* GameScreen.java + 1) This abstract class now holds abstract definitions of update and + render. This class also manages its own list objects that require + keyboard and mouse support. The function of this class is to model + in game screens (e.g. Game menu, pause menu, inventory etc). The + AbstractGame class manages the sequencing and invoking of the methods + of this class. + +* AbstractGame.java + 1) addKeyboardSupport(), addMouseSupport(), keyboard listener methods, + mouse listener methods, update and render have been moved to the + GameScreen class. An ArrayList of GameScreen objects has been added. + This maintains a collections of all the screens related to the game. + A static integer index has been added to indicate the the index of + the currentScreen within the ArrayList. AbstractGame itself now extends + GameScreen. This allows old games to run without any changes. The main + game loop has been modified to call the update and render methods of + the current screen. The AWT keyboard and mouse event listeners have + also been changed to forward the events to the current game screen. + +* Sprite.java + 1) getNextFrame now correctly returns the next frame indicated by the + currently active sequence. + +* GameEntity.java + 1) Added constants for keycodes of left, right, up and down buttons. + +* Spritesheet.java + 1) New class to represent Spritesheets. Contains convenience + methods to easily load full or partial tileset. extractAll method loads + a tileset along with a text file that contains labels for each + individual image of the tileset. extractRow returns a BufferedImage + array of all the images of a single row. + +* Utilities.java + 1) Added removeMask method which takes in an image and removes the mask + color. + + +19/06/2008 Shahriar Haque <[email protected]> + +* AbstractGame.java + 1) Set the ignoreRepaint property of the GameWindow inner class to true to improve rendering performance. + 2) Added white and black Color constants as they are frequently used. + + +13/06/2008 Shahriar Haque <[email protected]> + +* GameEntity.java + 1) Changed access modifier of x,y,width height to public. + 2) Sprite object is now public and final. + 3) Removed getters for getX(),getY(),getWidth(),getHeight() and + getSprite(). + 4) Removed setLocation(x,y) and setDimensionMethod(w,h) methods. + 5) Changed accessor of Rectangle bound to final, fixed constructor to + initialize bound. + +* AdvancedGameEntity.java + 1) Replaced accessor method called for getX(), getY(), getWidth(), + getSprite() to their respective public instance variables. + 2) Added sine-table from NS-47 Project + 3) Added heading fixes from NS-47 Project + 4) Changed dx = (int) (x + x_velocity) to x = (int) (x + x_velocity); + 5) Removed occurences of setLocation methods in the class. + 6) Commented out declarations of dx and dy because they do not seemed + to be used anywhere. + +* Sprite.java + 1) Changed accessor for BufferedImage[] frames to final. + +* AbstractGame.java + 1) Changed all the access modifiers to final \ No newline at end of file diff --git a/Features.txt b/Features.txt new file mode 100644 index 0000000..e8b7f2a --- /dev/null +++ b/Features.txt @@ -0,0 +1,8 @@ +P2P Web Service (beta) +Real time Particle System +Lighting Effects (beta) +Special Effect Library +Precision Vector-based Collisions +Threaded MP3, Wav, Midi playback support +Spritesheet loading and extraction +High quality anti-aliased image operations \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b9c6625 --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +clean: + rm ai/evolutionary/*.class collection/*.class effects/*.class \ +experimental/lighting/*.class experimental/network/*.class \ +experimental/physics/*.class kobaltBasic/*.class particle/*.class \ +sound/*.class tester/*.class diff --git a/README b/README new file mode 100644 index 0000000..1e07698 --- /dev/null +++ b/README @@ -0,0 +1,18 @@ +Kobalt is a 2d game engine written in Java. It currently +has the following features: + + - Loading and managing 2d sprites + - Collission detection using arbitrary shapes + - A particle effects engine + - A library of raster graphics effects + - Loading and playing WAV and MIDI files in the background + +================== +Build Instructions +================== +Kobalt was built using Eclipse. To be able to build this project +and run the demos, simply import this directory as a project in +Eclipse. The demos are in a package called tester. + +Note: The Makefile is still incomplete. Use it to clean up +.class files before committing the code. diff --git a/Roadmap b/Roadmap new file mode 100644 index 0000000..60baa4e --- /dev/null +++ b/Roadmap @@ -0,0 +1,34 @@ +Roadmap Version 2.0 +Last Revised 22/03/2010 +Author: Shahriar Haque <[email protected]> + + - Refactor to support chaining together animations + - Rewrite experimental networking package with UDP based P2P + - Dedicated Generic Game Server (Client-Server Model?) + - Complete Physics Engine integration + - Migrate code to JOGL + + +=============================================================================== + +Roadmap Version 1.0 +Last Revised: 6/12/2008 +Author: Shahriar Haque <[email protected]> + + - Have support for multiple screens (completed) + - New derived class of AdvancedGameEntity to support vector graphics transformation. (completed) + - Advanced collision detection method/class with vector based outlines. (completed) + - Support for playing MP3 files in a threaded environment. (completed) + - Add support for playing Midis, preloading sound clips, and playing them on new threads. (completed) + - Base class for vector graphics consisting of Shapes, Areas or Polygons. (completed) + + - Update queue and render queue with Z-order sorting + - EntityGroup class for managing update, render and collision detection. + - SVG support for sprites. + + +Special Effects: + - Refraction Effects (Warp, Magnify) + - Saturation Effects (Saturate, Desaturate) + - Reflection Effects (Faded Reflection, Water Reflection) + \ No newline at end of file diff --git a/TesterGameIdeas b/TesterGameIdeas new file mode 100644 index 0000000..3aad234 --- /dev/null +++ b/TesterGameIdeas @@ -0,0 +1,7 @@ +Simple Game Ideas + +Chicken Cross The Road + Chicken pops up in random location. His goal is to reach another randomly + selected destination. Chicken can only move at 90 degrees. Cars bounce + horizontally or vertically on the walls. Each level increases the number + of cars. \ No newline at end of file diff --git a/ai/evolutionary/Chromosome.java b/ai/evolutionary/Chromosome.java new file mode 100644 index 0000000..bf9e8a2 --- /dev/null +++ b/ai/evolutionary/Chromosome.java @@ -0,0 +1,35 @@ +package ai.evolutionary; + +/** + * A Chromosome represents a candidate solution in a genetic algorithm. The current + * representation can model arbitrary number of real valued parameters. + * @author Shahriar Haque + * + */ +public class Chromosome implements Comparable<Chromosome>{ + + /** number of genes in the chromosome **/ + int[] parameters; + /** fitness of this chromosome**/ + double fitness; + + /** + * Creates a new chromosome with the given number of parameters + * @param numParameters + */ + public Chromosome(int numParameters){ + parameters = new int[numParameters]; + } + + /** + * Compares two chromosomes and returns the sign of the difference of their fitness + */ + public int compareTo(Chromosome c) { + return ((fitness - c.fitness) > 0 ? 1 : -1) ; + } + + public String toString(){ + return fitness + ""; + } + +} \ No newline at end of file diff --git a/ai/evolutionary/FitnessFunction.java b/ai/evolutionary/FitnessFunction.java new file mode 100644 index 0000000..4731815 --- /dev/null +++ b/ai/evolutionary/FitnessFunction.java @@ -0,0 +1,13 @@ +package ai.evolutionary; + +public interface FitnessFunction { + + /** + * Returns a real number representing how close the solution represented by the + * Chromosome is. A higher fitness value means better solution. + * @param chromosome + * @return + */ + double fitnessFunction(Chromosome chromosome); + +} diff --git a/ai/evolutionary/GenericGA.java b/ai/evolutionary/GenericGA.java new file mode 100644 index 0000000..64026b0 --- /dev/null +++ b/ai/evolutionary/GenericGA.java @@ -0,0 +1,193 @@ +package ai.evolutionary; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; +import java.util.Scanner; + + +public class GenericGA { + + /** number of parameters in the solution we are searching **/ + int numberOfParameters; + + /** number of chromosomes in the pool **/ + int populationSize; + + /** ArrayList containing the whole population of chromosomes **/ + ArrayList<Chromosome> chromosomes; + + + /** probability of a chromosome's gene being randomly mutated, default: 10 % (not used) **/ + double mutationRate = 0.1; + + /** probability of one chromosome swapping a gene with another one, default: 20% **/ + double crossOverRate = 0.2; + + /** minimum error that has to be achieved for a chromosome to be selected as the best, default 0.01 % **/ + double tolerance = 1.75e-6; + + /** lower bound value for all genes in the chromosome **/ + double upperBound; + + /** upper bound value for all genes in the chromosome**/ + double lowerBound; + + /** desired value wished to be achieved through the algorithm **/ + double targetValue; + + int maxGeneration = 20; + + private Chromosome result; + + FitnessFunction f; + + + private static Random rand = new Random(); + + public GenericGA(String initPop) { + populateWorld(initPop); + } + + + /** + * Initializes the Genetic Algorithm Environment with a randomly generated population. + */ + public GenericGA(){ + populateWorld(populationSize, numberOfParameters, upperBound, lowerBound); + } + + + /** + * Initializes the Genetic Algorithm Environment with a population loaded from the given file. + */ + private void populateWorld(String initPop){ + try { + Scanner f = new Scanner(new File(initPop)); + + int numParam = f.nextInt(); + int popSize = f.nextInt(); + chromosomes = new ArrayList<Chromosome>(popSize); + + for(int i = 0; i < popSize; i++){ + Chromosome c = new Chromosome(numParam); + + for(int j = 0; j < numParam; j++){ + c.parameters[j] = f.nextInt(); + } + + chromosomes.add(c); + } + + + } + + catch (FileNotFoundException e) { + System.err.println("Population file " + initPop + " not found!"); + System.exit(1); + + } + + } + + private void populateWorld(int popSize,int numParam ,double upperBound, double lowerBound){ + double rand; + + chromosomes = new ArrayList<Chromosome>(popSize); + + for(int i = 0; i < popSize; i++){ + Chromosome c = new Chromosome(numParam); + + for(int j = 0; j < c.parameters.length; j++){ + rand = Math.random(); + c.parameters[j] = (int)(((upperBound - lowerBound)*rand) + lowerBound); + } + + chromosomes.add(c); + + } + + } + + + + public void runGA(){ + new Thread(new Runnable(){ + + public void run() { + runInner(); + + } + + }).start(); + } + + private void runInner(){ + + + int cg = 0; + + double currentBest = Double.POSITIVE_INFINITY; + + while(!false){ + if(cg > maxGeneration) break; + + for(int i = 0; i < chromosomes.size(); i++){ + Chromosome c = chromosomes.get(i); + c.fitness = f.fitnessFunction(c); + if(c.fitness == 0) break; + } + + + Collections.sort(chromosomes); + + cg++; + if(chromosomes.get(0).fitness < currentBest){ + currentBest = chromosomes.get(0).fitness; + } + System.out.println(cg + "\t" + currentBest); + + if(chromosomes.get(0).fitness == 0.0) break; + + + // swaps the value of a random parameter between two random chromosomes at the crossOverRate + for(int i = 0; i < populationSize-1; i++){ + int x = rand.nextInt(numberOfParameters); + int y = rand.nextInt(numberOfParameters); + + int temp; + Chromosome c1 = chromosomes.get(i); + Chromosome c2 = chromosomes.get(rand.nextInt(populationSize)); + + double rx = Math.random(); + + if(rx < crossOverRate){ + temp = c1.parameters[x]; + c1.parameters[x] = c2.parameters[y]; + c2.parameters[y] = temp; + } + + + + } + + } + + + Chromosome sol = chromosomes.get(0); + + synchronized(this){ + result = sol; + } + + + } + + + + public Chromosome getResult(){ + return result; + } + +} diff --git a/collection/QuadTree.java b/collection/QuadTree.java new file mode 100644 index 0000000..d905a00 --- /dev/null +++ b/collection/QuadTree.java @@ -0,0 +1,42 @@ +package collection; + +import java.util.HashSet; + + + +public class QuadTree<E> { + + public QuadNode<E> root = null; + + public QuadTree(int width, int height, int max_level){ + //root = createTree(root, width, height, 0, max_level); + + + } + + + + private void createTree(QuadNode<E> node, int width, int height, int level, + int maxLevel) { + + node = new QuadNode<E>(); + if(level == maxLevel) return; + + + } + + + + private class QuadNode<E>{ + public boolean isLeaf = false; + public int level = 0; + public int[] xcorners = new int[4]; + public int[] ycorners = new int[4]; + public QuadNode<E>[] children = (QuadNode<E>[]) new Object[4]; + HashSet<E> set = new HashSet<E>(); + + + public QuadNode(){} + } + +} diff --git a/effects/BlendComposite.java b/effects/BlendComposite.java new file mode 100644 index 0000000..5eded7a --- /dev/null +++ b/effects/BlendComposite.java @@ -0,0 +1,836 @@ +/* + * Copyright (c) 2006 Romain Guy <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package effects; + +import java.awt.Composite; +import java.awt.CompositeContext; +import java.awt.RenderingHints; +import java.awt.image.ColorModel; +import java.awt.image.DataBuffer; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; + +/** + * This class contains 32 new Composite implementations for Java2D (even though Normal is the + * equivalent of AlphaComposite.Src): + * <ul> + * <li> Normal</li> + * <li> Average</li> + * <li> Multiply</li> + * <li> Screen</li> + * <li> Darken</li> + * <li> Lighten</li> + * <li> Overlay</li> + * <li> HardLight</li> + * <li> SoftLight</li> + * <li> Difference</li> + * <li> Negation</li> + * <li> Exclusion</li> + * <li> ColorDodge</li> + * <li> InverseColorDodge</li> + * <li> SoftDodge</li> + * <li> ColorBurn</li> + * <li> InverseColorBurn</li> + * <li> SoftBurn</li> + * <li> Reflect</li> + * <li> Glow</li> + * <li> Freeze</li> + * <li> Heat</li> + * <li> Add</li> + * <li> Subtract</li> + * <li> Stamp</li> + * <li> Red</li> + * <li> Green</li> + * <li> Blue</li> + * <li> Hue</li> + * <li> Saturation</li> + * <li> Color</li> + * <li> Luminosity</li> + * </ul> + * + * BlendComposite works exactly as AlphaComposite. I simply duplicated the API. Here is an example + * of blending two pictures with the Overlay mode: + * <p> + * {@code g2.drawImage(imageA, 0, 0, null); }<br/> + * {@code g2.setComposite(BlendComposite.Overlay.derive(0.75f)); }<br/> + * {@code g2.drawImage(imageB, 0, 0, null); }<br/> + * </p> + * + * There are a few caveats though. First, I only implemented the operations for primitives stored + * as integers. That means you have to make sure you draw images that store their pixels as + * INT_RGB or INT_ARGB (making your pictures compatible will work.) Next, these implementations + * are not very fast, do not try real-time drawing with them. Finally, the SoftLight blending + * is not implemented yet and the HSL modes are not perfect when you blend a grayscale primitive. + * If you want to help, feel free to send me patches. + * + * Those composites work much better with Java SE 6; I have noticed speed improvements of x3 to x4 + * when compared to J2SE 5.0. + * + * @author Romain Guy + * + */ +public final class BlendComposite implements Composite { + public enum BlendingMode { + NORMAL, + AVERAGE, + MULTIPLY, + SCREEN, + DARKEN, + LIGHTEN, + OVERLAY, + HARD_LIGHT, + SOFT_LIGHT, + DIFFERENCE, + NEGATION, + EXCLUSION, + COLOR_DODGE, + INVERSE_COLOR_DODGE, + SOFT_DODGE, + COLOR_BURN, + INVERSE_COLOR_BURN, + SOFT_BURN, + REFLECT, + GLOW, + FREEZE, + HEAT, + ADD, + SUBTRACT, + STAMP, + RED, + GREEN, + BLUE, + HUE, + SATURATION, + COLOR, + LUMINOSITY + } + + public static final BlendComposite Normal = new BlendComposite(BlendingMode.NORMAL); + public static final BlendComposite Average = new BlendComposite(BlendingMode.AVERAGE); + public static final BlendComposite Multiply = new BlendComposite(BlendingMode.MULTIPLY); + public static final BlendComposite Screen = new BlendComposite(BlendingMode.SCREEN); + public static final BlendComposite Darken = new BlendComposite(BlendingMode.DARKEN); + public static final BlendComposite Lighten = new BlendComposite(BlendingMode.LIGHTEN); + public static final BlendComposite Overlay = new BlendComposite(BlendingMode.OVERLAY); + public static final BlendComposite HardLight = new BlendComposite(BlendingMode.HARD_LIGHT); + public static final BlendComposite SoftLight = new BlendComposite(BlendingMode.SOFT_LIGHT); + public static final BlendComposite Difference = new BlendComposite(BlendingMode.DIFFERENCE); + public static final BlendComposite Negation = new BlendComposite(BlendingMode.NEGATION); + public static final BlendComposite Exclusion = new BlendComposite(BlendingMode.EXCLUSION); + public static final BlendComposite ColorDodge = new BlendComposite(BlendingMode.COLOR_DODGE); + public static final BlendComposite InverseColorDodge = new BlendComposite(BlendingMode.INVERSE_COLOR_DODGE); + public static final BlendComposite SoftDodge = new BlendComposite(BlendingMode.SOFT_DODGE); + public static final BlendComposite ColorBurn = new BlendComposite(BlendingMode.COLOR_BURN); + public static final BlendComposite InverseColorBurn = new BlendComposite(BlendingMode.INVERSE_COLOR_BURN); + public static final BlendComposite SoftBurn = new BlendComposite(BlendingMode.SOFT_BURN); + public static final BlendComposite Reflect = new BlendComposite(BlendingMode.REFLECT); + public static final BlendComposite Glow = new BlendComposite(BlendingMode.GLOW); + public static final BlendComposite Freeze = new BlendComposite(BlendingMode.FREEZE); + public static final BlendComposite Heat = new BlendComposite(BlendingMode.HEAT); + public static final BlendComposite Add = new BlendComposite(BlendingMode.ADD); + public static final BlendComposite Subtract = new BlendComposite(BlendingMode.SUBTRACT); + public static final BlendComposite Stamp = new BlendComposite(BlendingMode.STAMP); + public static final BlendComposite Red = new BlendComposite(BlendingMode.RED); + public static final BlendComposite Green = new BlendComposite(BlendingMode.GREEN); + public static final BlendComposite Blue = new BlendComposite(BlendingMode.BLUE); + public static final BlendComposite Hue = new BlendComposite(BlendingMode.HUE); + public static final BlendComposite Saturation = new BlendComposite(BlendingMode.SATURATION); + public static final BlendComposite Color = new BlendComposite(BlendingMode.COLOR); + public static final BlendComposite Luminosity = new BlendComposite(BlendingMode.LUMINOSITY); + + private float alpha; + private BlendingMode mode; + + private BlendComposite(BlendingMode mode) { + this(mode, 1.0f); + } + + private BlendComposite(BlendingMode mode, float alpha) { + this.mode = mode; + setAlpha(alpha); + } + + public static BlendComposite getInstance(BlendingMode mode) { + return new BlendComposite(mode); + } + + public static BlendComposite getInstance(BlendingMode mode, float alpha) { + return new BlendComposite(mode, alpha); + } + + public BlendComposite derive(BlendingMode mode) { + return this.mode == mode ? this : new BlendComposite(mode, getAlpha()); + } + + public BlendComposite derive(float alpha) { + return this.alpha == alpha ? this : new BlendComposite(getMode(), alpha); + } + + public float getAlpha() { + return alpha; + } + + public BlendingMode getMode() { + return mode; + } + + private void setAlpha(float alpha) { + if (alpha < 0.0f || alpha > 1.0f) { + throw new IllegalArgumentException( + "alpha must be comprised between 0.0f and 1.0f"); + } + + this.alpha = alpha; + } + + @Override + public int hashCode() { + return Float.floatToIntBits(alpha) * 31 + mode.ordinal(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlendComposite)) { + return false; + } + + BlendComposite bc = (BlendComposite) obj; + + if (mode != bc.mode) { + return false; + } + + return alpha == bc.alpha; + } + + public CompositeContext createContext(ColorModel srcColorModel, + ColorModel dstColorModel, + RenderingHints hints) { + return new BlendingContext(this); + } + + private static final class BlendingContext implements CompositeContext { + private final Blender blender; + private final BlendComposite composite; + + private BlendingContext(BlendComposite composite) { + this.composite = composite; + this.blender = Blender.getBlenderFor(composite); + } + + public void dispose() { + } + + public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { + if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT || + dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT || + dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) { + throw new IllegalStateException( + "Source and destination must store pixels as INT."); + } + + int width = Math.min(src.getWidth(), dstIn.getWidth()); + int height = Math.min(src.getHeight(), dstIn.getHeight()); + + float alpha = composite.getAlpha(); + + int[] srcPixel = new int[4]; + int[] dstPixel = new int[4]; + int[] srcPixels = new int[width]; + int[] dstPixels = new int[width]; + + for (int y = 0; y < height; y++) { + src.getDataElements(0, y, width, 1, srcPixels); + dstIn.getDataElements(0, y, width, 1, dstPixels); + for (int x = 0; x < width; x++) { + // pixels are stored as INT_ARGB + // our arrays are [R, G, B, A] + int pixel = srcPixels[x]; + srcPixel[0] = (pixel >> 16) & 0xFF; + srcPixel[1] = (pixel >> 8) & 0xFF; + srcPixel[2] = (pixel ) & 0xFF; + srcPixel[3] = (pixel >> 24) & 0xFF; + + pixel = dstPixels[x]; + dstPixel[0] = (pixel >> 16) & 0xFF; + dstPixel[1] = (pixel >> 8) & 0xFF; + dstPixel[2] = (pixel ) & 0xFF; + dstPixel[3] = (pixel >> 24) & 0xFF; + + int[] result = blender.blend(srcPixel, dstPixel); + + // mixes the result with the opacity + dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 | + ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 | + ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 | + (int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF; + } + dstOut.setDataElements(0, y, width, 1, dstPixels); + } + } + } + + private static abstract class Blender { + public abstract int[] blend(int[] src, int[] dst); + + private static void RGBtoHSL(int r, int g, int b, float[] hsl) { + float var_R = (r / 255f); + float var_G = (g / 255f); + float var_B = (b / 255f); + + float var_Min; + float var_Max; + float del_Max; + + if (var_R > var_G) { + var_Min = var_G; + var_Max = var_R; + } else { + var_Min = var_R; + var_Max = var_G; + } + if (var_B > var_Max) { + var_Max = var_B; + } + if (var_B < var_Min) { + var_Min = var_B; + } + + del_Max = var_Max - var_Min; + + float H, S, L; + L = (var_Max + var_Min) / 2f; + + if (del_Max - 0.01f <= 0.0f) { + H = 0; + S = 0; + } else { + if (L < 0.5f) { + S = del_Max / (var_Max + var_Min); + } else { + S = del_Max / (2 - var_Max - var_Min); + } + + float del_R = (((var_Max - var_R) / 6f) + (del_Max / 2f)) / del_Max; + float del_G = (((var_Max - var_G) / 6f) + (del_Max / 2f)) / del_Max; + float del_B = (((var_Max - var_B) / 6f) + (del_Max / 2f)) / del_Max; + + if (var_R == var_Max) { + H = del_B - del_G; + } else if (var_G == var_Max) { + H = (1 / 3f) + del_R - del_B; + } else { + H = (2 / 3f) + del_G - del_R; + } + if (H < 0) { + H += 1; + } + if (H > 1) { + H -= 1; + } + } + + hsl[0] = H; + hsl[1] = S; + hsl[2] = L; + } + + private static void HSLtoRGB(float h, float s, float l, int[] rgb) { + int R, G, B; + + if (s - 0.01f <= 0.0f) { + R = (int) (l * 255.0f); + G = (int) (l * 255.0f); + B = (int) (l * 255.0f); + } else { + float var_1, var_2; + if (l < 0.5f) { + var_2 = l * (1 + s); + } else { + var_2 = (l + s) - (s * l); + } + var_1 = 2 * l - var_2; + + R = (int) (255.0f * hue2RGB(var_1, var_2, h + (1.0f / 3.0f))); + G = (int) (255.0f * hue2RGB(var_1, var_2, h)); + B = (int) (255.0f * hue2RGB(var_1, var_2, h - (1.0f / 3.0f))); + } + + rgb[0] = R; + rgb[1] = G; + rgb[2] = B; + } + + private static float hue2RGB(float v1, float v2, float vH) { + if (vH < 0.0f) { + vH += 1.0f; + } + if (vH > 1.0f) { + vH -= 1.0f; + } + if ((6.0f * vH) < 1.0f) { + return (v1 + (v2 - v1) * 6.0f * vH); + } + if ((2.0f * vH) < 1.0f) { + return (v2); + } + if ((3.0f * vH) < 2.0f) { + return (v1 + (v2 - v1) * ((2.0f / 3.0f) - vH) * 6.0f); + } + return (v1); + } + + public static Blender getBlenderFor(BlendComposite composite) { + switch (composite.getMode()) { + case NORMAL: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return src; + } + }; + case ADD: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.min(255, src[0] + dst[0]), + Math.min(255, src[1] + dst[1]), + Math.min(255, src[2] + dst[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case AVERAGE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + (src[0] + dst[0]) >> 1, + (src[1] + dst[1]) >> 1, + (src[2] + dst[2]) >> 1, + Math.min(255, src[3] + dst[3]) + }; + } + }; + case BLUE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0], + src[1], + dst[2], + Math.min(255, src[3] + dst[3]) + }; + } + }; + case COLOR: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + float[] srcHSL = new float[3]; + RGBtoHSL(src[0], src[1], src[2], srcHSL); + float[] dstHSL = new float[3]; + RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); + + int[] result = new int[4]; + HSLtoRGB(srcHSL[0], srcHSL[1], dstHSL[2], result); + result[3] = Math.min(255, src[3] + dst[3]); + + return result; + } + }; + case COLOR_BURN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0] == 0 ? 0 : + Math.max(0, 255 - (((255 - dst[0]) << 8) / src[0])), + src[1] == 0 ? 0 : + Math.max(0, 255 - (((255 - dst[1]) << 8) / src[1])), + src[2] == 0 ? 0 : + Math.max(0, 255 - (((255 - dst[2]) << 8) / src[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case COLOR_DODGE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0] == 255 ? 255 : + Math.min((dst[0] << 8) / (255 - src[0]), 255), + src[1] == 255 ? 255 : + Math.min((dst[1] << 8) / (255 - src[1]), 255), + src[2] == 255 ? 255 : + Math.min((dst[2] << 8) / (255 - src[2]), 255), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case DARKEN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.min(src[0], dst[0]), + Math.min(src[1], dst[1]), + Math.min(src[2], dst[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case DIFFERENCE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.abs(dst[0] - src[0]), + Math.abs(dst[1] - src[1]), + Math.abs(dst[2] - src[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case EXCLUSION: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] + src[0] - (dst[0] * src[0] >> 7), + dst[1] + src[1] - (dst[1] * src[1] >> 7), + dst[2] + src[2] - (dst[2] * src[2] >> 7), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case FREEZE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0] == 0 ? 0 : Math.max(0, 255 - (255 - dst[0]) * (255 - dst[0]) / src[0]), + src[1] == 0 ? 0 : Math.max(0, 255 - (255 - dst[1]) * (255 - dst[1]) / src[1]), + src[2] == 0 ? 0 : Math.max(0, 255 - (255 - dst[2]) * (255 - dst[2]) / src[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case GLOW: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] == 255 ? 255 : Math.min(255, src[0] * src[0] / (255 - dst[0])), + dst[1] == 255 ? 255 : Math.min(255, src[1] * src[1] / (255 - dst[1])), + dst[2] == 255 ? 255 : Math.min(255, src[2] * src[2] / (255 - dst[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case GREEN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0], + dst[1], + src[2], + Math.min(255, src[3] + dst[3]) + }; + } + }; + case HARD_LIGHT: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0] < 128 ? dst[0] * src[0] >> 7 : + 255 - ((255 - src[0]) * (255 - dst[0]) >> 7), + src[1] < 128 ? dst[1] * src[1] >> 7 : + 255 - ((255 - src[1]) * (255 - dst[1]) >> 7), + src[2] < 128 ? dst[2] * src[2] >> 7 : + 255 - ((255 - src[2]) * (255 - dst[2]) >> 7), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case HEAT: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] == 0 ? 0 : Math.max(0, 255 - (255 - src[0]) * (255 - src[0]) / dst[0]), + dst[1] == 0 ? 0 : Math.max(0, 255 - (255 - src[1]) * (255 - src[1]) / dst[1]), + dst[2] == 0 ? 0 : Math.max(0, 255 - (255 - src[2]) * (255 - src[2]) / dst[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case HUE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + float[] srcHSL = new float[3]; + RGBtoHSL(src[0], src[1], src[2], srcHSL); + float[] dstHSL = new float[3]; + RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); + + int[] result = new int[4]; + HSLtoRGB(srcHSL[0], dstHSL[1], dstHSL[2], result); + result[3] = Math.min(255, src[3] + dst[3]); + + return result; + } + }; + case INVERSE_COLOR_BURN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] == 0 ? 0 : + Math.max(0, 255 - (((255 - src[0]) << 8) / dst[0])), + dst[1] == 0 ? 0 : + Math.max(0, 255 - (((255 - src[1]) << 8) / dst[1])), + dst[2] == 0 ? 0 : + Math.max(0, 255 - (((255 - src[2]) << 8) / dst[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case INVERSE_COLOR_DODGE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] == 255 ? 255 : + Math.min((src[0] << 8) / (255 - dst[0]), 255), + dst[1] == 255 ? 255 : + Math.min((src[1] << 8) / (255 - dst[1]), 255), + dst[2] == 255 ? 255 : + Math.min((src[2] << 8) / (255 - dst[2]), 255), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case LIGHTEN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.max(src[0], dst[0]), + Math.max(src[1], dst[1]), + Math.max(src[2], dst[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case LUMINOSITY: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + float[] srcHSL = new float[3]; + RGBtoHSL(src[0], src[1], src[2], srcHSL); + float[] dstHSL = new float[3]; + RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); + + int[] result = new int[4]; + HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); + result[3] = Math.min(255, src[3] + dst[3]); + + return result; + } + }; + case MULTIPLY: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + (src[0] * dst[0]) >> 8, + (src[1] * dst[1]) >> 8, + (src[2] * dst[2]) >> 8, + Math.min(255, src[3] + dst[3]) + }; + } + }; + case NEGATION: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + 255 - Math.abs(255 - dst[0] - src[0]), + 255 - Math.abs(255 - dst[1] - src[1]), + 255 - Math.abs(255 - dst[2] - src[2]), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case OVERLAY: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] < 128 ? dst[0] * src[0] >> 7 : + 255 - ((255 - dst[0]) * (255 - src[0]) >> 7), + dst[1] < 128 ? dst[1] * src[1] >> 7 : + 255 - ((255 - dst[1]) * (255 - src[1]) >> 7), + dst[2] < 128 ? dst[2] * src[2] >> 7 : + 255 - ((255 - dst[2]) * (255 - src[2]) >> 7), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case RED: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0], + dst[1], + dst[2], + Math.min(255, src[3] + dst[3]) + }; + } + }; + case REFLECT: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + src[0] == 255 ? 255 : Math.min(255, dst[0] * dst[0] / (255 - src[0])), + src[1] == 255 ? 255 : Math.min(255, dst[1] * dst[1] / (255 - src[1])), + src[2] == 255 ? 255 : Math.min(255, dst[2] * dst[2] / (255 - src[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case SATURATION: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + float[] srcHSL = new float[3]; + RGBtoHSL(src[0], src[1], src[2], srcHSL); + float[] dstHSL = new float[3]; + RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); + + int[] result = new int[4]; + HSLtoRGB(dstHSL[0], srcHSL[1], dstHSL[2], result); + result[3] = Math.min(255, src[3] + dst[3]); + + return result; + } + }; + case SCREEN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + 255 - ((255 - src[0]) * (255 - dst[0]) >> 8), + 255 - ((255 - src[1]) * (255 - dst[1]) >> 8), + 255 - ((255 - src[2]) * (255 - dst[2]) >> 8), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case SOFT_BURN: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] + src[0] < 256 ? + (dst[0] == 255 ? 255 : + Math.min(255, (src[0] << 7) / (255 - dst[0]))) : + Math.max(0, 255 - (((255 - dst[0]) << 7) / src[0])), + dst[1] + src[1] < 256 ? + (dst[1] == 255 ? 255 : + Math.min(255, (src[1] << 7) / (255 - dst[1]))) : + Math.max(0, 255 - (((255 - dst[1]) << 7) / src[1])), + dst[2] + src[2] < 256 ? + (dst[2] == 255 ? 255 : + Math.min(255, (src[2] << 7) / (255 - dst[2]))) : + Math.max(0, 255 - (((255 - dst[2]) << 7) / src[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case SOFT_DODGE: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + dst[0] + src[0] < 256 ? + (src[0] == 255 ? 255 : + Math.min(255, (dst[0] << 7) / (255 - src[0]))) : + Math.max(0, 255 - (((255 - src[0]) << 7) / dst[0])), + dst[1] + src[1] < 256 ? + (src[1] == 255 ? 255 : + Math.min(255, (dst[1] << 7) / (255 - src[1]))) : + Math.max(0, 255 - (((255 - src[1]) << 7) / dst[1])), + dst[2] + src[2] < 256 ? + (src[2] == 255 ? 255 : + Math.min(255, (dst[2] << 7) / (255 - src[2]))) : + Math.max(0, 255 - (((255 - src[2]) << 7) / dst[2])), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case SOFT_LIGHT: + break; + case STAMP: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.max(0, Math.min(255, dst[0] + 2 * src[0] - 256)), + Math.max(0, Math.min(255, dst[1] + 2 * src[1] - 256)), + Math.max(0, Math.min(255, dst[2] + 2 * src[2] - 256)), + Math.min(255, src[3] + dst[3]) + }; + } + }; + case SUBTRACT: + return new Blender() { + @Override + public int[] blend(int[] src, int[] dst) { + return new int[] { + Math.max(0, src[0] + dst[0] - 256), + Math.max(0, src[1] + dst[1] - 256), + Math.max(0, src[2] + dst[2] - 256), + Math.min(255, src[3] + dst[3]) + }; + } + }; + } + throw new IllegalArgumentException("Blender not implement for " + + composite.getMode().name()); + } + } +} diff --git a/effects/BlurEffect.java b/effects/BlurEffect.java new file mode 100644 index 0000000..7e42fd3 --- /dev/null +++ b/effects/BlurEffect.java @@ -0,0 +1,65 @@ +package effects; + +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.ConvolveOp; +import java.awt.image.Kernel; + +import kobaltBasic.BasicGame; +import kobaltBasic.SpriteActor; + +/** + * A special effects class that applies a blur effect to the current frame of a given GameEntity. + * The effect uses a default (3x3) kernel that the user can access staticly. If there is a need + * to change the kernel, the value of {@code kernelDim} also has to be changed accordingly. + * @author Shahriar Haque + * + */ +public class BlurEffect { + + + /** Kernel of the blur filter that will be applied to the image **/ + public static float[] kernel = new float[]{ + 0.1f, 0.1f, 0.1f, + 0.1f, 0.2f, 0.1f, + 0.1f, 0.1f, 0.1f + }; + + /** Dimension of the kernel, kernel are always square matrices. Thus this + * is the dimension for both rows and columns. Default value is 3. **/ + public static int kernelDim = 3; + + + public static void applyEffect(Graphics2D g, BufferedImage b, int x, int y){ + + // get the background on which the frame will be drawn + BufferedImage bg = BasicGame.backBuffer.getSubimage(x, y, b.getWidth(), b.getHeight()); + bg.getGraphics().drawImage(b,0,0,null); + + // apply the blur filter + ConvolveOp op = new ConvolveOp(new Kernel(kernelDim,kernelDim, kernel)); + Image img = op.filter(bg, null); + g.drawImage(img,x, y, null); + } + + public static void applyEffect(Graphics2D g, SpriteActor entity){ + applyEffect(g, entity.theSprite.getCurrentFrame(), (int)entity.x, (int)entity.y); + } + + + public static void applyEffect(Graphics2D g, Drawable d){ + + // get the background on which the frame will be drawn + BufferedImage bg = BasicGame.backBuffer.getSubimage(d.getX(), d.getY(), d.getWidth(), d.getHeight()); + d.draw((Graphics2D) bg.getGraphics()); + + // apply the blur filter + ConvolveOp op = new ConvolveOp(new Kernel(kernelDim,kernelDim, kernel)); + Image img = op.filter(bg, null); + g.drawImage(img,d.getX(), d.getY(), null); + } + + + +} diff --git a/effects/Drawable.java b/effects/Drawable.java new file mode 100644 index 0000000..9bf8955 --- /dev/null +++ b/effects/Drawable.java @@ -0,0 +1,26 @@ +package effects; + +import java.awt.Graphics2D; + +/** + * All objects that needs to be rendered on a screen, but is not represented by a Sprite should + * implement this interface. Special effects operations can be performed on implementing classes. + * @author Shahriar Haque + * + */ +public interface Drawable { + + + /** + * The custom drawing code for this on-screen object should be implemented here. + * @param g The graphics context of the screen on which the object will be drawn on. + */ + public void draw(Graphics2D g); + + public int getX(); + public int getY(); + public int getWidth(); + public int getHeight(); + + +} diff --git a/effects/FadeEffect.java b/effects/FadeEffect.java new file mode 100644 index 0000000..47e6869 --- /dev/null +++ b/effects/FadeEffect.java @@ -0,0 +1,124 @@ +package effects; + + +import java.awt.AlphaComposite; +import java.awt.Composite; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import kobaltBasic.SpriteActor; + +public class FadeEffect { + + + /** Flag that indicates whether the animation has terminated or not. **/ + public boolean done = false; + + /** Fade Out constant **/ + public static final int FADE_OUT = 1; + /** Fade In constant**/ + public static final int FADE_IN = 0; + + /** Current type of fade effect**/ + public int type = 0; + + /** Duration in milliseconds **/ + public int duration = 1000; + + private int elapsed = 0; + + /** + * Creates a FadeEffect object of the given type + * @param type Either FadeEffect.FADE_IN or FadeEffect.FADE_OUT. Any other value will result in a fade out effect. + */ + public FadeEffect(int type){ + this.type = type; + } + + + /** + * Resets internal fade effect counter to zero. Use this to initialize the FadeEffect object for a new run. + */ + public void reset(){ + elapsed = 0; + done = false; + } + + + /** + * Applies the fade effect on the given BufferedImage on the graphics context {@code g} + * at location x,y; + * @param g The graphics context (background) on which the image will be drawn. + * @param b The BufferedImage on which the effect will be applied. + * @param x X coordinate of the image on the background. + * @param y Y coordinate of the image on the background. + */ + public void applyEffect(Graphics2D g, BufferedImage b, int x, int y){ + + + + elapsed += BasicGame.interval; + + + if(elapsed >= duration) { + elapsed = duration; + done = true; + } + + // linear interpolation of alpha value + float amount = ((float) (elapsed)) / duration; + + Composite oldComposite = g.getComposite(); + Composite fade = null; + if(type == FADE_IN) fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, amount); + else fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f - amount ); + + g.setComposite(fade); + g.drawImage(b, x, y, null); + g.setComposite(oldComposite); + + + } + + public void applyEffect(Graphics2D g, Drawable d){ + + + elapsed += BasicGame.interval; + + if(elapsed >= duration) { + elapsed = duration; + done = true; + } + + // linear interpolation of alpha value + float amount = ((float) (elapsed)) / duration; + + Composite oldComposite = g.getComposite(); + Composite fade = null; + if(type == FADE_IN) fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, amount); + else fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f - amount ); + + g.setComposite(fade); + d.draw(g); // delegates rendering to the Drawable + g.setComposite(oldComposite); + + } + + + + + + /** + * Applies the fade effect on the current frame of the given GameEntity + * @param g The graphics context (background) on which the GameEntity will be drawn. + * @param entity The GameEntity on which the fade effect will be applied. + */ + public void applyEffect(Graphics2D g, SpriteActor entity){ + + applyEffect(g, entity.theSprite.getCurrentFrame(), (int)entity.x, (int)entity.y); + + } + + +} diff --git a/effects/TwirlEffect.java b/effects/TwirlEffect.java new file mode 100644 index 0000000..13e58b4 --- /dev/null +++ b/effects/TwirlEffect.java @@ -0,0 +1,69 @@ +package effects; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import com.jhlabs.image.TwirlFilter; + +public class TwirlEffect { + + public int center_x; + public int center_y; + + public int duration = 10000; + public float radius = 50; + + private int elapsed = 0; + private float angle = 0; + + /** Rotational velocity in degrees/second. **/ + public float speed = 120; + + public boolean done = false; + + private TwirlFilter effect; + + public TwirlEffect(int x, int y){ + this.center_x = x; + this.center_y = y; + + effect = new TwirlFilter(); + + } + + public void reset(){ + elapsed = 0; + done = false; + } + + public void update(){ + + + effect.setRadius(radius); + + + if(elapsed > duration) done = true; + + float fraction = BasicGame.interval/1000.0f; + angle += speed*fraction; + effect.setAngle((float)Math.toRadians(angle)); + + + elapsed += BasicGame.interval; + + + + } + + public void applyEffect(Graphics2D g){ + if(done) return; + + BufferedImage b = BasicGame.backBuffer.getSubimage(center_x-(int)radius, center_y-(int)radius, (int)(2*radius), (int)(2*radius)); + effect.filter(b, b); + + g.drawImage(b,center_x-(int)radius, center_y-(int)radius,null); + + } + +} diff --git a/effects/WaterRippleEffect.java b/effects/WaterRippleEffect.java new file mode 100644 index 0000000..41cbccb --- /dev/null +++ b/effects/WaterRippleEffect.java @@ -0,0 +1,68 @@ +package effects; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import com.jhlabs.image.WaterFilter; + +public class WaterRippleEffect { + + public int center_x; + public int center_y; + public float amplitude = 10; + public float wavelength = 16; + public int duration = 10000; + public float radius = 50; + + private int elapsed = 0; + private float phase = 0; + public float speed = 15; + + public boolean done = false; + + private WaterFilter effect; + + public WaterRippleEffect(int x, int y){ + this.center_x = x; + this.center_y = y; + + effect = new WaterFilter(); + + } + + public void reset(){ + elapsed = 0; + done = false; + } + + public void update(){ + + effect.setAmplitude(amplitude); + effect.setWavelength(wavelength); + effect.setRadius(radius); + + if(elapsed > duration) done = true; + + float fraction = BasicGame.interval/1000.0f; + phase += speed*fraction; + effect.setPhase(phase); + + + elapsed += BasicGame.interval; + + + + } + + public void applyEffect(Graphics2D g){ + if(done) return; + + BufferedImage b = BasicGame.backBuffer.getSubimage(center_x-(int)radius, center_y-(int)radius, (int)(2*radius), (int)(2*radius)); + effect.filter(b, b); + + g.drawImage(b,center_x-(int)radius, center_y-(int)radius,null); + + } + +} diff --git a/experimental/lighting/Illuminator.java b/experimental/lighting/Illuminator.java new file mode 100644 index 0000000..bca8fd3 --- /dev/null +++ b/experimental/lighting/Illuminator.java @@ -0,0 +1,110 @@ +package experimental.lighting; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.image.WritableRaster; + +import kobaltBasic.SpriteActor; + +/** + * This class provides support for rendering lighting effects. In this experimental version only + * one light source and one object can be illuminated. The rendering only supports diffuse effects. + * Whenever the target object is out of the range of a light source, the default sprite is untouched. + * Within range, the brightness of the target increases as it approaches the light source. + * + * This is still an experimental implementation. + * @author Shahriar Haque + * + */ +public class Illuminator { + + /** Light source that illuminates the scene. **/ + public LightSource source; + /** The target object that needs to be illumniated.**/ + public SpriteActor target; + + public void render(Graphics2D g){ + + source.render(g); + + BufferedImage sprite = target.theSprite.getCurrentFrame(); + + float dist = (float) source.getDistance((int)target.x, (int)target.y); + float inc = (float) (1.0f - (dist/source.range)); + if(inc <= 0) inc = 0; + + float rFactor = 1.0f + inc; + + if(rFactor <= 1.0f){ + g.drawImage(sprite,(int)target.x, (int)target.y,null ); + return; + } + + // this is not being used because transparency is not preserved +// BufferedImage b = new BufferedImage(sprite.getWidth(), sprite.getHeight(), BufferedImage.TYPE_INT_RGB); +// b.createGraphics().drawImage(sprite,0,0,null); +// +// RescaleOp op = new RescaleOp(rFactor, 0.0f, null); +// b = op.filter(b, null); + + BufferedImage b = getBufferedImage(target,rFactor); + + + g.drawImage(b,(int)target.x, (int)target.y,null ); + } + + /** + * Given a GameEntity and a brightness factor, returns a new brighter image of that factor. + * @param t The GameEntity whose brightness has to be increased. + * @param factor The factor of brightness. 1.0 = no change, 2.0 = 100 % increase + * @return + */ + private BufferedImage getBufferedImage(SpriteActor t, float factor) { + BufferedImage sprite = t.theSprite.getCurrentFrame(); + + BufferedImage b = new BufferedImage(sprite.getWidth(), sprite.getHeight(), BufferedImage.TYPE_INT_ARGB); + b.createGraphics().drawImage(sprite,0,0,null); + + WritableRaster raster = b.getRaster(); + int[] pixel = new int[4]; + int width = raster.getWidth(); + int height = raster.getHeight(); + + for(int i = 0; i < width; i++){ + for(int j = 0; j < height; j++){ + + + raster.getPixel(i, j, pixel); + + // do not do anything for fully transparent pixels + if(pixel[3] == 0) continue; + + + // multiply each color band by the factor, change to 255 if it overflows + double color; + color = pixel[0]*factor; + if(color > 255) color = 255; + pixel[0] = (int) color; + + color = pixel[1]*factor; + if(color > 255) color = 255; + pixel[1] = (int) color; + + color = pixel[2]*factor; + if(color > 255) color = 255; + pixel[2] = (int) color; + + + + raster.setPixel(i, j, pixel); + } + } + + + + return b; + } + + + +} diff --git a/experimental/lighting/LightSource.java b/experimental/lighting/LightSource.java new file mode 100644 index 0000000..f6c3409 --- /dev/null +++ b/experimental/lighting/LightSource.java @@ -0,0 +1,33 @@ +package experimental.lighting; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + + +public class LightSource { + public double x; + public double y; + + /** The effective range of the light source**/ + public double range; + + /** The image used to render the light source **/ + BufferedImage img = null; + + public LightSource(BufferedImage image){ + this.img = image; + } + + + + /** If an image is present for this LightSource, renders it at (x,y) **/ + public void render(Graphics2D g){ + if(img != null)g.drawImage( img, (int)x, (int)y, null ); + } + + /** Returns the distance from itself to the given coordinate **/ + public final double getDistance(int x1, int y1){ + return Math.sqrt( ((x1-x)*(x1-x)) + ((y1-y)*(y1-y)) ); + } + +} diff --git a/experimental/network/NetworkComponent.java b/experimental/network/NetworkComponent.java new file mode 100644 index 0000000..09fbf86 --- /dev/null +++ b/experimental/network/NetworkComponent.java @@ -0,0 +1,9 @@ +package experimental.network; + +public interface NetworkComponent { + + void parseData(String msg); + + String getData(); + +} diff --git a/experimental/network/NetworkConstants.java b/experimental/network/NetworkConstants.java new file mode 100644 index 0000000..00b1f2e --- /dev/null +++ b/experimental/network/NetworkConstants.java @@ -0,0 +1,7 @@ +package experimental.network; + +public class NetworkConstants { + + public static final String READY_MESSAGE = "start"; + +} diff --git a/experimental/network/NetworkService.java b/experimental/network/NetworkService.java new file mode 100644 index 0000000..2871381 --- /dev/null +++ b/experimental/network/NetworkService.java @@ -0,0 +1,15 @@ +package experimental.network; + +public interface NetworkService { + + /** + * Starts a network service session. + */ + public void startSession(); + + /** + * Shuts down a network service session and closes any open connections. + */ + public void closeSession(); + +} diff --git a/experimental/network/P2PService.java b/experimental/network/P2PService.java new file mode 100644 index 0000000..7198a00 --- /dev/null +++ b/experimental/network/P2PService.java @@ -0,0 +1,168 @@ +package experimental.network; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.UnknownHostException; + +public class P2PService implements NetworkService { + + // networking declarations start here + + private boolean clientReady = false; + @SuppressWarnings("unused") + private boolean selfReady = false; + + public int PORT = 8080; + public InetAddress HOST; + + private Socket clientSock; + private ServerSocket serverSock; + private BufferedReader in; + private PrintWriter out; + + @SuppressWarnings("unused") + private boolean serverMode = false; + Thread connThread; + private static boolean isClosing = false; + + + // networking declarations end here + + + NetworkComponent game; + + public P2PService(NetworkComponent theGame){ + game = theGame; + + try { + HOST = InetAddress.getLocalHost(); + } + catch (UnknownHostException e) { + System.err.println("Could not set host to localhost"); + HOST = null; + } + } + + public void startSession(){ + new Thread(){ + public void run(){ + out.println("start"); + selfReady = true; + + + if(!clientReady) waitForClient(); + System.out.println("Starting session"); + + try{ + + while(!isClosing){ + out.println(game.getData()); + game.parseData(in.readLine()); + } + } + + catch (IOException e) { + e.printStackTrace(); + } + } + + }.start(); + } + + + private void waitForClient(){ + + try { + while(!clientReady){ + + String s = in.readLine(); + System.out.println("received: " + s); + if(s.equals(NetworkConstants.READY_MESSAGE)) { + clientReady = true; + System.out.println("client is ready"); + } + } + } + catch (IOException e) {} + } + + public void connectToHost(String host, int port){ + + try { + HOST = InetAddress.getByName(host); // handles host names like www.google.com and 84.101.146.2 + PORT = port; + + clientSock = new Socket(HOST,PORT); + System.out.println("Connected to " + HOST + " at port: " + PORT); + serverMode = false; + in = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); + out = new PrintWriter(clientSock.getOutputStream(), true); + connThread = new Thread(){ + public void run(){ + waitForClient(); + } + }; + + connThread.start(); + + } + + catch (UnknownHostException e) { + e.printStackTrace(); + System.err.println("Host: " + host + " not found"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public void startServer(int port){ + PORT = port; + + connThread = new Thread(){ + public void run(){ + try { + serverSock = new ServerSocket(PORT); + System.out.println("Server started... Listening at port: " + PORT); + serverMode = true; + clientSock = serverSock.accept(); + in = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); + out = new PrintWriter(clientSock.getOutputStream(), true); + + System.out.println("Connected to " + clientSock.getInetAddress().getHostAddress() + + " at port: " + PORT); + //waitForClient(); + } + + + catch (IOException e) { + System.out.println(e.getMessage()); + } + + + } + }; + + connThread.start(); + + + } + + public void closeSession() { + try { + + if(serverSock != null) serverSock.close(); + if(clientSock != null) clientSock.close(); + + } + + catch (IOException e) {} + + } + +} diff --git a/experimental/physics/AbstractPhysicsDemo.java b/experimental/physics/AbstractPhysicsDemo.java new file mode 100644 index 0000000..41ec288 --- /dev/null +++ b/experimental/physics/AbstractPhysicsDemo.java @@ -0,0 +1,426 @@ +package experimental.physics; + +import java.awt.Color; +import java.awt.Graphics2D; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import net.phys2d.math.MathUtil; +import net.phys2d.math.Matrix2f; +import net.phys2d.math.ROVector2f; +import net.phys2d.math.Vector2f; +import net.phys2d.raw.AngleJoint; +import net.phys2d.raw.Arbiter; +import net.phys2d.raw.ArbiterList; +import net.phys2d.raw.BasicJoint; +import net.phys2d.raw.Body; +import net.phys2d.raw.BodyList; +import net.phys2d.raw.Contact; +import net.phys2d.raw.DistanceJoint; +import net.phys2d.raw.FixedJoint; +import net.phys2d.raw.Joint; +import net.phys2d.raw.JointList; +import net.phys2d.raw.SlideJoint; +import net.phys2d.raw.SpringJoint; +import net.phys2d.raw.World; +import net.phys2d.raw.shapes.Box; +import net.phys2d.raw.shapes.Circle; +import net.phys2d.raw.shapes.Line; +import net.phys2d.raw.shapes.Polygon; +import net.phys2d.raw.strategies.QuadSpaceStrategy; + +/** + * A common demo box super class. + * + * @author Kevin Glass + */ +public abstract class AbstractPhysicsDemo extends BasicGame implements KeyboardSupport { + + + /** The world containing the physics model */ + public World world = new World(new Vector2f(0.0f, 10.0f), 10, new QuadSpaceStrategy(20,5)); + + + /** True if we should reset the demo on the next loop */ + public boolean needsReset; + /** True if we should render normals */ + public boolean normals = true; + /** True if we should render contact points */ + public boolean contacts = true; + + + + public AbstractPhysicsDemo(String title, int w, int h) { + super(title, w, h); + initDemo(); + + } + + public void handleKeyRelease(int keyCode){ + char c = (char) keyCode; + keyHit(c); + + } + + + /** + * Notification that a key was pressed + * + * @param c The character of key hit + */ + protected void keyHit(char c) { + if (c == 'r') { + needsReset = true; + } + if (c == 'c') { + normals = !normals; + contacts = !contacts; + } + } + + + public void render(Graphics2D g){ + fillWithColor(WHITE); + draw(g); + } + + public void update(){ + + for (int i=0;i<5;i++) { + world.step(); + } + + + if (needsReset) { + world.clear(); + initDemo(); + needsReset = false; + + } + } + + + + /** + * Draw a specific contact point determined from the simulation + * + * @param g The graphics context on which to draw + * @param contact The contact to draw + */ + protected void drawContact(Graphics2D g, Contact contact) { + int x = (int) contact.getPosition().getX(); + int y = (int) contact.getPosition().getY(); + if (contacts) { + g.setColor(Color.blue); + g.fillOval(x-3,y-3,6,6); + } + + if (normals) { + int dx = (int) (contact.getNormal().getX() * 10); + int dy = (int) (contact.getNormal().getY() * 10); + g.setColor(Color.darkGray); + g.drawLine(x,y,x+dx,y+dy); + } + } + + /** + * Draw a body + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + */ + protected void drawBody(Graphics2D g, Body body) { + if (body.getShape() instanceof Box) { + drawBoxBody(g,body,(Box) body.getShape()); + } + if (body.getShape() instanceof Circle) { + drawCircleBody(g,body,(Circle) body.getShape()); + } + if (body.getShape() instanceof Line) { + drawLineBody(g,body,(Line) body.getShape()); + } + if (body.getShape() instanceof Polygon) { + drawPolygonBody(g,body,(Polygon) body.getShape()); + } + } + + /** + * Draw a polygon into the demo + * + * @param g The graphics to draw the poly onto + * @param body The body describing the poly's position + * @param poly The poly to be drawn + */ + protected void drawPolygonBody(Graphics2D g, Body body, Polygon poly) { + g.setColor(Color.black); + + ROVector2f[] verts = poly.getVertices(body.getPosition(), body.getRotation()); + for ( int i = 0, j = verts.length-1; i < verts.length; j = i, i++ ) { + g.drawLine( + (int) (0.5f + verts[i].getX()), + (int) (0.5f + verts[i].getY()), + (int) (0.5f + verts[j].getX()), + (int) (0.5f + verts[j].getY())); + } + } + + /** + * Draw a line into the demo + * + * @param g The graphics to draw the line onto + * @param body The body describing the line's position + * @param line The line to be drawn + */ + protected void drawLineBody(Graphics2D g, Body body, Line line) { + g.setColor(Color.black); + +// float x = body.getPosition().getX(); +// float y = body.getPosition().getY(); +// float dx = line.getDX(); +// float dy = line.getDY(); + +// g.drawLine((int) x,(int) y,(int) (x+dx),(int) (y+dy)); + Vector2f[] verts = line.getVertices(body.getPosition(), body.getRotation()); + g.drawLine( + (int) verts[0].getX(), + (int) verts[0].getY(), + (int) verts[1].getX(), + (int) verts[1].getY()); + } + + /** + * Draw a circle in the world + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + * @param circle The shape to be drawn + */ + protected void drawCircleBody(Graphics2D g, Body body, Circle circle) { + g.setColor(Color.black); + float x = body.getPosition().getX(); + float y = body.getPosition().getY(); + float r = circle.getRadius(); + float rot = body.getRotation(); + float xo = (float) (Math.cos(rot) * r); + float yo = (float) (Math.sin(rot) * r); + + g.drawOval((int) (x-r),(int) (y-r),(int) (r*2),(int) (r*2)); + g.drawLine((int) x,(int) y,(int) (x+xo),(int) (y+yo)); + } + + /** + * Draw a box in the world + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + * @param box The shape to be drawn + */ + protected void drawBoxBody(Graphics2D g, Body body, Box box) { + Vector2f[] pts = box.getPoints(body.getPosition(), body.getRotation()); + + Vector2f v1 = pts[0]; + Vector2f v2 = pts[1]; + Vector2f v3 = pts[2]; + Vector2f v4 = pts[3]; + + g.setColor(Color.black); + g.drawLine((int) v1.x,(int) v1.y,(int) v2.x,(int) v2.y); + g.drawLine((int) v2.x,(int) v2.y,(int) v3.x,(int) v3.y); + g.drawLine((int) v3.x,(int) v3.y,(int) v4.x,(int) v4.y); + g.drawLine((int) v4.x,(int) v4.y,(int) v1.x,(int) v1.y); + } + + /** + * Draw a joint + * + * @param g The graphics contact on which to draw + * @param j The joint to be drawn + */ + public void drawJoint(Graphics2D g, Joint j) { + if (j instanceof FixedJoint) { + FixedJoint joint = (FixedJoint) j; + + g.setColor(Color.red); + float x1 = joint.getBody1().getPosition().getX(); + float x2 = joint.getBody2().getPosition().getX(); + float y1 = joint.getBody1().getPosition().getY(); + float y2 = joint.getBody2().getPosition().getY(); + + g.drawLine((int) x1,(int) y1,(int) x2,(int) y2); + } + if(j instanceof SlideJoint){ + SlideJoint joint = (SlideJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getAnchor2()); + p2.add(x2); + + Vector2f im = new Vector2f(p2); + im.sub(p1); + im.normalise(); + + + + g.setColor(Color.red); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+im.x*joint.getMinDistance()),(int)(p1.y+im.y*joint.getMinDistance())); + g.setColor(Color.blue); + g.drawLine((int)(p1.x+im.x*joint.getMinDistance()),(int)(p1.y+im.y*joint.getMinDistance()),(int)(p1.x+im.x*joint.getMaxDistance()),(int)(p1.y+im.y*joint.getMaxDistance())); + } + if(j instanceof AngleJoint){ + AngleJoint angleJoint = (AngleJoint)j; + Body b1 = angleJoint.getBody1(); + Body b2 = angleJoint.getBody2(); + float RA = j.getBody1().getRotation() + angleJoint.getRotateA(); + float RB = j.getBody1().getRotation() + angleJoint.getRotateB(); + + Vector2f VA = new Vector2f((float) Math.cos(RA), (float) Math.sin(RA)); + Vector2f VB = new Vector2f((float) Math.cos(RB), (float) Math.sin(RB)); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,angleJoint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,angleJoint.getAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+VA.x*20),(int)(p1.y+VA.y*20)); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+VB.x*20),(int)(p1.y+VB.y*20)); + } + if (j instanceof BasicJoint) { + BasicJoint joint = (BasicJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getLocalAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getLocalAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) x1.getX(), (int) x1.getY(), (int) p1.x, (int) p1.y); + g.drawLine((int) p1.x, (int) p1.y, (int) x2.getX(), (int) x2.getY()); + g.drawLine((int) x2.getX(), (int) x2.getY(), (int) p2.x, (int) p2.y); + g.drawLine((int) p2.x, (int) p2.y, (int) x1.getX(), (int) x1.getY()); + } + if(j instanceof DistanceJoint){ + DistanceJoint joint = (DistanceJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.x, (int) p2.y); + } + if (j instanceof SpringJoint) { + SpringJoint joint = (SpringJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getLocalAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getLocalAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) x1.getX(), (int) x1.getY(), (int) p1.x, (int) p1.y); + g.drawLine((int) p1.x, (int) p1.y, (int) p2.getX(), (int) p2.getY()); + g.drawLine((int) p2.getX(), (int) p2.getY(), (int) x2.getX(), (int) x2.getY()); + } + } + + /** + * Draw the whole simulation + * + * @param g The graphics context on which to draw + */ + protected void draw(Graphics2D g) { + BodyList bodies = world.getBodies(); + + for (int i=0;i<bodies.size();i++) { + Body body = bodies.get(i); + + drawBody(g, body); + } + + JointList joints = world.getJoints(); + + for (int i=0;i<joints.size();i++) { + Joint joint = joints.get(i); + + drawJoint(g, joint); + } + + ArbiterList arbs = world.getArbiters(); + + for (int i=0;i<arbs.size();i++) { + Arbiter arb = arbs.get(i); + + Contact[] contacts = arb.getContacts(); + int numContacts = arb.getNumContacts(); + + for (int j=0;j<numContacts;j++) { + drawContact(g, contacts[j]); + } + } + } + + /** + * Initialise the demo - clear the world + */ + public final void initDemo() { + world.clear(); + world.setGravity(0,10); + + init(world); + } + + /** + * Should be implemented by the demo, add the bodies/joints + * to the world. + * + * @param world The world in which the simulation is going to run + */ + public abstract void init(World world); + +} + diff --git a/experimental/physics/AbstractPhysicsEngine.java b/experimental/physics/AbstractPhysicsEngine.java new file mode 100644 index 0000000..5fc0633 --- /dev/null +++ b/experimental/physics/AbstractPhysicsEngine.java @@ -0,0 +1,381 @@ +package experimental.physics; + +import java.awt.Color; +import java.awt.Graphics2D; + +import net.phys2d.math.MathUtil; +import net.phys2d.math.Matrix2f; +import net.phys2d.math.ROVector2f; +import net.phys2d.math.Vector2f; +import net.phys2d.raw.AngleJoint; +import net.phys2d.raw.Arbiter; +import net.phys2d.raw.ArbiterList; +import net.phys2d.raw.BasicJoint; +import net.phys2d.raw.Body; +import net.phys2d.raw.BodyList; +import net.phys2d.raw.Contact; +import net.phys2d.raw.DistanceJoint; +import net.phys2d.raw.FixedJoint; +import net.phys2d.raw.Joint; +import net.phys2d.raw.JointList; +import net.phys2d.raw.SlideJoint; +import net.phys2d.raw.SpringJoint; +import net.phys2d.raw.World; +import net.phys2d.raw.shapes.Box; +import net.phys2d.raw.shapes.Circle; +import net.phys2d.raw.shapes.Line; +import net.phys2d.raw.shapes.Polygon; +import net.phys2d.raw.strategies.QuadSpaceStrategy; + +public abstract class AbstractPhysicsEngine { + + + // TODO world should be created using user dimensions + /** The world containing the physics model */ + public World world; + + + /** True if we should reset the demo on the next loop */ + public boolean needsReset; + /** True if we should render normals */ + public boolean normals = true; + /** True if we should render contact points */ + public boolean contacts = true; + + /** Edge color in debug mode **/ + public Color renderColor = Color.black; + + /** Number of simulation steps for rendering frame **/ + public int stepsPerFrame = 5; + + public AbstractPhysicsEngine(){ + world = new World(new Vector2f(0.0f, 10.0f), 10, new QuadSpaceStrategy(20,5)); + init(); + } + + /** + * This is where all the physical bodies and models should be created + */ + public abstract void init(); + + public void update(){ + + for(int i = 0; i < stepsPerFrame; i++) { + world.step(); + } + + + if (needsReset) { + world.clear(); + init(); + needsReset = false; + + } + } + + public void render(Graphics2D g){ + draw(g); + } + + + + + /** + * Draw a specific contact point determined from the simulation + * + * @param g The graphics context on which to draw + * @param contact The contact to draw + */ + protected void drawContact(Graphics2D g, Contact contact) { + int x = (int) contact.getPosition().getX(); + int y = (int) contact.getPosition().getY(); + if (contacts) { + g.setColor(Color.blue); + g.fillOval(x-3,y-3,6,6); + } + + if (normals) { + int dx = (int) (contact.getNormal().getX() * 10); + int dy = (int) (contact.getNormal().getY() * 10); + g.setColor(Color.darkGray); + g.drawLine(x,y,x+dx,y+dy); + } + } + + /** + * Draw a body + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + */ + protected void drawBody(Graphics2D g, Body body) { + if (body.getShape() instanceof Box) { + drawBoxBody(g,body,(Box) body.getShape()); + } + if (body.getShape() instanceof Circle) { + drawCircleBody(g,body,(Circle) body.getShape()); + } + if (body.getShape() instanceof Line) { + drawLineBody(g,body,(Line) body.getShape()); + } + if (body.getShape() instanceof Polygon) { + drawPolygonBody(g,body,(Polygon) body.getShape()); + } + } + + /** + * Draw a polygon into the demo + * + * @param g The graphics to draw the poly onto + * @param body The body describing the poly's position + * @param poly The poly to be drawn + */ + protected void drawPolygonBody(Graphics2D g, Body body, Polygon poly) { + g.setColor(renderColor); + + ROVector2f[] verts = poly.getVertices(body.getPosition(), body.getRotation()); + for ( int i = 0, j = verts.length-1; i < verts.length; j = i, i++ ) { + g.drawLine( + (int) (0.5f + verts[i].getX()), + (int) (0.5f + verts[i].getY()), + (int) (0.5f + verts[j].getX()), + (int) (0.5f + verts[j].getY())); + } + } + + /** + * Draw a line into the demo + * + * @param g The graphics to draw the line onto + * @param body The body describing the line's position + * @param line The line to be drawn + */ + protected void drawLineBody(Graphics2D g, Body body, Line line) { + g.setColor(renderColor); + + Vector2f[] verts = line.getVertices(body.getPosition(), body.getRotation()); + g.drawLine( + (int) verts[0].getX(), + (int) verts[0].getY(), + (int) verts[1].getX(), + (int) verts[1].getY()); + } + + /** + * Draw a circle in the world + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + * @param circle The shape to be drawn + */ + protected void drawCircleBody(Graphics2D g, Body body, Circle circle) { + g.setColor(renderColor); + float x = body.getPosition().getX(); + float y = body.getPosition().getY(); + float r = circle.getRadius(); + float rot = body.getRotation(); + float xo = (float) (Math.cos(rot) * r); + float yo = (float) (Math.sin(rot) * r); + + g.drawOval((int) (x-r),(int) (y-r),(int) (r*2),(int) (r*2)); + g.drawLine((int) x,(int) y,(int) (x+xo),(int) (y+yo)); + } + + /** + * Draw a box in the world + * + * @param g The graphics contact on which to draw + * @param body The body to be drawn + * @param box The shape to be drawn + */ + protected void drawBoxBody(Graphics2D g, Body body, Box box) { + Vector2f[] pts = box.getPoints(body.getPosition(), body.getRotation()); + + Vector2f v1 = pts[0]; + Vector2f v2 = pts[1]; + Vector2f v3 = pts[2]; + Vector2f v4 = pts[3]; + + g.setColor(renderColor); + g.drawLine((int) v1.x,(int) v1.y,(int) v2.x,(int) v2.y); + g.drawLine((int) v2.x,(int) v2.y,(int) v3.x,(int) v3.y); + g.drawLine((int) v3.x,(int) v3.y,(int) v4.x,(int) v4.y); + g.drawLine((int) v4.x,(int) v4.y,(int) v1.x,(int) v1.y); + } + + /** + * Draw a joint + * + * @param g The graphics contact on which to draw + * @param j The joint to be drawn + */ + public void drawJoint(Graphics2D g, Joint j) { + if (j instanceof FixedJoint) { + FixedJoint joint = (FixedJoint) j; + + g.setColor(Color.red); + float x1 = joint.getBody1().getPosition().getX(); + float x2 = joint.getBody2().getPosition().getX(); + float y1 = joint.getBody1().getPosition().getY(); + float y2 = joint.getBody2().getPosition().getY(); + + g.drawLine((int) x1,(int) y1,(int) x2,(int) y2); + } + if(j instanceof SlideJoint){ + SlideJoint joint = (SlideJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getAnchor2()); + p2.add(x2); + + Vector2f im = new Vector2f(p2); + im.sub(p1); + im.normalise(); + + + + g.setColor(Color.red); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+im.x*joint.getMinDistance()),(int)(p1.y+im.y*joint.getMinDistance())); + g.setColor(Color.blue); + g.drawLine((int)(p1.x+im.x*joint.getMinDistance()),(int)(p1.y+im.y*joint.getMinDistance()),(int)(p1.x+im.x*joint.getMaxDistance()),(int)(p1.y+im.y*joint.getMaxDistance())); + } + if(j instanceof AngleJoint){ + AngleJoint angleJoint = (AngleJoint)j; + Body b1 = angleJoint.getBody1(); + Body b2 = angleJoint.getBody2(); + float RA = j.getBody1().getRotation() + angleJoint.getRotateA(); + float RB = j.getBody1().getRotation() + angleJoint.getRotateB(); + + Vector2f VA = new Vector2f((float) Math.cos(RA), (float) Math.sin(RA)); + Vector2f VB = new Vector2f((float) Math.cos(RB), (float) Math.sin(RB)); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,angleJoint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,angleJoint.getAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+VA.x*20),(int)(p1.y+VA.y*20)); + g.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+VB.x*20),(int)(p1.y+VB.y*20)); + } + if (j instanceof BasicJoint) { + BasicJoint joint = (BasicJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getLocalAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getLocalAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) x1.getX(), (int) x1.getY(), (int) p1.x, (int) p1.y); + g.drawLine((int) p1.x, (int) p1.y, (int) x2.getX(), (int) x2.getY()); + g.drawLine((int) x2.getX(), (int) x2.getY(), (int) p2.x, (int) p2.y); + g.drawLine((int) p2.x, (int) p2.y, (int) x1.getX(), (int) x1.getY()); + } + if(j instanceof DistanceJoint){ + DistanceJoint joint = (DistanceJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.x, (int) p2.y); + } + if (j instanceof SpringJoint) { + SpringJoint joint = (SpringJoint) j; + + Body b1 = joint.getBody1(); + Body b2 = joint.getBody2(); + + Matrix2f R1 = new Matrix2f(b1.getRotation()); + Matrix2f R2 = new Matrix2f(b2.getRotation()); + + ROVector2f x1 = b1.getPosition(); + Vector2f p1 = MathUtil.mul(R1,joint.getLocalAnchor1()); + p1.add(x1); + + ROVector2f x2 = b2.getPosition(); + Vector2f p2 = MathUtil.mul(R2,joint.getLocalAnchor2()); + p2.add(x2); + + g.setColor(Color.red); + g.drawLine((int) x1.getX(), (int) x1.getY(), (int) p1.x, (int) p1.y); + g.drawLine((int) p1.x, (int) p1.y, (int) p2.getX(), (int) p2.getY()); + g.drawLine((int) p2.getX(), (int) p2.getY(), (int) x2.getX(), (int) x2.getY()); + } + } + + /** + * Draw the whole simulation + * + * @param g The graphics context on which to draw + */ + protected void draw(Graphics2D g) { + BodyList bodies = world.getBodies(); + + for (int i=0;i<bodies.size();i++) { + Body body = bodies.get(i); + + drawBody(g, body); + } + + JointList joints = world.getJoints(); + + for (int i=0;i<joints.size();i++) { + Joint joint = joints.get(i); + + drawJoint(g, joint); + } + + ArbiterList arbs = world.getArbiters(); + + for (int i=0;i<arbs.size();i++) { + Arbiter arb = arbs.get(i); + + Contact[] contacts = arb.getContacts(); + int numContacts = arb.getNumContacts(); + + for (int j=0;j<numContacts;j++) { + drawContact(g, contacts[j]); + } + } + } + + +} diff --git a/kobaltBasic/BasicActor.java b/kobaltBasic/BasicActor.java new file mode 100644 index 0000000..13ef5d4 --- /dev/null +++ b/kobaltBasic/BasicActor.java @@ -0,0 +1,114 @@ +package kobaltBasic; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; + + +/** + * The most basic of game-play elements. This class should act as a base for all playable, + * non-playable, and interactive game elements. A GameEntity object can hold a sprite (single / + * multiple frames), along with coordinates and dimension. It also handles it own rendering. + * Any sub-class can initialize it with a sprite and change the {@code x_velocity} and + * {@code y_velocity} variables to be able to the entity. Use the {@link KeyboardSupport} + * and/or {@link MouseSupport} interfaces for implementing playable characters. + * + * @author Shahriar Haque + * Last Modified: 18 December, 2008 + * + */ +public abstract class BasicActor { + + //changed accessor to public on June 13, 2008 + public double x,y; // changed type to double on December 18, 2008 + + + /** 2d component of the velocity vector **/ + public double x_velocity = 0, y_velocity = 0; + + public static final int RIGHT = KeyEvent.VK_RIGHT; + public static final int LEFT = KeyEvent.VK_LEFT; + public static final int UP = KeyEvent.VK_UP; + public static final int DOWN = KeyEvent.VK_DOWN; + + public int UPDATE_INTERVAL = 40; + public int lastUpdated = 0; + + + Area vectorBound = null; + + /** If true, the outline of the bound will be overlayed on the sprite **/ + public boolean drawVector = false; + + + /** + * Initializes a new GameEntity and places it at the given location. + * @param posX X Position + * @param posY Y Position + */ + public BasicActor(double x, double y){ + this.x = x; + this.y = y; + } + + + + /** + * Updates the (x,y) coordinates by adding the {@code x_velocity} and {@code y_velocity} + * parameters. + * + */ + public void update(){ + + float fraction = (BasicGame.interval/1000.0f); + + x += (x_velocity * fraction) ; + y += (y_velocity * fraction) ; + } + + /** + * Renders the GameEntity on the given graphics context{@code (g)}. Rendering is performed at + * the (x,y) location of the instance. + * @param g The graphics context on to which the GameEntity is to be drawn. + */ + public abstract void render(Graphics2D g); + + + public void renderBounds(Graphics2D g){ + g.setColor(Color.white); + g.draw(getBounds()); + } + + public void setBounds(Area a){ vectorBound = a; } + + /** + * Returns a new instance of the bounding Area with the latest translations applied. + * @return + */ + public Area getBounds(){ + AffineTransform transform = new AffineTransform(); + transform.translate(x, y); + + return vectorBound.createTransformedArea(transform); + + } + + /** + * Returns true if the current VectorGameEntity's bound intersects the bound of the other. + * @param vge The other VectorGameEntity + * @return + */ + public boolean collides(BasicActor actor){ + Area a1 = getBounds(); + Area a2 = actor.getBounds(); + + a1.intersect(a2); + + return !a1.isEmpty(); // if two shapes collide, their intersection is not empty + } + + + +} diff --git a/kobaltBasic/BasicGame.java b/kobaltBasic/BasicGame.java new file mode 100644 index 0000000..ad8ac0b --- /dev/null +++ b/kobaltBasic/BasicGame.java @@ -0,0 +1,262 @@ +package kobaltBasic; + +import java.awt.Color; +import java.awt.DisplayMode; +import java.awt.Graphics2D; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Shape; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.awt.image.BufferStrategy; +import java.awt.image.BufferedImage; +import java.util.ArrayList; + +import javax.swing.JFrame; + +import experimental.network.NetworkService; + + +/** + * This provides all the necessary GUI and graphics infrastructure on which a 2D game can run + * on. The ControlledByKeyboard and ControlledByMouse interfaces provide keyboard and mouse playing + * functionality to the game. In order to use the facilities of this class, extend it and call + * the {@link #start()} method to begin the game. + * @author Shahriar Haque + * + * + */ +public abstract class BasicGame extends GameScreen { + + /** Width of the game window **/ + private final int screenWidth; + + /** Height of the game window **/ + private final int screenHeight; + + private final String gameTitle; + + /** Interval between now and the last time a time sample was taken **/ + public static long interval = 0; + + /** + * This is the time interval (in milliseconds) between each rendering loop of the game. + * Lower this only if your game is appearing to run slowly. + */ + public int REFRESH_INTERVAL = 10; + + /** The back buffer onto which all game graphics are drawn. **/ + public static BufferedImage backBuffer; + + private final Graphics2D bufferGraphics; + + private final GameWindow gWin; + + public static final Color WHITE = Color.white; + public static final Color BLACK = Color.black; + + /** Arraylist that holds various game screens (e.g. Intro menu, pause menu, inventory etc.) **/ + public static final ArrayList<GameScreen> screenList = new ArrayList<GameScreen>(); + + /** The index of the current screen within the screen list array **/ + public static int currentScreen = 0; + + public NetworkService netService; + + public boolean fullScreen = false; + private DisplayMode displayMode; + + // end of variable declaration + + /** + * Constructor that initializes the GUI window in which the game runs. + * @param title The title of the game GUI window. + * @param w Width of the window in pixels. + * @param h Height of the window in pixels. + */ + public BasicGame(String title, int w, int h){ + gameTitle = title; + screenWidth = w; + screenHeight = h; + + backBuffer = new BufferedImage(screenWidth,screenHeight,BufferedImage.TYPE_INT_RGB); + bufferGraphics = (Graphics2D) backBuffer.getGraphics(); + + gWin = new GameWindow(gameTitle,screenWidth,screenHeight); + + screenList.add(this); // the main game screen itself is one of the screens + + } + + public BasicGame(String title, int w, int h, boolean fullScreen){ + this(title,w,h); + if(!fullScreen) return; + + displayMode = new DisplayMode(w,h,32,0); + } + + /** + * Draws the given text on the screen with the given Color + * @param text The string to be drawn on the screen. + * @param x X coordinate. + * @param y Y coordiante. + * @param c Color of the text. + */ + public void drawText(String text, int x, int y, Color c){ + bufferGraphics.setColor(c); + bufferGraphics.drawString(text, x, y); + } + + /** + * Flood fills the screen with the given color. + * @param c Flood-fill color. + */ + public void fillWithColor(Color c){ + bufferGraphics.setColor(c); + bufferGraphics.fillRect(0, 0, screenWidth, screenHeight); + } + + /** + * Draws any arbitrary geometrical object that implements the {@link Shape} interface. + * @param s The shape to be drawn. + * @param c Color of the shape's outline. + */ + public void drawShape(Shape s, Color c){ + bufferGraphics.setColor(c); + bufferGraphics.draw(s); + } + + public void addNetworkService(NetworkService net){ + netService = net; + } + + + /** + * Starts the main game loop and runs it continuously. Frame rate of the is controlled through + * the game is controlled via the {@link #REFRESH_INTERVAL} field. + */ + public void start(){ + + long startTime = System.currentTimeMillis(); + + GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); + GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice(); + DisplayMode originalDisplayMode = graphicsDevice.getDisplayMode(); + + + gWin.createBufferStrategy(2); + BufferStrategy bufferStrategy = gWin.getBufferStrategy(); + + + if(fullScreen){ + gWin.setUndecorated(true); + gWin.setIgnoreRepaint(true); + graphicsDevice.setFullScreenWindow(gWin); + if (graphicsDevice.isDisplayChangeSupported()) graphicsDevice.setDisplayMode(displayMode); + else{ + System.out.println("Display Mode could not be changed"); + } + } + + + while(true){ + interval = System.currentTimeMillis() - startTime; + + screenList.get(currentScreen).update(); + startTime = System.currentTimeMillis(); + + screenList.get(currentScreen).render(bufferGraphics); // render of backbuffer + + gWin.screenGFX = (Graphics2D) bufferStrategy.getDrawGraphics(); + gWin.screenGFX.drawImage(backBuffer,0,0,null); + + bufferStrategy.show(); + + + if(gWin.screenGFX != null){ + gWin.screenGFX.dispose(); + } + + if(!gWin.isShowing()){ + gWin.dispose(); + break; + } + + try { Thread.sleep(REFRESH_INTERVAL); } catch(Exception e) {} + } + + + if(fullScreen){ + graphicsDevice.setDisplayMode(originalDisplayMode); + graphicsDevice.setFullScreenWindow(null); + } + + + } + + + private class GameWindow extends JFrame implements KeyListener, MouseListener, + MouseMotionListener, WindowListener{ + + private static final long serialVersionUID = 1L; + Graphics2D screenGFX; + + public GameWindow(String title, int w, int h){ + this.setTitle(title); + this.setSize(w, h); +// this.setResizable(false); + this.addKeyListener(this); + this.addMouseListener(this); + this.addMouseMotionListener(this); + this.addWindowListener(this); + this.setIgnoreRepaint(true); + this.setVisible(true); + this.setIgnoreRepaint(true); + + } + + + public void keyPressed(KeyEvent k) { screenList.get(currentScreen).listenToKeyPress(k); } + + public void keyReleased(KeyEvent k) { screenList.get(currentScreen).listenToKeyRelease(k); } + + public void mouseClicked(MouseEvent m) { screenList.get(currentScreen).listenToMouseClick(m); } + + public void mousePressed(MouseEvent m) { screenList.get(currentScreen).listenToMousePress(m); } + + public void mouseReleased(MouseEvent m) { screenList.get(currentScreen).listenToMouseRelease(m); } + + public void mouseMoved(MouseEvent m) { screenList.get(currentScreen).listenToMouseMove(m); } + + public void mouseDragged(MouseEvent m) {} + public void keyTyped(KeyEvent k) {} + public void mouseEntered(MouseEvent arg0) {} + public void mouseExited(MouseEvent arg0) {} + + public void windowActivated(WindowEvent arg0) {} + + public void windowClosed(WindowEvent e) {} + + public void windowClosing(WindowEvent e) { + if(netService != null) netService.closeSession(); + handleWindowClosing(e); + } + + public void windowDeactivated(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowIconified(WindowEvent e) {} + + public void windowOpened(WindowEvent e) {} + + } // end of private class GameWindow + + + +} diff --git a/kobaltBasic/GameScreen.java b/kobaltBasic/GameScreen.java new file mode 100644 index 0000000..47c567b --- /dev/null +++ b/kobaltBasic/GameScreen.java @@ -0,0 +1,77 @@ +package kobaltBasic; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.ArrayList; + +public abstract class GameScreen { + + private final ArrayList<KeyboardSupport> kbControls = new ArrayList<KeyboardSupport>(); + private final ArrayList<MouseSupport> msControls = new ArrayList<MouseSupport>(); + private final ArrayList<WindowListener> winListeners = new ArrayList<WindowListener>(); + + /** + * Adds the functionality of being able to be controlled by the keyboard to the passed object. + * @param cbk The game element that is to be controlled by keyboard. + */ + public void addKeyboardSupport(KeyboardSupport cbk){ kbControls.add(cbk); } + + /** + * Adds the functionality of being able to be controlled by the mouse to the passed object. + * @param cbm The game element that is to be controlled by mouse. + */ + public void addMouseSupport(MouseSupport cbm){ msControls.add(cbm); } + + + public void addWindowListener(WindowListener winListener) { winListeners.add(winListener); } + + + + // public final helper methods + + public final void listenToKeyPress(KeyEvent k){ + for(KeyboardSupport cbk: kbControls) cbk.handleKeyPress(k.getKeyCode()); + } + + public final void listenToKeyRelease(KeyEvent k){ + for(KeyboardSupport cbk: kbControls) cbk.handleKeyRelease(k.getKeyCode()); + } + + public final void listenToMousePress(MouseEvent m){ + for(MouseSupport cbm: msControls) cbm.handleMousePress(m.getX(),m.getY()); + } + + public final void listenToMouseRelease(MouseEvent m){ + for(MouseSupport cbm: msControls) cbm.handleMouseRelease(m.getX(),m.getY()); + } + + public final void listenToMouseClick(MouseEvent m){ + for(MouseSupport cbm: msControls) cbm.handleMouseClick(m.getX(),m.getY()); + } + + public final void listenToMouseMove(MouseEvent m){ + for(MouseSupport cbm: msControls) cbm.handleMouseMove(m.getX(),m.getY()); + } + + public final void handleWindowClosing(WindowEvent e){ + for(WindowListener win: winListeners) win.windowClosing(e); + } + + + /** + * Renders all the game elements. Simply call the render(Graphics2D) method of your game + * elements if you do not wish to customize the rendering process. + * @param g The graphics context on to which the game elements are to be rendered. + */ + public abstract void render(Graphics2D g); + + /** + * Used to update the logic for all the game elements. This method is called during each + * iteration of the game loop. + */ + public abstract void update(); + +} diff --git a/kobaltBasic/KeyboardSupport.java b/kobaltBasic/KeyboardSupport.java new file mode 100644 index 0000000..c7f004d --- /dev/null +++ b/kobaltBasic/KeyboardSupport.java @@ -0,0 +1,23 @@ +package kobaltBasic; + +/** + * Provides the necessary methods to allow keyboard controlling features to your game and/or + * GameEntity objects. + * @author Shahriar Haque + * + */ +public interface KeyboardSupport { + + /** + * Handles the event of a key being pressed. + * @param keyCode The integer representation of the ascii value of the pressed key. + */ + public abstract void handleKeyPress(int keyCode); + + /** + * Handles the event of a key being released. + * @param keyCode The integer representation of the ascii value of the pressed key. + */ + public abstract void handleKeyRelease(int keyCode); + +} diff --git a/kobaltBasic/MaskedImage.java b/kobaltBasic/MaskedImage.java new file mode 100644 index 0000000..5b5580e --- /dev/null +++ b/kobaltBasic/MaskedImage.java @@ -0,0 +1,61 @@ +package kobaltBasic; + +import java.awt.image.BufferedImage; + +/** + * A masked image is an image that has different levels of transparency in different areas. + * The transparency (alpha) value is set using a mask image. Mask images, ideally, are gray-scale + * images. Black areas represent opaque, while white represent total transparency. Different + * shaded of gray are used to represent different levels of translucency. Masked images are useful + * for getting fine smoothened images for arbitrarily shaped sprites. Rotation of masked image + * sprites are also of very high quality. However, using large masked images in your game can + * drop your frame rate heavily. + * @author Shahriar Haque + * + */ +public class MaskedImage { + + private BufferedImage img,aMask; + + private BufferedImage maskedImage; + + /** + * Constructs a MaskedImage object based on the source image and using the gray-values + * from the alphaMask + * @param image The orginal colored source image. + * @param alphaMask The gray scale mask for the source image. + */ + public MaskedImage(BufferedImage image, BufferedImage alphaMask){ + img = image; + aMask = alphaMask; + + maskedImage = Utilities.applyAlphaMask(img, aMask); + } + + /** + * Constructs a MaskedImage object given the locations of the source and alpha mask images. + * @param imgPath Relative path to the source image. + * @param maskPath Relative path to the alpha mask. + */ + public MaskedImage(String imgPath, String maskPath){ + img = Utilities.load(imgPath); + aMask = Utilities.load(maskPath); + + maskedImage = Utilities.applyAlphaMask(img, aMask); + } + + /** + * Returns the original (un-altered) source image. + * @return Source Image + */ + public BufferedImage getImage() { return img; } + + /** + * Returns a BufferedImage on which the alpha mask has been applied. + * @return An alpha-masked image. + */ + public BufferedImage getMaskedImage() { return maskedImage; } + + + +} diff --git a/kobaltBasic/MouseSupport.java b/kobaltBasic/MouseSupport.java new file mode 100644 index 0000000..673de77 --- /dev/null +++ b/kobaltBasic/MouseSupport.java @@ -0,0 +1,38 @@ +package kobaltBasic; + +/** + * Provides the necessary methods to allow a game-element to be mouse-controlled. + * @author Shahriar Haque + * + */ +public interface MouseSupport { + + /** + * Handles the event of a mouse click on the given location. + * @param x X Coordinate + * @param y Y Coordinate + */ + public abstract void handleMouseClick(int x, int y); + + /** + * Handles the event of a mouse button being pressed down at the given location. + * @param x X Coordinate + * @param y Y Coordinate + */ + public abstract void handleMousePress(int x, int y); + + /** + * Handles the event of a mouse button being released from the given location. + * @param x X Coordinate + * @param y Y Coordinate + */ + public abstract void handleMouseRelease(int x, int y); + + /** + * Handles the event of the mouse pointer being moved to another location. + * @param x X Coordinate + * @param y Y Coordinate + */ + public abstract void handleMouseMove(int x, int y); + +} diff --git a/kobaltBasic/RotatingActor.java b/kobaltBasic/RotatingActor.java new file mode 100644 index 0000000..3cfbcb4 --- /dev/null +++ b/kobaltBasic/RotatingActor.java @@ -0,0 +1,457 @@ +package kobaltBasic; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; + +/** + * An advanced version of the {@link BasicActor} class that allows high-precision rotation of the + * rendered images. Rotation is controlled through the <code>velocity</code> and the + * <code>heading</code> varaiables. Rendering of this type of game elements are optimized for + * quality and not for speed. + * @author Shahriar Haque + * + */ +public abstract class RotatingActor extends BasicActor { + + /** Heading independent velocity of the game elements. **/ + public double velocity; + + public double rotational_velocity = 0; + + public double anchor_x = 0; + public double anchor_y = 0; + + + /** Heading of the game element in degrees. **/ + public double heading; + + ///** X component of speed change **/ + //public int dx; + + ///** Y component of speed change **/ + //public int dy; + + private double tempHeading; + + + public RotatingActor(double x, double y) { + super(x,y); + } + + /** + * Modified version of the {@link BasicActor#update()} method that changes the location + * based on the <code>heading</code> and <code>velocity</code> values. The <code>x_velocity + * </code> and <code>y_velocity</code> variables are changed in this process. + */ + public void update(){ + + double fraction = (BasicGame.interval/1000.0); + + heading += rotational_velocity*fraction; + + tempHeading = (heading%360); // allows full 360 rotation + + if(tempHeading < 0) tempHeading += 360; // fixes negative headings + + x_velocity = velocity*sineTable[(int)tempHeading]; + y_velocity = -velocity*sineTable[(int)( (tempHeading+90)%360 )]; + + + x += (x_velocity * fraction); + y += (y_velocity * fraction); + + } + + /** + * Renders high-quality rotated images of the GameEntity using bilinear interpolation with anti-aliasing. + * @param g The graphics context on to which the sprite is to be rendered. + */ + public abstract void render(Graphics2D g); + + public void renderBounds(Graphics2D g){ + g.setColor(Color.white); + g.draw(getBounds()); + + } + + + public Area getBounds(){ + AffineTransform transform = new AffineTransform(); + transform.translate(x, y); + + double theta = Math.toRadians(heading); + transform.rotate(theta, 0, 0); + + return vectorBound.createTransformedArea(transform); + + + } + + + public static final float[] sineTable = new float[]{ + 0.0f , + 0.01745240643728351f , + 0.03489949670250097f , + 0.05233595624294383f , + 0.0697564737441253f , + 0.08715574274765817f , + 0.10452846326765346f , + 0.12186934340514748f , + 0.13917310096006544f , + 0.15643446504023087f , + 0.17364817766693033f , + 0.1908089953765448f , + 0.20791169081775931f , + 0.22495105434386498f , + 0.24192189559966773f , + 0.25881904510252074f , + 0.27563735581699916f , + 0.2923717047227367f , + 0.3090169943749474f , + 0.3255681544571567f , + 0.3420201433256687f , + 0.35836794954530027f , + 0.374606593415912f , + 0.3907311284892737f , + 0.40673664307580015f , + 0.42261826174069944f , + 0.4383711467890774f , + 0.45399049973954675f , + 0.4694715627858908f , + 0.48480962024633706f , + 0.49999999999999994f , + 0.5150380749100542f , + 0.5299192642332049f , + 0.544639035015027f , + 0.5591929034707468f , + 0.573576436351046f , + 0.5877852522924731f , + 0.6018150231520483f , + 0.6156614753256583f , + 0.6293203910498375f , + 0.6427876096865393f , + 0.6560590289905073f , + 0.6691306063588582f , + 0.6819983600624985f , + 0.6946583704589973f , + 0.7071067811865475f , + 0.7193398003386511f , + 0.7313537016191705f , + 0.7431448254773942f , + 0.7547095802227719f , + 0.766044443118978f , + 0.7771459614569708f , + 0.7880107536067219f , + 0.7986355100472928f , + 0.8090169943749475f , + 0.8191520442889918f , + 0.8290375725550417f , + 0.8386705679454239f , + 0.8480480961564261f , + 0.8571673007021122f , + 0.8660254037844386f , + 0.8746197071393957f , + 0.8829475928589269f , + 0.8910065241883678f , + 0.898794046299167f , + 0.9063077870366499f , + 0.9135454576426009f , + 0.9205048534524404f , + 0.9271838545667873f , + 0.9335804264972017f , + 0.9396926207859083f , + 0.9455185755993167f , + 0.9510565162951535f , + 0.9563047559630354f , + 0.9612616959383189f , + 0.9659258262890683f , + 0.9702957262759965f , + 0.9743700647852352f , + 0.9781476007338057f , + 0.981627183447664f , + 0.984807753012208f , + 0.9876883405951378f , + 0.9902680687415704f , + 0.992546151641322f , + 0.9945218953682733f , + 0.9961946980917455f , + 0.9975640502598242f , + 0.9986295347545738f , + 0.9993908270190958f , + 0.9998476951563913f , + 1.0f , + 0.9998476951563913f , + 0.9993908270190958f , + 0.9986295347545738f , + 0.9975640502598242f , + 0.9961946980917455f , + 0.9945218953682734f , + 0.9925461516413221f , + 0.9902680687415704f , + 0.9876883405951377f , + 0.984807753012208f , + 0.981627183447664f , + 0.9781476007338057f , + 0.9743700647852352f , + 0.9702957262759965f , + 0.9659258262890683f , + 0.9612616959383189f , + 0.9563047559630355f , + 0.9510565162951536f , + 0.9455185755993168f , + 0.9396926207859084f , + 0.9335804264972017f , + 0.9271838545667874f , + 0.9205048534524404f , + 0.913545457642601f , + 0.90630778703665f , + 0.8987940462991669f , + 0.8910065241883679f , + 0.8829475928589271f , + 0.8746197071393959f , + 0.8660254037844387f , + 0.8571673007021123f , + 0.8480480961564261f , + 0.838670567945424f , + 0.8290375725550417f , + 0.819152044288992f , + 0.8090169943749475f , + 0.7986355100472927f , + 0.788010753606722f , + 0.777145961456971f , + 0.766044443118978f , + 0.7547095802227721f , + 0.7431448254773945f , + 0.7313537016191706f , + 0.7193398003386511f , + 0.7071067811865476f , + 0.6946583704589975f , + 0.6819983600624986f , + 0.669130606358858f , + 0.6560590289905073f , + 0.6427876096865395f , + 0.6293203910498374f , + 0.6156614753256584f , + 0.6018150231520486f , + 0.5877852522924732f , + 0.5735764363510459f , + 0.5591929034707469f , + 0.5446390350150273f , + 0.5299192642332049f , + 0.5150380749100544f , + 0.49999999999999994f , + 0.48480962024633717f , + 0.4694715627858907f , + 0.45399049973954686f , + 0.4383711467890777f , + 0.4226182617406995f , + 0.40673664307580004f , + 0.39073112848927377f , + 0.37460659341591224f , + 0.35836794954530066f , + 0.3420201433256689f , + 0.3255681544571566f , + 0.3090169943749475f , + 0.29237170472273705f , + 0.2756373558169992f , + 0.258819045102521f , + 0.24192189559966773f , + 0.2249510543438652f , + 0.20791169081775931f , + 0.19080899537654497f , + 0.17364817766693072f , + 0.15643446504023098f , + 0.13917310096006533f , + 0.12186934340514755f , + 0.10452846326765373f , + 0.0871557427476582f , + 0.06975647374412552f , + 0.05233595624294425f , + 0.03489949670250114f , + 0.01745240643728344f , + 0.0f , + -0.017452406437283192f , + -0.0348994967025009f , + -0.052335956242943564f , + -0.06975647374412483f , + -0.08715574274765794f , + -0.1045284632676535f , + -0.12186934340514775f , + -0.13917310096006552f , + -0.15643446504023073f , + -0.17364817766693047f , + -0.19080899537654472f , + -0.20791169081775907f , + -0.22495105434386498f , + -0.2419218955996675f , + -0.25881904510252035f , + -0.2756373558169986f , + -0.29237170472273677f , + -0.30901699437494773f , + -0.32556815445715676f , + -0.34202014332566866f , + -0.35836794954530043f , + -0.374606593415912f , + -0.39073112848927355f , + -0.4067366430757998f , + -0.4226182617406993f , + -0.43837114678907707f , + -0.45399049973954625f , + -0.4694715627858905f , + -0.48480962024633734f , + -0.5000000000000001f , + -0.5150380749100542f , + -0.5299192642332048f , + -0.5446390350150271f , + -0.5591929034707467f , + -0.5735764363510458f , + -0.587785252292473f , + -0.601815023152048f , + -0.6156614753256578f , + -0.6293203910498373f , + -0.6427876096865393f , + -0.6560590289905074f , + -0.6691306063588582f , + -0.6819983600624984f , + -0.6946583704589974f , + -0.7071067811865475f , + -0.7193398003386509f , + -0.7313537016191705f , + -0.743144825477394f , + -0.7547095802227717f , + -0.7660444431189779f , + -0.7771459614569711f , + -0.7880107536067221f , + -0.7986355100472928f , + -0.8090169943749473f , + -0.8191520442889916f , + -0.8290375725550414f , + -0.838670567945424f , + -0.848048096156426f , + -0.8571673007021121f , + -0.8660254037844385f , + -0.8746197071393955f , + -0.882947592858927f , + -0.8910065241883678f , + -0.8987940462991668f , + -0.90630778703665f , + -0.913545457642601f , + -0.9205048534524403f , + -0.9271838545667873f , + -0.9335804264972016f , + -0.9396926207859082f , + -0.9455185755993168f , + -0.9510565162951535f , + -0.9563047559630353f , + -0.9612616959383189f , + -0.9659258262890683f , + -0.9702957262759965f , + -0.9743700647852351f , + -0.9781476007338056f , + -0.981627183447664f , + -0.984807753012208f , + -0.9876883405951377f , + -0.9902680687415703f , + -0.992546151641322f , + -0.9945218953682733f , + -0.9961946980917455f , + -0.9975640502598242f , + -0.9986295347545739f , + -0.9993908270190958f , + -0.9998476951563913f , + -1.0f , + -0.9998476951563913f , + -0.9993908270190958f , + -0.9986295347545739f , + -0.9975640502598243f , + -0.9961946980917455f , + -0.9945218953682733f , + -0.992546151641322f , + -0.9902680687415704f , + -0.9876883405951378f , + -0.9848077530122081f , + -0.9816271834476641f , + -0.9781476007338056f , + -0.9743700647852352f , + -0.9702957262759966f , + -0.9659258262890684f , + -0.961261695938319f , + -0.9563047559630354f , + -0.9510565162951536f , + -0.945518575599317f , + -0.9396926207859083f , + -0.9335804264972017f , + -0.9271838545667874f , + -0.9205048534524405f , + -0.9135454576426011f , + -0.9063077870366503f , + -0.898794046299167f , + -0.891006524188368f , + -0.8829475928589271f , + -0.8746197071393956f , + -0.8660254037844386f , + -0.8571673007021123f , + -0.8480480961564261f , + -0.8386705679454243f , + -0.8290375725550416f , + -0.8191520442889918f , + -0.8090169943749476f , + -0.798635510047293f , + -0.7880107536067223f , + -0.7771459614569713f , + -0.7660444431189781f , + -0.7547095802227721f , + -0.743144825477394f , + -0.7313537016191703f , + -0.7193398003386511f , + -0.7071067811865477f , + -0.6946583704589976f , + -0.6819983600624989f , + -0.6691306063588588f , + -0.6560590289905074f , + -0.6427876096865396f , + -0.6293203910498372f , + -0.6156614753256582f , + -0.6018150231520483f , + -0.5877852522924734f , + -0.5735764363510465f , + -0.5591929034707473f , + -0.544639035015027f , + -0.529919264233205f , + -0.5150380749100545f , + -0.5000000000000004f , + -0.48480962024633767f , + -0.4694715627858908f , + -0.45399049973954697f , + -0.4383711467890778f , + -0.4226182617406992f , + -0.40673664307580015f , + -0.3907311284892739f , + -0.37460659341591235f , + -0.35836794954530077f , + -0.34202014332566943f , + -0.3255681544571567f , + -0.3090169943749476f , + -0.29237170472273716f , + -0.27563735581699894f , + -0.2588190451025207f , + -0.24192189559966787f , + -0.22495105434386534f , + -0.20791169081775987f , + -0.19080899537654467f , + -0.1736481776669304f , + -0.15643446504023112f , + -0.13917310096006588f , + -0.12186934340514811f , + -0.1045284632676543f , + -0.08715574274765832f , + -0.06975647374412564f , + -0.05233595624294348f , + -0.034899496702500823f , + -0.01745240643728356f , + 0.0f + }; + +} diff --git a/kobaltBasic/RotatingSpriteActor.java b/kobaltBasic/RotatingSpriteActor.java new file mode 100644 index 0000000..bcb8fe1 --- /dev/null +++ b/kobaltBasic/RotatingSpriteActor.java @@ -0,0 +1,66 @@ +package kobaltBasic; + +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.TexturePaint; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; + +public class RotatingSpriteActor extends RotatingActor { + + + public int width,height; + public final Sprite theSprite; + + public RotatingSpriteActor(Sprite s, double x, double y) { + super(x, y); + + theSprite = s; + width = s.getCurrentFrame().getWidth(); + height= s.getCurrentFrame().getHeight(); + anchor_x = width/2; + anchor_y = height/2; + + setBounds(new Area(new Rectangle((int)x,(int)y,width,height))); + + } + + public void update(){ + super.update(); + + if(lastUpdated >= UPDATE_INTERVAL){ + this.theSprite.advanceFrame(); + lastUpdated = 0; + } + + else lastUpdated += BasicGame.interval; + } + + public void render(Graphics2D g){ + + BufferedImage srcImage = theSprite.getCurrentFrame(); + + AffineTransform oldTransform = g.getTransform(); + + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + g.setPaint(new TexturePaint(srcImage, + new Rectangle2D.Float(0, 0, srcImage.getWidth(), srcImage.getHeight()))); + + AffineTransform transform = new AffineTransform(); + + transform.translate(x, y); + + double theta = Math.toRadians(heading); + transform.rotate(theta, anchor_x, anchor_y); + g.transform(transform); + g.fillRect(0, 0, srcImage.getWidth(), srcImage.getHeight()); + + g.setTransform(oldTransform); + + } + +} diff --git a/kobaltBasic/ScrollingEntity.java b/kobaltBasic/ScrollingEntity.java new file mode 100644 index 0000000..15a58cf --- /dev/null +++ b/kobaltBasic/ScrollingEntity.java @@ -0,0 +1,169 @@ +package kobaltBasic; + +import java.awt.Graphics2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; + +/** + * ScrollingEntities are used to represent backgrounds that wrap around as the player moves in the world. They are + * typical in old-school platform games to simulate the parallax effect. To use this class, one has to provide it with + * coordinates and the dimensions of the projection panel. The projection panel is the area of the screen on which + * the image will be scrolled. Setting the {@code x_velocity} and {@code y_velocity} simulates movement and wrap-around + * behavior. + * @author Shahriar Haque + * + */ +public class ScrollingEntity extends SpriteActor { + + + /** Height and width of the panel on to which the scrolling image will be projected on. **/ + public int panelWidth; + public int panelHeight; + + /** Coordinates of the panel on to which the scrolling image will be projected on.**/ + public int panelX; + public int panelY; + + // used simulate 360 degree scrolling, each rectangle has the exact dimensions of the scrolling image. + private Rectangle2D.Double[] guide = new Rectangle2D.Double[9]; + + // rectangle with the same dimensions as the projection panel + private Rectangle2D.Double panel; + + + /** + * Creates a new ScrollingEntity that has the ability to scroll in all possible directions. + * @param s The sprite that represents the image. + * @param pX X of the projection panel. + * @param pY Y of the projection panel. + * @param pWidth Width of the projection panel. + * @param pHeight Height of the projection panel. + */ + public ScrollingEntity(Sprite s, int pX, int pY, int pWidth, int pHeight) { + super(s, pX, pY); + + panelX = pX; + panelY = pY; + panelWidth = pWidth; + panelHeight = pHeight; + + // initializing according to the dimensions of the projection panel + panel = new Rectangle2D.Double(pX, pY, pWidth, pHeight); + + // guide[0] is aligned with the upper left corner of the projection panel + guide[0] = new Rectangle2D.Double(panelX, panelY, width, height); + + guide[1] = new Rectangle2D.Double(panelX-width, panelY-height, width, height); + guide[2] = new Rectangle2D.Double(panelX, panelY-height, width, height); + guide[3] = new Rectangle2D.Double(panelX+width,panelY-height, width, height); + + guide[4] = new Rectangle2D.Double(panelX-width, panelY, width, height); + guide[5] = new Rectangle2D.Double(panelX+width, panelY, width, height); + + guide[6] = new Rectangle2D.Double(panelX-width, panelY+height, width, height); + guide[7] = new Rectangle2D.Double(panelX, panelY+height, width, height); + guide[8] = new Rectangle2D.Double(panelX+width,panelY+height, width, height); + + + } + + /* + * Updates the position of the guiding rectangles with respect to guide[0]. Guide[0] always + * assumes the coordinates of the ScrollingEntity itself. + */ + private void updateGuides(){ + double gx = x; + double gy = y; + + + guide[0].x = gx; + guide[0].y = gy; + + guide[1].x = gx-width; + guide[1].y = gy-height; + + guide[2].x = gx; + guide[2].y = gy-height; + + guide[3].x = gx+width; + guide[3].y = gy-height; + + guide[4].x = gx-width; + guide[4].y = gy; + + guide[5].x = gx+width; + guide[5].y = gy; + + guide[6].x = gx-width; + guide[6].y = gy+height; + + guide[7].x = gx; + guide[7].y = gy+height; + + guide[8].x = gx+width; + guide[8].y = gy+height; + + + + + } + + public void update(){ + float fraction = (BasicGame.interval/1000.0f); + + x += (x_velocity * fraction); + y += (y_velocity * fraction); + + x = x%width; + y = y%height; + + + updateGuides(); + + } + + + public void render(Graphics2D g){ + BufferedImage img = theSprite.getCurrentFrame(); + + int sx; + int sy; + + int sw; + int sh; + + // if the panel is fully contained within any of the guiding rectangles, crop and display the cropped image + for(int i = 0; i < 9; i++){ + if(guide[i].contains(panel)){ + sx = (int) (panel.x - guide[i].x); + sy = (int) (panel.y - guide[i].y); + g.drawImage(img, 0, 0, panelX+panelWidth, panelY+panelHeight, sx, sy, sx+panelWidth, sy+panelHeight,null ); + + return; + } + } + + // if the panel intersects several guiding rectangles, crop the intersections, stich them and display + for(int i = 0; i < 9; i++){ + if(panel.intersects(guide[i])){ + Rectangle2D r = panel.createIntersection(guide[i]); + + sx = (int) (r.getX() - guide[i].x); + sy = (int) (r.getY() - guide[i].y); + sw = (int)r.getWidth(); + sh = (int)r.getHeight(); + + + g.drawImage(img, (int)r.getX(), (int)r.getY(), (int)(r.getX() + r.getWidth()), + (int) (r.getY() + r.getHeight()), sx,sy, sx+sw, sy+sh, null); + + } + } + + + } + + + + +} diff --git a/kobaltBasic/Sprite.java b/kobaltBasic/Sprite.java new file mode 100644 index 0000000..f0e8bf7 --- /dev/null +++ b/kobaltBasic/Sprite.java @@ -0,0 +1,121 @@ +package kobaltBasic; + +import java.awt.image.BufferedImage; + +/** + * A sprite is the visual representation of all game objects, let it be game characters, bonuses, + * or even message screens. A sprite can hold either a single image, or a sequence of images. + * Using the appropriate methods of the class you can change the ordering of the images and + * specify what image to show at what time. + * @author Shahriar Haque + * + * BugID 001: Sprite not using indices from sequence array while getting next frame. (Fixed) + * + */ +public class Sprite { + + private final BufferedImage[] frames; + private int[] sequence; + + private int currentFrame; + + /** + * Constructs a new Sprite object given the {@link BufferedImage} reference. + * @param b The BufferedImage which the Sprite will visually represent. + */ + public Sprite(BufferedImage b){ + frames = new BufferedImage[]{b}; + sequence = new int[]{0}; + + currentFrame = sequence[0]; + } + + /** + * Constructs a new Sprite given an array of {@link BufferedImage} objects. The images are + * ordered on the same arrangment as it was in the passed array. If you wish to use a different + * arrangement, refer to the {@link #changeSequence(int[])} method on how to do so. By default, + * calling current frame points to the first image element of the passed array. Thus calling + * the {@link #getCurrentFrame()} returns the first element of the array if nothing else is + * changed between the constructor call and the method invocation. + * @param b An array of BufferedImage objects that the Sprite will use. + */ + public Sprite(BufferedImage[] b){ + frames = b; + + sequence = new int[frames.length]; + + for(int i = 0; i < frames.length;i++) sequence[i] = i; + + currentFrame = sequence[0]; + } + + /** + * Initializes the Sprite object with the given {@link MaskedImage}. Internally, the constructor + * makes a call to the {@link MaskedImage#getMaskedImage() } method to get the reference to + * the image onto which the alpha mask has been applied to. + * @param m MaskedImage Object. + */ + public Sprite(MaskedImage m){ + frames = new BufferedImage[]{m.getMaskedImage()}; + sequence = new int[]{0}; + + currentFrame = sequence[0]; + } + + /** + * Constructs a new Sprite object from an array of MaskedImage object. The current sequence + * of the sprite images is set to the same sequence as the the passed array. Invoking the + * {@link #getCurrentFrame()} will return the first image of the given array if nothing is + * changed between the constructor call and the method invocation. Refer to the + * {@link #Sprite(MaskedImage)} to know how the constructor works internally. + * @param m Array of MaskedImage objects. + */ + public Sprite(MaskedImage[] m){ + frames = new BufferedImage[m.length]; + + for(int i = 0; i < frames.length; i++) { frames[i] = m[i].getMaskedImage(); } + + sequence = new int[frames.length]; + + for(int i = 0; i < frames.length;i++) { sequence[i] = i; } + + currentFrame = sequence[0]; + } + + + /** + * Changes the sequence of pictures to be used. If you instantiated this class using an + * array of images then the sequence in which that array was created will be used as the + * internal sequence for this sprite. However, by providing a new sequence in the form of + * an array of the same length as the BufferedImage[] array you started of with, you can + * specify a custom sequence. For example if you call this method using the parameter + * new int {2,3,1,4} then everytime you advance a frame, the sprite will read the next + * image's index from this sequence. + * @param newSequence int[] Integer array of the same length as the number of images in + * this sprite. + */ + public void changeSequence(int[] newSequence) { + for(int i = 0; i < sequence.length; i++) sequence[i] = newSequence[i]; + } + + /** + * Returns the BufferedImage at the location given by the {@link #getFrameIndex()} method. + * @return BufferedImage Current image of the provided sequence. + */ + public BufferedImage getCurrentFrame() { return frames[sequence[currentFrame]]; } + + /** + * Returns an integer pointing to the index of the current frame within its sequence. + * @return int Index of current frame. + */ + public int getFrameIndex() { return currentFrame; } + + /** + * Makes the currentFrame point to the next image of the sequence. + */ + public void advanceFrame() { + currentFrame++; + currentFrame %= sequence.length; + } + +} diff --git a/kobaltBasic/SpriteActor.java b/kobaltBasic/SpriteActor.java new file mode 100644 index 0000000..af8995a --- /dev/null +++ b/kobaltBasic/SpriteActor.java @@ -0,0 +1,44 @@ +package kobaltBasic; + +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.geom.Area; + +public class SpriteActor extends BasicActor { + + public int width,height; + public final Sprite theSprite; + + + + + public SpriteActor(Sprite s, int x, int y){ + super(x,y); + + theSprite = s; + width = s.getCurrentFrame().getWidth(); + height= s.getCurrentFrame().getHeight(); + setBounds(new Area(new Rectangle(x, y, width, height))); + + } + + + + public void update(){ + super.update(); + + if(lastUpdated >= UPDATE_INTERVAL){ + this.theSprite.advanceFrame(); + lastUpdated = 0; + } + + else lastUpdated += BasicGame.interval; + } + + + public void render(Graphics2D g){ + g.drawImage(theSprite.getCurrentFrame(),(int)x,(int)y,null); + } + + +} diff --git a/kobaltBasic/Spritesheet.java b/kobaltBasic/Spritesheet.java new file mode 100644 index 0000000..9776167 --- /dev/null +++ b/kobaltBasic/Spritesheet.java @@ -0,0 +1,126 @@ +package kobaltBasic; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.Scanner; + +/** + * This class represents a sprite sheet and contains convenience methods for extracting images from it. + * @author Shahriar Haque + */ +public final class Spritesheet { + + /** Given a string, this map returns the corresponding image from the tileset. **/ + public final HashMap<String, BufferedImage> map = new HashMap<String, BufferedImage>(); + + public int imgWidth = 0; + public int imgHeight = 0; + public int numColumns = 0; + public int numRows = 0; + + /** Offset between each row of images in the sprite sheet **/ + public int hOffset = 0; + + /** Offset between each column of images in the sprite sheet **/ + public int vOffset = 0; + + public int x; + public int y; + + /** Width of the entire sprite sheet **/ + public int width; + + /** Height of the entire sprite sheet **/ + public int height; + + /** Mask color used by this sprite sheet. This color will be receive an alpha value of 0.0 **/ + public Color maskColor = null; + + /** The BufferedImage that holds the sprite sheet after loading it **/ + public BufferedImage set; + + public Spritesheet(String fileLocation){ + set = Utilities.load(fileLocation); + } + + /** + * Renders the whole sprite sheet as an image on the screen + * @param g + * @param grid If grid is true, a white grid is drawn on top of the sprite sheet for debugging. + */ + public void render(Graphics2D g, boolean grid){ + g.drawImage(set,x,y,null); + g.setColor(Color.white); + + + for(int i = x; i < (x+width); i+= (imgWidth+hOffset) ){ + g.drawLine(i, y, i, (y+height)); + g.drawLine(i+imgWidth, y, i+imgWidth, (y+height)); + } + + for(int i = y; i < (y+height); i+=(imgHeight+vOffset) ){ + g.drawLine(x, i, (x+width), i); + g.drawLine(x,i+imgHeight, (x+width),i+imgHeight); + } + } + + + /** + * Returns an array consisting of a vertical row of images from a tileset. + * @param startX Starting X coordinate of the row. + * @param startY Starting Y coordinate of the row. + * @param w Width of each image. + * @param h Height of each image. + * @param offset The distance between each of image. + * @param numImages Number of images in the row. + * @return + */ + public BufferedImage[] extractRow(int startX, int startY, int w, int h, int offset, int numImages){ + + BufferedImage[] array = new BufferedImage[numImages]; + + for(int i = 0; i < numImages; i++){ + array[i] = Utilities.removeMask(set.getSubimage(startX + (i*(w + offset) ), startY, w, h), maskColor ); + } + + return array; + } + + + /** + * Reads an entire tile and labels them with the labels found in the label file. + * @param imgLabelFile The file that contains the labels for the tile set. + * @return + */ + public void extractAll(String imgLabelFile){ + + + try { + Scanner in = new Scanner(new File(imgLabelFile)); + BufferedImage img; + String label; + + for(int i = 0; i < numRows; i++){ + for(int j = 0; j < numColumns; j++){ + img = Utilities.removeMask(set.getSubimage( j*(imgWidth + hOffset), i*(imgHeight + vOffset), imgWidth, imgHeight), maskColor); + label = in.next(); + map.put(label, img); + } + + } + + + } catch (FileNotFoundException e) { + System.out.println("Image Label File: " + imgLabelFile + " not found"); + } + + catch (Exception e){ + e.printStackTrace(); + } + } + +} diff --git a/kobaltBasic/Utilities.java b/kobaltBasic/Utilities.java new file mode 100644 index 0000000..739c65a --- /dev/null +++ b/kobaltBasic/Utilities.java @@ -0,0 +1,261 @@ +package kobaltBasic; + +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +/** + * Simple utility class for loading images for sprites and also for applying transparency masks + * (alpha masks) to existing images. + * @author Shahriar Haque + * + */ +public class Utilities { + + /** + * Loads and returns a {@link BufferedImage} object given the proper file location. + * @param fileLocation Relative path to the image. + * @return A<code> BufferedImage </code>object if load is successful, <code>null</null> + * otherwise. + */ + public static BufferedImage load(String fileLocation){ + + try { + return ImageIO.read(new File(fileLocation)); + } + + + catch (IOException e) { + System.out.println(fileLocation + " not found"); + return null; + } + } + + /** + * Takes a souce image and and a gray-scale mask image of the same dimension, combines them + * to create an alpha-masked image, then returns the combined image. If the provided mask is + * not in gray-scale, gray values will be approximated from the red-channel of the pixels. + * The returned image will appear to be more transparent where the mask image was more white, + * and appear to be opaque where the mask was darker. + * @param src The source image. + * @param msk The gray-scale masked of the same dimensions of the src image. + * @return An alpha-masked {@link BufferedImage} with varying level of transparency. + * @throws IndexOutOfBoundsException if the supplied images are of different dimensions. + */ + public static BufferedImage applyAlphaMask(BufferedImage src, BufferedImage msk){ + + BufferedImage alphaMask = new BufferedImage(msk.getWidth(),msk.getHeight(),BufferedImage.TYPE_INT_ARGB); + alphaMask.createGraphics().drawImage(msk,0,0,null); + + BufferedImage dstOut = new BufferedImage(src.getWidth(),src.getHeight(),BufferedImage.TYPE_INT_ARGB); + dstOut.createGraphics().drawImage(src,0,0,null); + + + Raster maskRaster = alphaMask.getRaster(); + WritableRaster dstRaster = dstOut.getRaster(); + + + + int w = maskRaster.getWidth(); + int h = maskRaster.getHeight(); + + int[] mskPixel = new int[4]; // array of size 4 to hold [r,g,b,a] values + int[] dstPixel = new int[4]; + + for(int i = 0; i < w; i++){ + for(int j = 0; j < h; j++){ + maskRaster.getPixel(i, j, mskPixel); + dstRaster.getPixel(i,j,dstPixel); + + dstPixel[3] = mskPixel[0]; // copies red value to alpha of the dst Image + + dstRaster.setPixel(i, j, dstPixel); + + } + + } + + + return dstOut; + } + + /** + * Given an image, makes the regions with the mask color transparent. + * @param src The source image of which the mask color has to be removed. + * @param maskColor Mask color + * @return A new BufferedImage with the regions of the mask color turned transparent. + */ + public static BufferedImage removeMask(BufferedImage src, Color maskColor){ + + if(maskColor == null) return src; + + BufferedImage dstOut = new BufferedImage(src.getWidth(),src.getHeight(),BufferedImage.TYPE_INT_ARGB); + dstOut.createGraphics().drawImage(src,0,0,null); + + int w = dstOut.getWidth(); + int h = dstOut.getHeight(); + int[] dstPixel = new int[4]; + + WritableRaster dstRaster = dstOut.getRaster(); + + int mRed = maskColor.getRed(); + int mGreen = maskColor.getGreen(); + int mBlue = maskColor.getBlue(); + + for(int i = 0; i < w; i++){ + for(int j = 0; j < h; j++){ + dstRaster.getPixel(i,j,dstPixel); + + if(dstPixel[0] == mRed && dstPixel[1] == mGreen && dstPixel[2] == mBlue ){ + dstPixel[3] = 0; + dstRaster.setPixel(i, j, dstPixel); + } + + } + + } + + return dstOut; + + } + + /** + * Given an array of BufferedImages, returns a new array of images where each of the original images have + * been flipped horizontally. + * @param srcArray The source array of BufferedImages. + */ + public static BufferedImage[] flipHorizontal(BufferedImage[] srcArray){ + BufferedImage[] array = new BufferedImage[srcArray.length]; + + for(int i = 0; i < array.length; i++) array[i] = flipHorizontal(srcArray[i]); + + return array; + } + + /** + * Given a BufferedImage, returns a horizontally flipped version of it. + * @param src The source image + */ + public static BufferedImage flipHorizontal(BufferedImage src){ + BufferedImage temp = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB); + temp.createGraphics().drawImage(src, src.getWidth(), 0, 0, src.getHeight(), + 0, 0, src.getWidth(), src.getHeight(), null); + + + return temp; + } + + /** + * Given an array of BufferedImages, returns a new array of images where each of the original images have + * been flipped vertically. + * @param srcArray The source array of BufferedImages. + */ + public static BufferedImage[] flipVertical(BufferedImage[] srcArray){ + BufferedImage[] array = new BufferedImage[srcArray.length]; + + for(int i = 0; i < array.length; i++) array[i] = flipVertical(srcArray[i]); + + return array; + } + + + /** + * Given a BufferedImage, returns a vertically flipped version of it. + * @param src The source image + */ + public static BufferedImage flipVertical(BufferedImage src){ + BufferedImage temp = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB); + temp.createGraphics().drawImage(src, 0, src.getHeight(), src.getWidth(), 0, + 0, 0, src.getWidth(), src.getHeight(),null); + + return temp; + } + + + /** + * Returns an array containing the given number of colors by sampling them vertically + * over an equally divided distance. + * @param fileLocation The location of the image to be sampled. + * @param numColors The number of colors to sample. + * @return + */ + public static Color[] getVerticalColors(String fileLocation, int numColors){ + BufferedImage b = Utilities.load(fileLocation); + return getVerticalColors(b,numColors); + } + + /** + * Returns an array containing the given number of colors by sampling them horizontally + * over an equally divided distance. + * @param fileLocation The location of the image to be sampled. + * @param numColors The number of colors to sample. + * @return + */ + public static Color[] getHorizontalColors(String fileLocation, int numColors){ + BufferedImage b = Utilities.load(fileLocation); + return getHorizontalColors(b,numColors); + } + + /** + * Returns an array containing the given number of colors by sampling them vertically + * over an equally divided distance. + * @param b The BufferedImage to choose the colors from. + * @param numColors The number of colors to sample. + * @return + */ + public static Color[] getVerticalColors(BufferedImage b, int numColors){ + Color[] colors = new Color[numColors]; + + + int offset = b.getHeight()/numColors; + + for(int i = 0; i < numColors; i++){ + int color = b.getRGB(0, (i*offset)); + colors[i] = new Color(color); + } + + return colors; + } + + /** + * Returns an array containing the given number of colors by sampling them horizontally + * over an equally divided distance. + * @param b The BufferedImage to choose the colors from. + * @param numColors The number of colors to sample. + * @return + */ + public static Color[] getHorizontalColors(BufferedImage b, int numColors){ + Color[] colors = new Color[numColors]; + + + int offset = b.getWidth()/numColors; + + for(int i = 0; i < numColors; i++){ + int color = b.getRGB((i*offset),0); + colors[i] = new Color(color); + } + + return colors; + } + + /** + * Returns a 1 or -1 with a probability of 50% + * @return 1 or -1 + */ + public static int getRandomSign(){ + int num = (int) (Math.random()*50); + if(num % 2 == 0) num = -1; + else num = 1; + + return num; + } + + + + +} diff --git a/lib/Filters.jar b/lib/Filters.jar new file mode 100644 index 0000000..05f5c22 Binary files /dev/null and b/lib/Filters.jar differ diff --git a/lib/jl1.0.1.jar b/lib/jl1.0.1.jar new file mode 100644 index 0000000..bd5fb8b Binary files /dev/null and b/lib/jl1.0.1.jar differ diff --git a/lib/phys2d-060408.jar b/lib/phys2d-060408.jar new file mode 100644 index 0000000..edcffdc Binary files /dev/null and b/lib/phys2d-060408.jar differ diff --git a/particle/Emitter.java b/particle/Emitter.java new file mode 100644 index 0000000..bd4fe42 --- /dev/null +++ b/particle/Emitter.java @@ -0,0 +1,87 @@ +package particle; + +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import kobaltBasic.BasicGame; + +public abstract class Emitter { + + public int sourceX; + public int sourceY; + + /** Acceleration in the X and Y directions (in pixel/second^2) **/ + public int accX = 0; + public int accY = 0; + + /** The array that holds all the particles **/ + public Particle[] pArray; + + /** + * Initializes all the particles. Called every time a particle system is reset. + */ + public abstract void initParticles(); + + /** + * Initializes the particle at the given index of the particle array {@code pArray}. + * @param i Index of the particle within the array. + */ + public abstract void initParticle(int i); + + + public void update(){ + + double fraction = 0; + + + for(int i = 0; i < pArray.length; i++){ + Particle p = pArray[i]; + p.age += BasicGame.interval; // age the particle + + fraction = (p.age / 1000.0); // calculate the age in terms on ONE second + + if(p.age >= 0){ // move the particle only when it is of positive age + + // calculate how much acceleration is in effect at this age + p.vx += accX*fraction; + p.vy += accY*fraction; + + // updates the position based on the current x and y velocities and age + p.update(); + } + + // if particle has died, respawn it + if(p.age >= p.lifeSpan) initParticle(i); + + } + + + + + } + + public void render(Graphics2D g){ + + + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + + for(int i = 0; i < pArray.length; i++){ + Particle p = pArray[i]; + + if(p.age >= 0){ + g.setColor(p.color); + p.render(g); + + } + + + } + + + + + } + + +} diff --git a/particle/FadingParticle.java b/particle/FadingParticle.java new file mode 100644 index 0000000..bbca291 --- /dev/null +++ b/particle/FadingParticle.java @@ -0,0 +1,31 @@ +package particle; + +import java.awt.AlphaComposite; +import java.awt.Composite; +import java.awt.Graphics2D; + +/** + * A circular particle that starts off fully opaque and gradually becomes transparent as it ages. + * @author Shahriar Haque + * + */ +public class FadingParticle extends Particle { + + public void render(Graphics2D g){ + + Composite oldComposite = g.getComposite(); + + float a = (float)age; + float span = (float) lifeSpan; + + + + Composite fade; + fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f - (a/span) ); + + g.setComposite(fade); + g.fillOval((int)x, (int)y, size, size); + g.setComposite(oldComposite); + } + +} diff --git a/particle/FountainEmitter.java b/particle/FountainEmitter.java new file mode 100644 index 0000000..a014e86 --- /dev/null +++ b/particle/FountainEmitter.java @@ -0,0 +1,101 @@ +package particle; + +import java.awt.Color; + +public class FountainEmitter extends Emitter { + + + public int initDX = 150; + public int initDY = -250; + public int pSize = 10; + + public Color[] cArray = null; + + + public FountainEmitter(Particle[] pArray, int sx, int sy){ + sourceX = sx; + sourceY = sy; + this.pArray = pArray; + + } + + public void reset(){ + for(int i=0; i < pArray.length; i++) initParticle(i); + } + + + @Override + public void initParticle(int i) { + Particle p = pArray[i]; + + p.x = sourceX; + p.y = sourceY; + p.color = cArray[0]; // use the first color of the color array + + p.age = -(int) (Math.random()*1000); //this ensures a delay between the launch of particles + + p.lifeSpan = 2000; // each particle has a lifespan of 2 seconds + + p.size = (int) (Math.random()*pSize)+1; // randomly assign a size + + + // split the flow between left and right with a 50% probability + int num = (int) (Math.random()*50); + num = num%2; + + if(num == 0) initLeftFlow(p); + else initRightFlow(p); + + + } + + private void initLeftFlow(Particle p){ + + p.vx = -(int) (Math.random()*initDX); + p.vy = initDY; + } + + private void initRightFlow(Particle p){ + + p.vx = (int) (Math.random()*initDX); + p.vy = initDY; + } + + + + @Override + public void initParticles() { + + for(int i = 0; i < (pArray.length/2); i++){ + Particle p = pArray[i]; + initLeftFlow(p); + pArray[i] = p; + } + + for(int i = (pArray.length/2); i < pArray.length; i++){ + Particle p = pArray[i]; + initRightFlow(p); + pArray[i] = p; + } + + accX = 0; + accY = 15; // positive value to simulate gravity + + } + + public void update(){ + super.update(); + if(cArray == null) return; + + /* For each particle, calculate the age in terms of its lifespan, use the ratio + * to pick the right color from the color array. + */ + for(Particle p: pArray){ + if(p.age >= 0) + p.color = cArray[(int)((p.age/ (double) p.lifeSpan)*(cArray.length-1))]; + } + } + + + +} diff --git a/particle/MagicParticle.java b/particle/MagicParticle.java new file mode 100644 index 0000000..36a3928 --- /dev/null +++ b/particle/MagicParticle.java @@ -0,0 +1,27 @@ +package particle; + +import java.awt.Composite; +import java.awt.Graphics2D; + +import effects.BlendComposite; + +/** + * A circular particle that uses additive blending while rendering itself. + * @author Shahriar Haque + */ +public class MagicParticle extends Particle { + + public void render(Graphics2D g){ + + Composite oldComposite = g.getComposite(); + + + Composite fade; + fade = BlendComposite.getInstance(BlendComposite.BlendingMode.ADD); + + g.setComposite(fade); + g.fillOval((int)x, (int)y, size, size); + g.setComposite(oldComposite); + } + +} diff --git a/particle/MagicWandEmitter.java b/particle/MagicWandEmitter.java new file mode 100644 index 0000000..8a6f94c --- /dev/null +++ b/particle/MagicWandEmitter.java @@ -0,0 +1,76 @@ +package particle; + +import java.awt.Color; + +import kobaltBasic.Utilities; + +public class MagicWandEmitter extends Emitter { + + + public int initDX = 150; + public int initDY = -250; + public int pSize = 18; + + public Color[] cArray = { + new Color(80,234,252), // light blue + new Color(255,106,106), // red + new Color(79,79,240), // dark blue + new Color(241,255,124), // yellow + new Color(141,255,141), // green + new Color(255,114,253) // purple + }; + + + public MagicWandEmitter(Particle[] pArray, int sx, int sy){ + sourceX = sx; + sourceY = sy; + this.pArray = pArray; + + } + + public void reset(){ + for(int i=0; i < pArray.length; i++) initParticle(i); + } + + + @Override + public void initParticle(int i) { + Particle p = pArray[i]; + + p.x = sourceX; + p.y = sourceY; + p.color = cArray[ (int) (Math.random()*cArray.length) ]; + + p.age = -(int) (Math.random()*500); //this ensures a delay between the launch of particles + + p.lifeSpan = 250; // each particle has a lifespan of 250 milliseconds + + p.size = (int) (Math.random()*pSize)+1; // randomly assign a size + + + p.vx = Utilities.getRandomSign()*(Math.random()*200); + + p.vy = Utilities.getRandomSign()*(Math.random()*200); + + + + } + + + + + + @Override + public void initParticles() { + int numParticles = pArray.length; + + for(int i = 0; i < numParticles; i++) initParticle(i); + + accX = 0; + accY = 0; + + } + + + +} diff --git a/particle/Particle.java b/particle/Particle.java new file mode 100644 index 0000000..b49cc49 --- /dev/null +++ b/particle/Particle.java @@ -0,0 +1,39 @@ +package particle; + +import java.awt.Color; +import java.awt.Graphics2D; + +import kobaltBasic.BasicGame; + +public abstract class Particle { + + public double x; + public double y; + + /** X and Y components of the velocity in pixels/second. **/ + public double vx; + public double vy; + + /** Color of the particle. **/ + public Color color; + + /** Age of the particle in milliseconds. **/ + public int age = 0; + + /** Lifespan of the particle in milliseconds.**/ + public int lifeSpan = 0; + + /** Radius of the particle in pixels.**/ + public int size; + + public abstract void render(Graphics2D g); + + public void update(){ + double fraction = BasicGame.interval / 1000.0f; + + x += (vx*fraction) ; + y += (vy*fraction); + } + + +} diff --git a/sound/MP3Engine.java b/sound/MP3Engine.java new file mode 100644 index 0000000..969ba38 --- /dev/null +++ b/sound/MP3Engine.java @@ -0,0 +1,70 @@ +package sound; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.HashMap; + +import javazoom.jl.decoder.JavaLayerException; +import javazoom.jl.player.Player; + +/** + * A class that loads all the given mp3 files into memory. Once a playback is requested it + * plays the sound on a new thread. + * @author Shahriar Haque + * + */ + +public class MP3Engine { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private static HashMap<String, Player> map = new HashMap<String, Player>(); + + + public static final void load(String name, String location){ + try { + Player p = new Player(new FileInputStream(new File(location))); + map.put(name, p); + } + + + catch (FileNotFoundException e) { + System.err.println("File not found"); + } catch (JavaLayerException e) { + e.printStackTrace(); + } + + } + + + + public static void play(final String name){ + if(map.get(name) == null) return; + + Player p = map.get(name); + try { + p.play(); + } + + + catch (JavaLayerException e) { + System.err.println("Could not play mp3 file"); + } + + + } + + + public static void close(final String name){ + if(map.get(name) == null) return; + + Player p = map.get(name); + p.close(); + } + + +} diff --git a/sound/MidiEngine.java b/sound/MidiEngine.java new file mode 100644 index 0000000..8cd00df --- /dev/null +++ b/sound/MidiEngine.java @@ -0,0 +1,48 @@ +package sound; +import javax.sound.midi.*; +import java.io.*; + +/** Creates a new thread and plays the MIDI file on it **/ +public class MidiEngine extends Thread { + + + + public void playFile(String fileName){ + + String file = fileName; + if(!file.endsWith(".mid")) { + helpAndExit(); + } + File midiFile = new File(file); + if(!midiFile.exists() || midiFile.isDirectory() || !midiFile.canRead()) { + helpAndExit(); + } + + try { + Sequencer sequencer = MidiSystem.getSequencer(); + sequencer.setSequence(MidiSystem.getSequence(midiFile)); + + + + + + sequencer.open(); + sequencer.start(); + sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY); + + + } catch(MidiUnavailableException mue) { + System.out.println("Midi device unavailable!"); + } catch(InvalidMidiDataException imde) { + System.out.println("Invalid Midi data!"); + } catch(IOException ioe) { + System.out.println("I/O Error!"); + } + } + + /** Provides help message and exits the program */ + private static void helpAndExit() { + System.out.println("Usage: java MidiPlayer midifile.mid"); + System.exit(1); + } +} \ No newline at end of file diff --git a/sound/WaveEngine.java b/sound/WaveEngine.java new file mode 100644 index 0000000..d881732 --- /dev/null +++ b/sound/WaveEngine.java @@ -0,0 +1,43 @@ +package sound; + +import java.util.HashMap; + +/** + * A class that loads all the given sound files into memory. Once a playback is requested it + * plays the sound on a new thread. + * @author Shahriar Haque + * + */ + +public class WaveEngine { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private static HashMap<String, WaveObject> map = new HashMap<String, WaveObject>(); + + + public static final void load(String name, String location){ + map.put(name, new WaveObject(location)); + } + + + // plays a sound given the correct sound event constant + public static void play(final String name){ + if(map.get(name) == null) return; + + + new Thread( + new Runnable() { + public void run() { + map.get(name).play(); + } + } + ).start(); + + + } + +} diff --git a/sound/WaveObject.java b/sound/WaveObject.java new file mode 100644 index 0000000..572a971 --- /dev/null +++ b/sound/WaveObject.java @@ -0,0 +1,96 @@ +package sound; +import java.io.File; +import java.io.IOException; +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.FloatControl; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.SourceDataLine; +import javax.sound.sampled.UnsupportedAudioFileException; + +public class WaveObject { + + private String filename; + + private Position curPosition; + + private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb + + enum Position { + LEFT, RIGHT, NORMAL + }; + + public WaveObject(String wavfile) { + filename = wavfile; + curPosition = Position.NORMAL; + } + + public WaveObject(String wavfile, Position p) { + filename = wavfile; + curPosition = p; + } + + public void play() { + + File soundFile = new File(filename); + if (!soundFile.exists()) { + System.err.println("Wave file not found: " + filename); + return; + } + + AudioInputStream audioInputStream = null; + try { + audioInputStream = AudioSystem.getAudioInputStream(soundFile); + } catch (UnsupportedAudioFileException e1) { + e1.printStackTrace(); + return; + } catch (IOException e1) { + e1.printStackTrace(); + return; + } + + AudioFormat format = audioInputStream.getFormat(); + SourceDataLine auline = null; + DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); + + try { + auline = (SourceDataLine) AudioSystem.getLine(info); + auline.open(format); + } catch (LineUnavailableException e) { + e.printStackTrace(); + return; + } catch (Exception e) { + e.printStackTrace(); + return; + } + if (auline.isControlSupported(FloatControl.Type.PAN)) { + FloatControl pan = (FloatControl) auline + .getControl(FloatControl.Type.PAN); + if (curPosition == Position.RIGHT) + pan.setValue(1.0f); + else if (curPosition == Position.LEFT) + pan.setValue(-1.0f); + } + + auline.start(); + int nBytesRead = 0; + byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; + + try { + while (nBytesRead != -1) { + nBytesRead = audioInputStream.read(abData, 0, abData.length); + if (nBytesRead >= 0) + auline.write(abData, 0, nBytesRead); + } + } catch (IOException e) { + e.printStackTrace(); + return; + } finally { + auline.drain(); + auline.close(); + } + + } +} \ No newline at end of file diff --git a/tester/AreaTester.java b/tester/AreaTester.java new file mode 100644 index 0000000..dcb2d1b --- /dev/null +++ b/tester/AreaTester.java @@ -0,0 +1,71 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.event.KeyEvent; +import java.awt.geom.Area; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class AreaTester extends BasicGame implements KeyboardSupport { + + VectorPlayer player1; + VectorPlayer player2; + + + public AreaTester(String title, int w, int h) { + super(title, w, h); + + addKeyboardSupport(this); + + int x[] = new int[] { 25, 47, 1 }; // 25, 47, 1 + int y[] = new int[] {8, 32, 32 }; // 8, 32, 32 + Polygon p = new Polygon(x,y,3); + Sprite s = new Sprite(Utilities.load("tester/resources/player.png")); + player1 = new VectorPlayer(s, new Area(p), 100, 100); + player2 = new VectorPlayer(s, new Area(p), 300, 300); + + + player1.drawVector = true; + player2.drawVector = true; + + player1.rotational_velocity = 40; + + } + + @Override + public void render(Graphics2D g) { + fillWithColor(BLACK); + player1.render(g); + player2.render(g); + + } + + @Override + public void update() { + player1.update(); + player2.update(); + + } + + public static void main(String[] args){ + new AreaTester("Area Tester",640,480).start(); + } + + public void handleKeyPress(int keyCode) { + + player2.handleKeyPress(keyCode); + if(keyCode == KeyEvent.VK_ENTER){ + System.out.println(player1.collides(player2)); + } + } + + public void handleKeyRelease(int keyCode) { + player2.handleKeyRelease(keyCode); + + } + +} diff --git a/tester/Boid.java b/tester/Boid.java new file mode 100644 index 0000000..33786d7 --- /dev/null +++ b/tester/Boid.java @@ -0,0 +1,40 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.geom.Area; + +import kobaltBasic.RotatingActor; + +public class Boid extends RotatingActor { + + + /** + * Creates a new Boid represented by an isosceles triangle with the given centroid, base and height + * @param x X coordinate of the centroid + * @param y Y coordinate of the centroid + * @param base Base of the triangle representing the boid + * @param height Height of the triangle representing hhe boid + */ + public Boid(int x, int y, int base, int height) { + super(x,y); + + + int[] xpoints = {-(base/2),(base/2),0}; + int[] ypoints = {height/3,height/3,-(2*height)/3}; + setBounds(new Area(new Polygon(xpoints, ypoints, 3))); + } + + + @Override + public void render(Graphics2D g) { + this.renderBounds(g); + } + + public double getDistance(Boid other){ + double v = (x-other.x)*(x-other.x); + v += (y-other.y)*(y-other.y); + return Math.sqrt(v); + } + +} diff --git a/tester/BoidTester.java b/tester/BoidTester.java new file mode 100644 index 0000000..c72616d --- /dev/null +++ b/tester/BoidTester.java @@ -0,0 +1,192 @@ +package tester; + +import java.awt.Graphics2D; +import java.util.Random; + +import kobaltBasic.BasicGame; + +public class BoidTester extends BasicGame { + + static final int FLOCK_SIZE = 10; + static final int LOCALITY_DISTANCE = 20; + + Boid[] flock = new Boid[FLOCK_SIZE]; + static final int bs = 16; + static final int ht = 18; + + public BoidTester(String title, int w, int h) { + super(title, w, h); + createFlock(); + } + + public void createFlock(){ + Random rd = new Random(); + + for(int i = 0; i < flock.length; i++){ + + flock[i] = new Boid(rd.nextInt(600),rd.nextInt(450), bs,ht); + flock[i].heading = rd.nextInt(360); + flock[i].velocity = 100; + + } + + } + + public void reposition(Boid boid){ + + double m = 0; + double b = 0; + double theta = 0; + double mdash= 0; + double mdash2 = 0; + + double ix = 0; + double iy = 0; + + if(boid.x > 640 || boid.y > 480 || boid.x < 0 || boid.y < 0){ + + theta = boid.heading-90; + m = Math.tan(Math.toRadians(theta)); + b = boid.y - m*boid.x; + + if(b < 0){ + + ix = (-b/m); + iy = 0; + + mdash = 480/(640-ix); + + if(boid.y <= 0){ + if(m > mdash){ + boid.x = (480-b)/m; + boid.y = 480; + } + + else{ + boid.x = 640; + boid.y = (640*m) + b; + } + } + + else{ + boid.x = ix; + boid.y = iy; + } + } + + else if(b >=0 && b <= 480){ + ix = 0; + iy = b; + + mdash = -b/640; // top + mdash2 = (480-b)/640; // bottom + + if(boid.x < 0){ + if(m < mdash){ + boid.x = -b/m; + boid.y = 0; + } + + else if(m > mdash2){ + boid.x = (480-b)/m; + boid.y = 480; + } + + else{ + boid.x = 640; + boid.y = (640*m)+b; + } + } + + else{ + boid.x = ix; + boid.y = iy; + } + + } + + else{ + ix = (480-b)/m; + iy = 480; + + mdash = -480/(640-ix); + + if(boid.y >= 480){ + if(m < mdash){ + boid.x = -b/m; + boid.y = 0; + } + + else{ + boid.x = 640; + boid.y = (640*m)+b; + } + } + else{ + boid.x = ix; + boid.y = iy; + } + } + } + } + + /** + * @param args + */ + public static void main(String[] args) { + new BoidTester("Boid Tester",640,480).start(); + + } + + @Override + public void render(Graphics2D g) { + this.fillWithColor(BLACK); + for(Boid b: flock){ + b.renderBounds(g); + g.fillOval((int) b.x, (int) b.y, 2, 2); +// g.setColor(Color.green); +// g.drawOval((int)b.x, (int)b.y, 20, 20); + } + + } + + + public void applyRules(){ + double sum_heading = 0; + double locality_size = 0; + + for(Boid b: flock){ + sum_heading = 0; + locality_size = 0; + + for(Boid local: flock){ + + // if within same locality + if(b.getDistance(local) < LOCALITY_DISTANCE){ + locality_size++; + + // sum up heading + sum_heading += local.heading; + } + } + + b.heading = (sum_heading/locality_size); + } + + + } + + @Override + public void update() { + + + for(Boid b: flock){ + + b.update(); + reposition(b); + applyRules(); + } + + } + +} diff --git a/tester/BubbleParticle.java b/tester/BubbleParticle.java new file mode 100644 index 0000000..08a1d48 --- /dev/null +++ b/tester/BubbleParticle.java @@ -0,0 +1,42 @@ +package tester; + +import java.awt.AlphaComposite; +import java.awt.Composite; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.Utilities; + +import particle.Particle; + +/** + * A circular particle that starts off fully opaque and gradually becomes transparent as it ages. + * @author Shahriar Haque + * + */ +public class BubbleParticle extends Particle { + + + static BufferedImage src = Utilities.load("tester/resources/bubble.gif"); + static BufferedImage msk = Utilities.load("tester/resources/bubble-mask.gif"); + static BufferedImage img = Utilities.applyAlphaMask(src, msk); + + + public void render(Graphics2D g){ + + Composite oldComposite = g.getComposite(); + + float a = (float)age; + float span = (float) lifeSpan; + + + + Composite fade; + fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f - (a/span) ); + + g.setComposite(fade); + g.drawImage(img,(int)x, (int)y, null); + g.setComposite(oldComposite); + } + +} diff --git a/tester/CustomButton.java b/tester/CustomButton.java new file mode 100644 index 0000000..c6c84cb --- /dev/null +++ b/tester/CustomButton.java @@ -0,0 +1,134 @@ +package tester; + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Composite; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; + +import kobaltBasic.MouseSupport; +import effects.Drawable; +import effects.FadeEffect; + + +public class CustomButton implements Drawable,MouseSupport { + + + String label; + private boolean mouseOver = false; + @SuppressWarnings("unused") + private boolean pressed = false; + + private final Rectangle bounds = new Rectangle(0,0,10,10); + + public Color fillColor = new Color(36,36,36); + FadeEffect f = new FadeEffect(FadeEffect.FADE_IN); + + + public int x,y,w,h; + + + + public CustomButton(String label, int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.label = label; + bounds.x = x; + bounds.y = y; + bounds.width = w; + bounds.height = h; + + f.duration = 1500; + + + } + + public void render(Graphics2D g) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + if(! f.done){ + g.setColor(fillColor); + f.applyEffect(g, this); // one time effect + } + + else{ + if(!mouseOver)g.setColor(fillColor); + else g.setColor(new Color(100,100,100)); + draw(g); + + + } + + + + + + } + + public void draw(Graphics2D g){ + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + Composite oldComposite = g.getComposite(); + Composite fade = null; + fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f ); + + g.setComposite(fade); + g.fillRect(x, y, w, h); + g.setColor(Color.white); + g.setComposite(oldComposite); + + g.setFont(new Font("Arial",0,36)); + g.drawString("Start", x+36, y+40); + } + + public void handleMouseClick(int x, int y) {} + + public void handleMouseMove(int x, int y) { + if(bounds.contains(x, y)) mouseOver = true; + else { + mouseOver = false; + } + + } + + public void handleMousePress(int x, int y) { + if(bounds.contains(x,y)){ + pressed = true; + PongIntro.fadeOut = true; + } + + } + + public void handleMouseRelease(int x, int y) { + if(bounds.contains(x,y)){ + pressed = false; + } + + } + + public int getHeight() { + + return h; + } + + public int getWidth() { + + return w; + } + + public int getX() { + + return x; + } + + public int getY() { + + return y; + } + + +} diff --git a/tester/ExhaustEmitter.java b/tester/ExhaustEmitter.java new file mode 100644 index 0000000..1f5ef03 --- /dev/null +++ b/tester/ExhaustEmitter.java @@ -0,0 +1,74 @@ +package tester; + +import java.awt.Color; + +import particle.Emitter; +import particle.Particle; + +import kobaltBasic.Utilities; + +public class ExhaustEmitter extends Emitter { + + + public double DY = 0; + public int pSize = 12; + + + + public Color[] cArray = { + new Color(24,57,247) + }; + + + public ExhaustEmitter(Particle[] pArray, int sx, int sy){ + sourceX = sx; + sourceY = sy; + this.pArray = pArray; + + } + + public void reset(){ + for(int i=0; i < pArray.length; i++) initParticle(i); + } + + + @Override + public void initParticle(int i) { + Particle p = pArray[i]; + + p.x = sourceX; + p.y = sourceY; + p.color = cArray[0]; + + p.age = -(int) (Math.random()*500); //this ensures a delay between the launch of particles + + p.lifeSpan = 150; // each particle has a lifespan of 250 milliseconds + + p.size = pSize;//(int) (Math.random()*pSize)+1; // randomly assign a size + + + p.vx = Utilities.getRandomSign()*(Math.random()*75); + p.vy = DY; + + + + } + + + + + + @Override + public void initParticles() { + int numParticles = pArray.length; + + for(int i = 0; i < numParticles; i++) initParticle(i); + + accX = 0; + accY = 0; + + } + + + +} diff --git a/tester/ExhaustTester.java b/tester/ExhaustTester.java new file mode 100644 index 0000000..a2b4145 --- /dev/null +++ b/tester/ExhaustTester.java @@ -0,0 +1,60 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class ExhaustTester extends BasicGame implements KeyboardSupport { + + Player1 p1; + + public ExhaustTester(String title, int w, int h) { + super(title, w, h); + + BufferedImage img = Utilities.load("tester/resources/pixelship.gif"); + BufferedImage grad = Utilities.load("tester/resources/grad.gif"); + BufferedImage ship = Utilities.applyAlphaMask(img, grad); + + p1 = new Player1(new Sprite(ship),300,300); // creates a player object with a sprite consisting of a single frame + + addKeyboardSupport(this); // makes the game screen responds to keyboard button events + + } + + + public void render(Graphics2D g) { + + + fillWithColor(Color.BLACK); // paints the background black + + p1.render(g); + + + } + + public void update() { + p1.update(); // this forces player1 to update its x,y coordinates based on its velocities. + + } + + + public void handleKeyPress(int keyCode) { + p1.handleKeyPress(keyCode); // informs player1 that the given key has been pressed. Similar method in Player1 decides how to deal with it + } + + + public void handleKeyRelease(int keyCode) { + p1.handleKeyRelease(keyCode); // same as previous method + } + + public static void main(String[] args) { + new ExhaustTester("Exhaust Testers",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/FountainTester.java b/tester/FountainTester.java new file mode 100644 index 0000000..3af9516 --- /dev/null +++ b/tester/FountainTester.java @@ -0,0 +1,66 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Utilities; +import particle.FadingParticle; +import particle.FountainEmitter; +import particle.Particle; + +public class FountainTester extends BasicGame implements KeyboardSupport { + + + FountainEmitter f; + + + public FountainTester(String title, int w, int h, boolean fullScreen) { + super(title, w, h, fullScreen); + + addKeyboardSupport(this); + + Particle[] pArray = new FadingParticle[700]; + for(int i = 0; i < 700; i++) pArray[i] = new FadingParticle(); + + f = new FountainEmitter(pArray, 300, 300); + f.cArray = Utilities.getVerticalColors("tester/resources/blue-grad.gif", 10); + f.initParticles(); + } + + + + @Override + public void render(Graphics2D g) { + fillWithColor(BLACK); + f.render(g); + + } + + + @Override + public void update() { + + f.update(); + } + + public static void main(String[] args) { + + + new FountainTester("Fountain Effect Demo", 640,480, false).start(); + + } + + + + public void handleKeyPress(int keyCode) {} + + + + public void handleKeyRelease(int keyCode) { + if(keyCode == KeyEvent.VK_ENTER) f.reset(); + + } + +} diff --git a/tester/FullScreen.java b/tester/FullScreen.java new file mode 100644 index 0000000..9a38caf --- /dev/null +++ b/tester/FullScreen.java @@ -0,0 +1,92 @@ +package tester; + +import java.awt.Color; +import java.awt.DisplayMode; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import java.awt.image.BufferStrategy; + +public class FullScreen { + + private static int counter = 0; + + private static final int MAX = 50; + + private static DisplayMode MODES[] = new DisplayMode[] { + new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 16, 0), + new DisplayMode(640, 480, 8, 0) }; + + private static DisplayMode getBestDisplayMode(GraphicsDevice device) { + for (int x = 0, xn = MODES.length; x < xn; x++) { + DisplayMode[] modes = device.getDisplayModes(); + for (int i = 0, in = modes.length; i < in; i++) { + if (modes[i].getWidth() == MODES[x].getWidth() + && modes[i].getHeight() == MODES[x].getHeight() + && modes[i].getBitDepth() == MODES[x].getBitDepth()) { + return MODES[x]; + } + } + } + return null; + } + + public static void main(String args[]) { + GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment + .getLocalGraphicsEnvironment(); + GraphicsDevice graphicsDevice = graphicsEnvironment + .getDefaultScreenDevice(); + DisplayMode originalDisplayMode = graphicsDevice.getDisplayMode(); + + try { + Frame frame = new Frame(); + frame.setUndecorated(true); + frame.setIgnoreRepaint(true); + graphicsDevice.setFullScreenWindow(frame); + if (graphicsDevice.isDisplayChangeSupported()) { + graphicsDevice + .setDisplayMode(getBestDisplayMode(graphicsDevice)); + } + frame.createBufferStrategy(2); // 2 buffers + Rectangle bounds = frame.getBounds(); + BufferStrategy bufferStrategy = frame.getBufferStrategy(); + while (!done()) { + Graphics g = null; + try { + g = bufferStrategy.getDrawGraphics(); + if ((counter <= 2)) { // 2 buffers + g.setColor(Color.CYAN); + g.fillRect(0, 0, bounds.width, bounds.height); + } + g.setColor(Color.RED); + // redraw prior line, too, since 2 buffers + if (counter != 1) { + g.drawLine(counter - 1, (counter - 1) * 5, + bounds.width, bounds.height); + } + g.drawLine(counter, counter * 5, bounds.width, + bounds.height); + bufferStrategy.show(); + } finally { + if (g != null) { + g.dispose(); + } + } + try { + Thread.sleep(250); + } catch (InterruptedException ignored) { + } + } + } finally { + graphicsDevice.setDisplayMode(originalDisplayMode); + graphicsDevice.setFullScreenWindow(null); + } + System.exit(0); + } + + private static boolean done() { + return (counter++ == MAX); + } +} diff --git a/tester/LightingTester.java b/tester/LightingTester.java new file mode 100644 index 0000000..0bc71d3 --- /dev/null +++ b/tester/LightingTester.java @@ -0,0 +1,81 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import experimental.lighting.Illuminator; +import experimental.lighting.LightSource; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class LightingTester extends BasicGame implements KeyboardSupport { + + Player2 p; + LightSource light; + Illuminator lumin; + + + public LightingTester(String title, int w, int h) { + super(title, w, h); + + BufferedImage img = Utilities.load("tester/resources/player.png"); + + p = new Player2(new Sprite(img),300,300); + + BufferedImage b1 = Utilities.load("tester/resources/sun.png"); + BufferedImage b2 = Utilities.load("tester/resources/sun-mask.png"); + light = new LightSource(Utilities.applyAlphaMask(b1, b2)); + light.x = 300; + light.y = 10; + light.range = 300; + + + lumin = new Illuminator(); + lumin.source = light; + lumin.target = p; + + PongIntro iScreen = new PongIntro(); + screenList.add(iScreen); + currentScreen = 0; + addKeyboardSupport(this); // makes the game screen responds to keyboard button events + + + + + } + + + public void render(Graphics2D g) { + + + fillWithColor(Color.BLACK); // paints the background black + + lumin.render(g); + + + } + + public void update() { + p.update(); + } + + + public void handleKeyPress(int keyCode) { + p.handleKeyPress(keyCode); + } + + + public void handleKeyRelease(int keyCode) { + p.handleKeyRelease(keyCode); + } + + public static void main(String[] args) { + new LightingTester("Lighting Effects Demo",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/MagicWandTester.java b/tester/MagicWandTester.java new file mode 100644 index 0000000..48f1318 --- /dev/null +++ b/tester/MagicWandTester.java @@ -0,0 +1,70 @@ +package tester; + +import java.awt.Graphics2D; + +import kobaltBasic.BasicGame; +import kobaltBasic.MouseSupport; +import particle.MagicParticle; +import particle.MagicWandEmitter; +import particle.Particle; + +public class MagicWandTester extends BasicGame implements MouseSupport { + + + MagicWandEmitter f; + + public MagicWandTester(String title, int w, int h) { + super(title, w, h); + + addMouseSupport(this); + + + int numParticles = 100; + Particle[] pArray = new MagicParticle[numParticles]; + for(int i = 0; i < numParticles; i++) pArray[i] = new MagicParticle(); + + f = new MagicWandEmitter(pArray, 300, 300); + f.initParticles(); + } + + + + @Override + public void render(Graphics2D g) { + fillWithColor(BLACK); + f.render(g); + + } + + @Override + public void update() { + f.update(); + } + + public static void main(String[] args) { + new MagicWandTester("Magic Wand Demo", 640,480).start(); + + } + + + + public void handleMouseClick(int x, int y) {} + + + + public void handleMouseMove(int x, int y) { + if(f != null){ + f.sourceX = x; + f.sourceY = y; + } + + } + + + + public void handleMousePress(int x, int y) {} + + public void handleMouseRelease(int x, int y) {} + + +} diff --git a/tester/MaskTester.java b/tester/MaskTester.java new file mode 100644 index 0000000..d546ae3 --- /dev/null +++ b/tester/MaskTester.java @@ -0,0 +1,56 @@ +package tester; + +import java.awt.Composite; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import kobaltBasic.Utilities; +import effects.BlendComposite; + +public class MaskTester extends BasicGame { + + BufferedImage img1; + BufferedImage msk; + + public MaskTester(String title, int w, int h) { + super(title, w, h); + + img1 = Utilities.load("tester/resources/starburst.gif"); + BufferedImage temp; + + msk = Utilities.load("tester/resources/dand-mask.gif"); + img1 = Utilities.applyAlphaMask(img1, msk); + + temp = new BufferedImage(msk.getWidth(), msk.getHeight(), BufferedImage.TYPE_INT_ARGB); + temp.createGraphics().drawImage(msk,0,0,null); + msk = temp; + + } + + + + @Override + public void render(Graphics2D g) { + fillWithColor(BLACK); + g.drawImage(img1, 100,100, null); + + Composite old = g.getComposite(); + g.setComposite(BlendComposite.ColorDodge); + g.drawImage(msk, 100,100, null); + g.setComposite(old); + + } + + @Override + public void update() {} + + /** + * @param args + */ + public static void main(String[] args) { + new MaskTester("Mask Tester",640,480).start(); + + } + +} diff --git a/tester/P2PTester.java b/tester/P2PTester.java new file mode 100644 index 0000000..35bd479 --- /dev/null +++ b/tester/P2PTester.java @@ -0,0 +1,90 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.image.BufferedImage; + +import experimental.network.NetworkComponent; +import experimental.network.P2PService; + + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + + +public class P2PTester extends BasicGame implements KeyboardSupport, NetworkComponent { + + + Player1 p1; + Player1 p2; + P2PService net; + + public P2PTester(String title, int w, int h) { + super(title, w, h); + + + + BufferedImage img = Utilities.load("tester/resources/player.png"); + + p1 = new Player1(new Sprite(img),100,300); + p2 = new Player1(new Sprite(img),500,300); + + net = new P2PService(this); + + addKeyboardSupport(this); + addNetworkService(net); + net.startServer(8181); + + } + + + @Override + public void render(Graphics2D g) { + fillWithColor(Color.BLACK); + p1.render(g); + p2.render(g); + } + + @Override + public void update() { + p1.update(); + p2.update(); + } + + public String getData() { + String s = p1.x_velocity + "," + p1.y_velocity; + return s; + } + + public void parseData(String msg) { + String[] arr = msg.split(","); + + p2.x_velocity = Double.parseDouble(arr[0]); + p2.y_velocity = Double.parseDouble(arr[1]); + } + + public static void main(String[] args) { + new P2PTester("P2P Tester", 640, 480).start(); + + } + + + public void handleKeyPress(int keyCode) { + p1.handleKeyPress(keyCode); + + } + + + public void handleKeyRelease(int keyCode) { + p1.handleKeyRelease(keyCode); + + if(keyCode == KeyEvent.VK_ENTER){ + net.startSession(); + } + + } + +} diff --git a/tester/PhyDemo1.java b/tester/PhyDemo1.java new file mode 100644 index 0000000..2ed9fda --- /dev/null +++ b/tester/PhyDemo1.java @@ -0,0 +1,60 @@ +package tester; + +import experimental.physics.AbstractPhysicsDemo; +import net.phys2d.raw.Body; +import net.phys2d.raw.StaticBody; +import net.phys2d.raw.World; +import net.phys2d.raw.shapes.Box; + +public class PhyDemo1 extends AbstractPhysicsDemo { + + + + public PhyDemo1(String title, int w, int h) { + super(title, w, h); + } + + + public void init(World world) { + + + Body body1 = new StaticBody("Ground1", new Box(400.0f, 20.0f)); + body1.setPosition(250.0f, 400); + world.add(body1); + Body body3 = new StaticBody("Ground2", new Box(200.0f, 20.0f)); + body3.setPosition(360.0f, 380); + world.add(body3); + Body body5 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body5.setPosition(200.0f, 300); + world.add(body5); + Body body6 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body6.setPosition(400.0f, 300); + world.add(body6); + + Body body2 = new Body("Mover1", new Box(50.0f, 50.0f), 100.0f); + body2.setPosition(250.0f, 4.0f); + world.add(body2); + Body body4 = new Body("Mover2", new Box(50.0f, 50.0f), 100.0f); + body4.setPosition(230.0f, -60.0f); + world.add(body4); + Body body8 = new Body("Mover3", new Box(50.0f, 50.0f), 100.0f); + body8.setPosition(280.0f, -120.0f); + world.add(body8); + + //System.out.println("Comes here"); + + } + + + + public void handleKeyPress(int keyCode) {} + + + public static void main(String[] args) { + new PhyDemo1("Physics Tester",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + + + +} diff --git a/tester/PhysicsTester.java b/tester/PhysicsTester.java new file mode 100644 index 0000000..234d1e5 --- /dev/null +++ b/tester/PhysicsTester.java @@ -0,0 +1,104 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import net.phys2d.math.Vector2f; +import net.phys2d.raw.Body; +import net.phys2d.raw.BodyList; +import net.phys2d.raw.StaticBody; +import net.phys2d.raw.World; +import net.phys2d.raw.shapes.Box; +import net.phys2d.raw.strategies.QuadSpaceStrategy; + +import kobaltBasic.BasicGame; + +public class PhysicsTester extends BasicGame { + + World world; + + public PhysicsTester(String title, int w, int h) { + super(title, w, h); + + world = new World(new Vector2f(0.0f, 10.0f), 10, new QuadSpaceStrategy(20,5)); + world.clear(); + world.setGravity(0,10); + + Body body1 = new StaticBody("Ground1", new Box(400.0f, 20.0f)); + body1.setPosition(250.0f, 400); + world.add(body1); + Body body3 = new StaticBody("Ground2", new Box(200.0f, 20.0f)); + body3.setPosition(360.0f, 380); + world.add(body3); + Body body5 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body5.setPosition(200.0f, 300); + world.add(body5); + Body body6 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body6.setPosition(400.0f, 300); + world.add(body6); + + Body body2 = new Body("Mover1", new Box(50.0f, 50.0f), 100.0f); + body2.setPosition(250.0f, 4.0f); + world.add(body2); + Body body4 = new Body("Mover2", new Box(50.0f, 50.0f), 100.0f); + body4.setPosition(230.0f, -60.0f); + world.add(body4); + Body body8 = new Body("Mover3", new Box(50.0f, 50.0f), 100.0f); + body8.setPosition(280.0f, -120.0f); + world.add(body8); + + } + + + + + public void render(Graphics2D g) { + + fillWithColor(WHITE); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + BodyList bodies = world.getBodies(); + + for (int i=0;i<bodies.size();i++) { + Body body = bodies.get(i); + + drawBody(g, body); + } + + } + + protected void drawBody(Graphics2D g, Body body) { + if (body.getShape() instanceof Box) { + drawBoxBody(g,body,(Box) body.getShape()); + } + + } + + protected void drawBoxBody(Graphics2D g, Body body, Box box) { + Vector2f[] pts = box.getPoints(body.getPosition(), body.getRotation()); + + Vector2f v1 = pts[0]; + Vector2f v2 = pts[1]; + Vector2f v3 = pts[2]; + Vector2f v4 = pts[3]; + + g.setColor(Color.black); + g.drawLine((int) v1.x,(int) v1.y,(int) v2.x,(int) v2.y); + g.drawLine((int) v2.x,(int) v2.y,(int) v3.x,(int) v3.y); + g.drawLine((int) v3.x,(int) v3.y,(int) v4.x,(int) v4.y); + g.drawLine((int) v4.x,(int) v4.y,(int) v1.x,(int) v1.y); + } + + public void update() { + for(int i = 0; i < 5; i++)world.step(); + } + + + + public static void main(String[] args) { + new PhysicsTester("Physics Tester",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/Player1.java b/tester/Player1.java new file mode 100644 index 0000000..e7de182 --- /dev/null +++ b/tester/Player1.java @@ -0,0 +1,96 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; + +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.SpriteActor; +import particle.MagicParticle; +import particle.Particle; +import effects.FadeEffect; + +/* + * Implementing ControlledByKeyboard lets this entity respond to keyboard button presses. + */ + +public class Player1 extends SpriteActor implements KeyboardSupport { + + + static final int space = KeyEvent.VK_SPACE; + + boolean fade = false; + FadeEffect f1 = new FadeEffect(FadeEffect.FADE_OUT); + + ExhaustEmitter e; + + + /* + * Sprite s: The sprite that this game entity will use, can contain multiple frames + * posX: X position of the entity + * posY: Y position of the entity + */ + public Player1(Sprite s, int posX, int posY) { + super(s, posX, posY); + + int numPart = 20; + Particle[] array = new Particle[numPart]; + for(int i = 0; i < array.length; i++) array[i] = new MagicParticle(); + e = new ExhaustEmitter(array, posX+(width/2-6), posY+(height/2+13)); + + } + + + public void update(){ + + if (x < 0) x = 300; + + + super.update(); + + e.sourceX = (int)this.x + (width/2-6) ; + e.sourceY = (int)this.y + (height/2+13); + e.DY = -(this.y_velocity-50); + + e.update(); + } + + public void handleKeyPress(int keyCode) { + + + + if(keyCode == UP) this.y_velocity = -200; // if the up button is pressed set negative velocity to go up + + if(keyCode == DOWN) this.y_velocity = 200; // if down button is pressed positive velocity to go down + + if(keyCode == LEFT) this.x_velocity = -200; + if(keyCode == RIGHT) this.x_velocity = 200; + + + } + + public void handleKeyRelease(int keyCode) { + this.y_velocity = 0; // when no key is being pressed set velocity to zero, otherwise the bar floats off the screen + this.x_velocity = 0; + + if(keyCode == space) { + fade = !fade; + f1.reset(); + } + + } + + public void render(Graphics2D g){ + if(fade) { +// BlurEffect.applyEffect(g, this); + f1.applyEffect(g, this); + fade = !f1.done; + + } + else super.render(g); + + e.render(g); + } + + +} diff --git a/tester/Player2.java b/tester/Player2.java new file mode 100644 index 0000000..102842d --- /dev/null +++ b/tester/Player2.java @@ -0,0 +1,56 @@ +package tester; + +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.SpriteActor; + +/* + * Implementing ControlledByKeyboard lets this entity respond to keyboard button presses. + */ + +public class Player2 extends SpriteActor implements KeyboardSupport { + + + + + + /* + * Sprite s: The sprite that this game entity will use, can contain multiple frames + * posX: X position of the entity + * posY: Y position of the entity + */ + public Player2(Sprite s, int posX, int posY) { + super(s, posX, posY); + x = posX; + y = posY; + + } + + public void update(){ + + if (x < 0) x = 300; + + + super.update(); + + } + + public void handleKeyPress(int keyCode) { + + if(keyCode == UP) this.y_velocity = -100; // if the up button is pressed set negative velocity to go up + + if(keyCode == DOWN) this.y_velocity = 100; // if down button is pressed positive velocity to go down + + if(keyCode == LEFT) this.x_velocity = -200; + if(keyCode == RIGHT) this.x_velocity = 200; + + } + + public void handleKeyRelease(int keyCode) { + this.y_velocity = 0; // when no key is being pressed set velocity to zero, otherwise the bar floats off the screen + this.x_velocity = 0; + + } + + +} diff --git a/tester/PongIntro.java b/tester/PongIntro.java new file mode 100644 index 0000000..7f6522a --- /dev/null +++ b/tester/PongIntro.java @@ -0,0 +1,77 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; + +import kobaltBasic.BasicGame; +import kobaltBasic.MouseSupport; +import kobaltBasic.GameScreen; + +public class PongIntro extends GameScreen implements MouseSupport { + + CustomButton cbtn; + SpaceBG bg; + + int delay = 1000; + int elapsed = 0; + + static boolean fadeOut = false; + + + public PongIntro(){ + addMouseSupport(this); + cbtn = new CustomButton("Click Me", 250,200,150,50); + bg = new SpaceBG(); + + + } + + @Override + public void render(Graphics2D g) { + g.setColor(Color.black); + g.drawRect(0, 0, 640, 480); + bg.draw(g); + + elapsed += BasicGame.interval; + + if(elapsed >= delay) elapsed = delay; + + if(elapsed >= delay) { + cbtn.render(g); + } + + if(fadeOut){ + + BasicGame.currentScreen = 0; + } + + } + + + @Override + public void update() { + // TODO Auto-generated method stub + + } + + public void handleMouseClick(int x, int y) { + // TODO Auto-generated method stub + + } + + public void handleMouseMove(int x, int y) { + cbtn.handleMouseMove(x, y); + + } + + public void handleMousePress(int x, int y) { + cbtn.handleMousePress(x, y); + + } + + public void handleMouseRelease(int x, int y) { + cbtn.handleMouseRelease(x, y); + + } + +} diff --git a/tester/RippleTester.java b/tester/RippleTester.java new file mode 100644 index 0000000..f60159c --- /dev/null +++ b/tester/RippleTester.java @@ -0,0 +1,44 @@ +package tester; + +import java.awt.Graphics2D; + +import effects.WaterRippleEffect; + +import kobaltBasic.BasicGame; + +public class RippleTester extends BasicGame { + + + SpaceBG bg; + WaterRippleEffect effect; + + public RippleTester(String title, int w, int h) { + super(title, w, h); + + bg = new SpaceBG(); + effect = new WaterRippleEffect(350,100); + + } + + + public void render(Graphics2D g) { + + + bg.draw(g); + effect.applyEffect(g); + + + } + + public void update() { + effect.update(); + } + + + + public static void main(String[] args) { + new RippleTester("Ripple Tester",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/RotationTester.java b/tester/RotationTester.java new file mode 100644 index 0000000..f18909d --- /dev/null +++ b/tester/RotationTester.java @@ -0,0 +1,61 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class RotationTester extends BasicGame implements KeyboardSupport { + + Spaceship p1; + + public RotationTester(String title, int w, int h) { + super(title, w, h); + + BufferedImage img = Utilities.load("tester/resources/powergenerator.gif"); + + p1 = new Spaceship(new Sprite(img),300,100); // creates a player object with a sprite consisting of a single frame + + p1.rotational_velocity = 10; + + addKeyboardSupport(this); // makes the game screen responds to keyboard button events + + } + + + public void render(Graphics2D g) { + + + fillWithColor(Color.BLACK); // paints the background black + + p1.render(g); + + + } + + public void update() { + + p1.update(); // this forces player1 to update its x,y coordinates based on its velocities. + + } + + + public void handleKeyPress(int keyCode) { + p1.handleKeyPress(keyCode); // informs player1 that the given key has been pressed. Similar method in Player1 decides how to deal with it + } + + + public void handleKeyRelease(int keyCode) { + p1.handleKeyRelease(keyCode); // same as previous method + } + + public static void main(String[] args) { + new RotationTester("Exhaust Testers",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/ScrollingTester.java b/tester/ScrollingTester.java new file mode 100644 index 0000000..0df769a --- /dev/null +++ b/tester/ScrollingTester.java @@ -0,0 +1,95 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.image.BufferedImage; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.ScrollingEntity; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class ScrollingTester extends BasicGame implements KeyboardSupport { + + Player1 p1; + ScrollingEntity bg; + + public ScrollingTester(String title, int w, int h) { + super(title, w, h); + + BufferedImage img = Utilities.load("tester/resources/player.png"); + BufferedImage img2 = Utilities.load("tester/resources/sky2.png"); + + p1 = new Player1(new Sprite(img),300,300); // creates a player object with a sprite consisting of a single frame + bg = new ScrollingEntity(new Sprite(img2), 0, 0, w, h); + + bg.y_velocity = 100; + addKeyboardSupport(this); // makes the game screen responds to keyboard button events + + } + + + public void render(Graphics2D g) { + + + //fillWithColor(Color.BLACK); // paints the background black + bg.render(g); + + p1.render(g); + + + + } + + public void update() { + p1.update(); // this forces player1 to update its x,y coordinates based on its velocities. + bg.update(); + } + + + public void handleKeyPress(int keyCode) { + //p1.handleKeyPress(keyCode); // informs player1 that the given key has been pressed. Similar method in Player1 decides how to deal with it + if(keyCode == KeyEvent.VK_LEFT){ + bg.x_velocity = 100; + } + + if(keyCode == KeyEvent.VK_RIGHT){ + bg.x_velocity = -100; + } + + if(keyCode == KeyEvent.VK_UP){ + bg.y_velocity = 100; + } + + if(keyCode == KeyEvent.VK_DOWN){ + bg.y_velocity = -100; + } + } + + + public void handleKeyRelease(int keyCode) { + //p1.handleKeyRelease(keyCode); // same as previous method + if(keyCode == KeyEvent.VK_LEFT){ + bg.x_velocity = 0; + } + + if(keyCode == KeyEvent.VK_RIGHT){ + bg.x_velocity = 0; + } + + if(keyCode == KeyEvent.VK_UP){ + bg.y_velocity = 0; + } + + if(keyCode == KeyEvent.VK_DOWN){ + bg.y_velocity = 0; + } + } + + public static void main(String[] args) { + new ScrollingTester("Exhaust Testers",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/Smiley.java b/tester/Smiley.java new file mode 100644 index 0000000..ccebbc2 --- /dev/null +++ b/tester/Smiley.java @@ -0,0 +1,29 @@ +package tester; + +import kobaltBasic.RotatingSpriteActor; +import kobaltBasic.Sprite; +import net.phys2d.math.ROVector2f; +import net.phys2d.raw.Body; + +public class Smiley extends RotatingSpriteActor { + + Body body; + + public Smiley(Sprite s, Body b) { + super(s, b.getPosition().getX(), b.getPosition().getY()); + body = b; + } + + public void update(){ + ROVector2f pos = body.getPosition(); + float angle = body.getRotation(); + + x = pos.getX()-50; + y = pos.getY()-50; + heading = Math.toDegrees(angle); + + super.update(); + + } + +} diff --git a/tester/SmileyPhysics.java b/tester/SmileyPhysics.java new file mode 100644 index 0000000..1947ac9 --- /dev/null +++ b/tester/SmileyPhysics.java @@ -0,0 +1,45 @@ +package tester; + +import experimental.physics.AbstractPhysicsEngine; +import net.phys2d.math.Vector2f; +import net.phys2d.raw.Body; +import net.phys2d.raw.StaticBody; +import net.phys2d.raw.World; +import net.phys2d.raw.shapes.Box; +import net.phys2d.raw.strategies.QuadSpaceStrategy; + +public class SmileyPhysics extends AbstractPhysicsEngine{ + + public Body body2; // smiley body + + public void init() { + world = new World(new Vector2f(0.0f, 10.0f), 10, new QuadSpaceStrategy(20,5)); + world.clear(); + world.setGravity(0,10); + + Body body1 = new StaticBody("Ground1", new Box(400.0f, 20.0f)); + body1.setPosition(250.0f, 400); + world.add(body1); + Body body3 = new StaticBody("Ground2", new Box(200.0f, 20.0f)); + body3.setPosition(360.0f, 380); + world.add(body3); + Body body5 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body5.setPosition(200.0f, 300); + world.add(body5); + Body body6 = new StaticBody("Ground3", new Box(20.0f, 100.0f)); + body6.setPosition(400.0f, 300); + world.add(body6); + + body2 = new Body("Mover1", new Box(100.0f, 100.0f), 10.0f); + body2.setPosition(250.0f, 4.0f); + world.add(body2); +// Body body4 = new Body("Mover2", new Box(50.0f, 50.0f), 100.0f); +// body4.setPosition(230.0f, -60.0f); +// world.add(body4); +// Body body8 = new Body("Mover3", new Box(50.0f, 50.0f), 100.0f); +// body8.setPosition(280.0f, -120.0f); +// world.add(body8); + + } + +} diff --git a/tester/SmileyTester.java b/tester/SmileyTester.java new file mode 100644 index 0000000..e1cce83 --- /dev/null +++ b/tester/SmileyTester.java @@ -0,0 +1,77 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; + +import net.phys2d.math.Vector2f; +import net.phys2d.raw.Body; + +import kobaltBasic.BasicGame; +import kobaltBasic.KeyboardSupport; +import kobaltBasic.Sprite; +import kobaltBasic.Utilities; + +public class SmileyTester extends BasicGame implements KeyboardSupport{ + + Smiley s; + SmileyPhysics sp; + Body sbody; + + public SmileyTester(String title, int w, int h) { + super(title, w, h); + + sp = new SmileyPhysics(); + sp.init(); + sbody = sp.body2; + + + s = new Smiley(new Sprite(Utilities.load("tester/resources/smiley.png")), sp.body2); + + addKeyboardSupport(this); + + + } + + /** + * @param args + */ + public static void main(String[] args) { + new SmileyTester("Smiley Tester",640,480).start(); + + } + + @Override + public void render(Graphics2D g) { + fillWithColor(WHITE); + s.render(g); + sp.render(g); // debugging + + } + + @Override + public void update() { + sp.update(); + s.update(); + + } + + + static final Vector2f up = new Vector2f(0,-2000); + static final Vector2f left = new Vector2f(-2000, 0); + static final Vector2f right = new Vector2f(2000 ,0); + + public void handleKeyPress(int keyCode) { + + if(keyCode == KeyEvent.VK_UP) sbody.addForce(up); + if(keyCode == KeyEvent.VK_LEFT) sbody.addForce(left); + if(keyCode == KeyEvent.VK_RIGHT) sbody.addForce(right); + + } + + public void handleKeyRelease(int keyCode) { + + + } + + +} diff --git a/tester/SpaceBG.java b/tester/SpaceBG.java new file mode 100644 index 0000000..57250bb --- /dev/null +++ b/tester/SpaceBG.java @@ -0,0 +1,47 @@ +package tester; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import effects.Drawable; + +import kobaltBasic.Utilities; + + + +public class SpaceBG implements Drawable { + + BufferedImage bg; + + public SpaceBG(){ + bg = Utilities.load("tester/resources/horsehead-nebula.jpg"); + } + + public void draw(Graphics2D g){ + + g.drawImage(bg,0,0,null); + } + + public int getHeight() { + // TODO Auto-generated method stub + return bg.getHeight(); + } + + public int getWidth() { + // TODO Auto-generated method stub + return bg.getWidth(); + } + + public int getX() { + // TODO Auto-generated method stub + return 0; + } + + public int getY() { + // TODO Auto-generated method stub + return 0; + } + + + +} diff --git a/tester/Spaceship.java b/tester/Spaceship.java new file mode 100644 index 0000000..096eee0 --- /dev/null +++ b/tester/Spaceship.java @@ -0,0 +1,52 @@ +package tester; + +import kobaltBasic.KeyboardSupport; +import kobaltBasic.RotatingSpriteActor; +import kobaltBasic.Sprite; + +/* + * Implementing ControlledByKeyboard lets this entity respond to keyboard button presses. + */ + +public class Spaceship extends RotatingSpriteActor implements KeyboardSupport { + + + + /* + * Sprite s: The sprite that this game entity will use, can contain multiple frames + * posX: X position of the entity + * posY: Y position of the entity + */ + public Spaceship(Sprite s, int posX, int posY) { + super(s, posX, posY); + x = posX; + y = posY; + + } + + + + public void handleKeyPress(int keyCode) { + + + + if(keyCode == UP) this.y_velocity = -100; // if the up button is pressed set negative velocity to go up + + if(keyCode == DOWN) this.y_velocity = 100; // if down button is pressed positive velocity to go down + + if(keyCode == LEFT) this.x_velocity = -100; + if(keyCode == RIGHT) this.x_velocity = 100; + + + } + + public void handleKeyRelease(int keyCode) { + this.y_velocity = 0; // when no key is being pressed set velocity to zero, otherwise the bar floats off the screen + this.x_velocity = 0; + + + } + + + +} diff --git a/tester/TileTester.java b/tester/TileTester.java new file mode 100644 index 0000000..2cf7d0e --- /dev/null +++ b/tester/TileTester.java @@ -0,0 +1,51 @@ +package tester; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import kobaltBasic.*; + +public class TileTester extends BasicGame { + + Spritesheet tiles = new Spritesheet("tester/resources/tiles.png"); + BufferedImage img = null; + + public TileTester(String title, int w, int h) { + super(title, w, h); + + + tiles.imgWidth = 22; + tiles.hOffset = 1; + tiles.vOffset = 4; + tiles.imgHeight = 24; + tiles.numColumns = 5; + tiles.numRows = 8; + tiles.maskColor = new Color(191,220,191); + + tiles.extractAll("tester/resources/tiles.txt"); + + BufferedImage buf[] = tiles.extractRow(0, 168, 22, 24, 2, 5); + img = buf[4]; + + } + + @Override + public void render(Graphics2D g) { + fillWithColor(BLACK); + + g.drawImage(img, 100, 100, null); + + } + + @Override + public void update() {} + + + public static void main(String[] args) { + new TileTester("Tile Test Demo", 640, 480).start(); + } + + + +} diff --git a/tester/TwirlTester.java b/tester/TwirlTester.java new file mode 100644 index 0000000..ebb587c --- /dev/null +++ b/tester/TwirlTester.java @@ -0,0 +1,42 @@ +package tester; + +import java.awt.Graphics2D; + +import kobaltBasic.BasicGame; +import effects.TwirlEffect; + +public class TwirlTester extends BasicGame { + + + SpaceBG bg; + TwirlEffect effect; + + public TwirlTester(String title, int w, int h) { + super(title, w, h); + + bg = new SpaceBG(); + effect = new TwirlEffect(350,100); + + } + + + public void render(Graphics2D g) { + + bg.draw(g); + effect.applyEffect(g); + + + } + + public void update() { + effect.update(); + } + + + + public static void main(String[] args) { + new TwirlTester("Twirl Tester",640,480).start(); // creates a new game window of size 640x480 and starts the game loop. + + } + +} diff --git a/tester/VectorPlayer.java b/tester/VectorPlayer.java new file mode 100644 index 0000000..6578a17 --- /dev/null +++ b/tester/VectorPlayer.java @@ -0,0 +1,52 @@ +package tester; + +import java.awt.geom.Area; + +import kobaltBasic.KeyboardSupport; +import kobaltBasic.RotatingSpriteActor; +import kobaltBasic.Sprite; + + + +public class VectorPlayer extends RotatingSpriteActor implements KeyboardSupport { + + public VectorPlayer(Sprite s, Area vectorSprite, double x, double y) { + super(s, x, y); + + this.setBounds(vectorSprite); + } + + public void handleKeyPress(int keyCode) { + + if(keyCode == UP) { + this.heading = 0; + this.velocity = -100; // if the up button is pressed set negative velocity to go up + } + + if(keyCode == DOWN) { + this.heading = 0; + this.velocity = 100; // if down button is pressed positive velocity to go down + } + + if(keyCode == LEFT) { + this.heading = -90; + this.velocity = 100; + } + if(keyCode == RIGHT) { + this.heading = 90; + this.velocity = 100; + } + + } + + public void handleKeyRelease(int keyCode) { + if(keyCode == UP) this.velocity = 0; // if the up button is pressed set negative velocity to go up + + if(keyCode == DOWN) this.velocity = 0; // if down button is pressed positive velocity to go down + + if(keyCode == LEFT) this.velocity = 0; + if(keyCode == RIGHT) this.velocity = 0; + + } + +} diff --git a/tester/resources/blue-grad.gif b/tester/resources/blue-grad.gif new file mode 100644 index 0000000..e9b0a31 Binary files /dev/null and b/tester/resources/blue-grad.gif differ diff --git a/tester/resources/bubble-mask.gif b/tester/resources/bubble-mask.gif new file mode 100644 index 0000000..2f66cec Binary files /dev/null and b/tester/resources/bubble-mask.gif differ diff --git a/tester/resources/bubble.gif b/tester/resources/bubble.gif new file mode 100644 index 0000000..6bfdc4b Binary files /dev/null and b/tester/resources/bubble.gif differ diff --git a/tester/resources/dand-mask.gif b/tester/resources/dand-mask.gif new file mode 100644 index 0000000..221350e Binary files /dev/null and b/tester/resources/dand-mask.gif differ diff --git a/tester/resources/dand.gif b/tester/resources/dand.gif new file mode 100644 index 0000000..9053012 Binary files /dev/null and b/tester/resources/dand.gif differ diff --git a/tester/resources/grad.gif b/tester/resources/grad.gif new file mode 100644 index 0000000..99bafb7 Binary files /dev/null and b/tester/resources/grad.gif differ diff --git a/tester/resources/hbm.gif b/tester/resources/hbm.gif new file mode 100644 index 0000000..74565f1 Binary files /dev/null and b/tester/resources/hbm.gif differ diff --git a/tester/resources/horsehead-nebula.jpg b/tester/resources/horsehead-nebula.jpg new file mode 100644 index 0000000..7adeeb2 Binary files /dev/null and b/tester/resources/horsehead-nebula.jpg differ diff --git a/tester/resources/mario_bg.gif b/tester/resources/mario_bg.gif new file mode 100644 index 0000000..7c9f8df Binary files /dev/null and b/tester/resources/mario_bg.gif differ diff --git a/tester/resources/megaman_sheet.png b/tester/resources/megaman_sheet.png new file mode 100644 index 0000000..57a32de Binary files /dev/null and b/tester/resources/megaman_sheet.png differ diff --git a/tester/resources/pixelship.gif b/tester/resources/pixelship.gif new file mode 100644 index 0000000..979fed5 Binary files /dev/null and b/tester/resources/pixelship.gif differ diff --git a/tester/resources/player.png b/tester/resources/player.png new file mode 100644 index 0000000..faba8e3 Binary files /dev/null and b/tester/resources/player.png differ diff --git a/tester/resources/pong.gif b/tester/resources/pong.gif new file mode 100644 index 0000000..303de4a Binary files /dev/null and b/tester/resources/pong.gif differ diff --git a/tester/resources/powergenerator.gif b/tester/resources/powergenerator.gif new file mode 100644 index 0000000..b0fb333 Binary files /dev/null and b/tester/resources/powergenerator.gif differ diff --git a/tester/resources/sky2.png b/tester/resources/sky2.png new file mode 100644 index 0000000..f4c620d Binary files /dev/null and b/tester/resources/sky2.png differ diff --git a/tester/resources/smiley.png b/tester/resources/smiley.png new file mode 100644 index 0000000..e3da017 Binary files /dev/null and b/tester/resources/smiley.png differ diff --git a/tester/resources/starburst.gif b/tester/resources/starburst.gif new file mode 100644 index 0000000..7609fdb Binary files /dev/null and b/tester/resources/starburst.gif differ diff --git a/tester/resources/sun-mask.png b/tester/resources/sun-mask.png new file mode 100644 index 0000000..07085e8 Binary files /dev/null and b/tester/resources/sun-mask.png differ diff --git a/tester/resources/sun.png b/tester/resources/sun.png new file mode 100644 index 0000000..afd27dc Binary files /dev/null and b/tester/resources/sun.png differ diff --git a/tester/resources/tiles.png b/tester/resources/tiles.png new file mode 100644 index 0000000..ceaa5f9 Binary files /dev/null and b/tester/resources/tiles.png differ diff --git a/tester/resources/tiles.txt b/tester/resources/tiles.txt new file mode 100644 index 0000000..d3fde18 --- /dev/null +++ b/tester/resources/tiles.txt @@ -0,0 +1,8 @@ +01 02 03 04 05 +06 07 08 09 10 +11 12 13 14 15 +16 17 18 19 20 +21 22 23 24 25 +26 27 28 29 30 +31 32 33 34 35 +36 37 38 39 40 \ No newline at end of file
dudarev/ssm2010
033c61f05844c4a7578dccd04a2e12e43dd20e17
more text styling
diff --git a/index.html b/index.html index 6df9d7e..743ef0f 100644 --- a/index.html +++ b/index.html @@ -1,74 +1,74 @@ <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>dudarev/ssm2010 @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: #fff; font-family: "Helvetica,Arial,FreeSans"; color: #000000; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; } h1 .small { font-size: 0.4em; } h1 a { text-decoration: none } h2 { font-size: 1.5em; color: #000000; } h3 { text-align: center; color: #000000; } a { color: #000000; } .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <div id="container"> <h1><a href="http://github.com/dudarev/ssm2010">ssm2010</a> </h1> <div class="description"> Notes on tweets related to Search in Social Media 2010 workshop </div> <div class="section"> <h2><a id="about-ssm2010" name="about-ssm2010">About SSM2010</a></h2> -<p>The Third Annual Workshop on Search in Social Media (<a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/">SSM 2010</a>) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (<a class="reference" href="http://twitter.com/hmason">&#64;hmason</a>). The topics discussed are of great interest to me nowadays (informal proceedings by all the speakers are <a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/proceedings.html">available in PDF format</a>).</p> +<p>The Third Annual Workshop on Search in Social Media (<a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/">SSM 2010</a>) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (<a class="reference" href="http://twitter.com/hmason">&#64;hmason</a>). The topics discussed are of great interest to me nowadays. Informal proceedings by all the speakers are <a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/proceedings.html">available in PDF format</a>.</p> </div> <div class="section"> <h2><a id="notes" name="notes">Notes</a></h2> <p>Thanks to the tweets from the audience (especially Gene Golovchinsky <a class="reference" href="http://twitter.com/HCIR_GeneG">&#64; HCIR_GeneG</a>) it was possible to follow discussions during the panels. Ian Soboroff <a class="reference" href="http://twitter.com/ian_soboroff">&#64;ian_soboroff</a> initiated archiving of tweets hashtaged with #ssm2010 at <a class="reference" href="http://twapperkeeper.com/ssm2010/">http://twapperkeeper.com/ssm2010/</a></p> <dl class="docutils"> -<dt>It was fun to follow the discussions during the meeting with Twitter search. To somewhat systemitize thoughts I used <a class="reference" href="http://en.wikipedia.org/wiki/Mind_map">mind mapping</a> approach with <a class="reference" href="http://freemind.sourceforge.net/">FreeMind</a> software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format:</dt> +<dt>It was fun to follow the discussions during the meeting with Twitter search. To somewhat systematize thoughts I used <a class="reference" href="http://en.wikipedia.org/wiki/Mind_map">mind mapping</a> approach with <a class="reference" href="http://freemind.sourceforge.net/">FreeMind</a> software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format:</dt> <dd><ul class="first last simple"> <li>First panel (Yahoo!, Microsoft, Google representatives) [<a class="reference" href="ssm2010_first_panel.html">html</a>, <a class="reference" href="ssm2010_first_panel.mm">mm</a>]</li> <li>Second panel (representatives from Myspace, Bit.ly, LinkedIn) [<a class="reference" href="ssm2010_second_panel.html">html</a>, <a class="reference" href="ssm2010_second_panel.mm">mm</a>]</li> </ul> </dd> </dl> </div> <div class="footer"> this page is hosted on github : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> </div> </div> </body> </html> diff --git a/index.rst b/index.rst index 17a99fa..2074268 100644 --- a/index.rst +++ b/index.rst @@ -1,21 +1,21 @@ SSM2010 ======= SSM2010 ======= About SSM2010 -------------- -The Third Annual Workshop on Search in Social Media (`SSM 2010 <http://ir.mathcs.emory.edu/SSM2010/>`__) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (`@hmason <http://twitter.com/hmason>`__). The topics discussed are of great interest to me nowadays (informal proceedings by all the speakers are `available in PDF format <http://ir.mathcs.emory.edu/SSM2010/proceedings.html>`__). +The Third Annual Workshop on Search in Social Media (`SSM 2010 <http://ir.mathcs.emory.edu/SSM2010/>`__) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (`@hmason <http://twitter.com/hmason>`__). The topics discussed are of great interest to me nowadays. Informal proceedings by all the speakers are `available in PDF format <http://ir.mathcs.emory.edu/SSM2010/proceedings.html>`__. Notes ------ Thanks to the tweets from the audience (especially Gene Golovchinsky `@ HCIR_GeneG <http://twitter.com/HCIR_GeneG>`__) it was possible to follow discussions during the panels. Ian Soboroff `@ian_soboroff <http://twitter.com/ian_soboroff>`__ initiated archiving of tweets hashtaged with #ssm2010 at http://twapperkeeper.com/ssm2010/ It was fun to follow the discussions during the meeting with Twitter search. To somewhat systematize thoughts I used `mind mapping <http://en.wikipedia.org/wiki/Mind_map>`__ approach with `FreeMind <http://freemind.sourceforge.net/>`__ software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format: - First panel (Yahoo!, Microsoft, Google representatives) [`html <ssm2010_first_panel.html>`__, `mm <ssm2010_first_panel.mm>`__] - Second panel (representatives from Myspace, Bit.ly, LinkedIn) [`html <ssm2010_second_panel.html>`__, `mm <ssm2010_second_panel.mm>`__]
dudarev/ssm2010
93874ccb45981bbef73ebde60c91003f4f98dfd5
archive of 450 tweets
diff --git a/index.rst b/index.rst index 86e324e..17a99fa 100644 --- a/index.rst +++ b/index.rst @@ -1,21 +1,21 @@ SSM2010 ======= SSM2010 ======= About SSM2010 -------------- The Third Annual Workshop on Search in Social Media (`SSM 2010 <http://ir.mathcs.emory.edu/SSM2010/>`__) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (`@hmason <http://twitter.com/hmason>`__). The topics discussed are of great interest to me nowadays (informal proceedings by all the speakers are `available in PDF format <http://ir.mathcs.emory.edu/SSM2010/proceedings.html>`__). Notes ------ Thanks to the tweets from the audience (especially Gene Golovchinsky `@ HCIR_GeneG <http://twitter.com/HCIR_GeneG>`__) it was possible to follow discussions during the panels. Ian Soboroff `@ian_soboroff <http://twitter.com/ian_soboroff>`__ initiated archiving of tweets hashtaged with #ssm2010 at http://twapperkeeper.com/ssm2010/ -It was fun to follow the discussions during the meeting with Twitter search. To somewhat systemitize thoughts I used `mind mapping <http://en.wikipedia.org/wiki/Mind_map>`__ approach with `FreeMind <http://freemind.sourceforge.net/>`__ software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format: +It was fun to follow the discussions during the meeting with Twitter search. To somewhat systematize thoughts I used `mind mapping <http://en.wikipedia.org/wiki/Mind_map>`__ approach with `FreeMind <http://freemind.sourceforge.net/>`__ software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format: - First panel (Yahoo!, Microsoft, Google representatives) [`html <ssm2010_first_panel.html>`__, `mm <ssm2010_first_panel.mm>`__] - Second panel (representatives from Myspace, Bit.ly, LinkedIn) [`html <ssm2010_second_panel.html>`__, `mm <ssm2010_second_panel.mm>`__] diff --git a/ssm2010-4b69eb3ed6313.tar b/ssm2010-4b69eb3ed6313.tar new file mode 100644 index 0000000..cbaf93f Binary files /dev/null and b/ssm2010-4b69eb3ed6313.tar differ
dudarev/ssm2010
012a66bc00ea43ba130bf8faa474f845aa8c2d07
added exported html files
diff --git a/index.html b/index.html index c238678..6df9d7e 100644 --- a/index.html +++ b/index.html @@ -1,76 +1,74 @@ <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>dudarev/ssm2010 @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: #fff; font-family: "Helvetica,Arial,FreeSans"; color: #000000; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; } h1 .small { font-size: 0.4em; } h1 a { text-decoration: none } h2 { font-size: 1.5em; color: #000000; } h3 { text-align: center; color: #000000; } a { color: #000000; } .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <div id="container"> <h1><a href="http://github.com/dudarev/ssm2010">ssm2010</a> </h1> <div class="description"> - My notes on tweets related to Search in Social Media 2010 workshop + Notes on tweets related to Search in Social Media 2010 workshop </div> - <div class="section"> <h2><a id="about-ssm2010" name="about-ssm2010">About SSM2010</a></h2> -<p>The Third Annual Workshop on Search in Social Media (SSM 2010) took place.</p> +<p>The Third Annual Workshop on Search in Social Media (<a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/">SSM 2010</a>) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (<a class="reference" href="http://twitter.com/hmason">&#64;hmason</a>). The topics discussed are of great interest to me nowadays (informal proceedings by all the speakers are <a class="reference" href="http://ir.mathcs.emory.edu/SSM2010/proceedings.html">available in PDF format</a>).</p> </div> <div class="section"> <h2><a id="notes" name="notes">Notes</a></h2> +<p>Thanks to the tweets from the audience (especially Gene Golovchinsky <a class="reference" href="http://twitter.com/HCIR_GeneG">&#64; HCIR_GeneG</a>) it was possible to follow discussions during the panels. Ian Soboroff <a class="reference" href="http://twitter.com/ian_soboroff">&#64;ian_soboroff</a> initiated archiving of tweets hashtaged with #ssm2010 at <a class="reference" href="http://twapperkeeper.com/ssm2010/">http://twapperkeeper.com/ssm2010/</a></p> <dl class="docutils"> -<dt>In FreeMind format:</dt> +<dt>It was fun to follow the discussions during the meeting with Twitter search. To somewhat systemitize thoughts I used <a class="reference" href="http://en.wikipedia.org/wiki/Mind_map">mind mapping</a> approach with <a class="reference" href="http://freemind.sourceforge.net/">FreeMind</a> software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format:</dt> <dd><ul class="first last simple"> -<li><a class="reference" href="ssm2010_first_panel.mm">First panel</a></li> -<li><a class="reference" href="ssm2010_second_panel.mm">Second panel</a></li> +<li>First panel (Yahoo!, Microsoft, Google representatives) [<a class="reference" href="ssm2010_first_panel.html">html</a>, <a class="reference" href="ssm2010_first_panel.mm">mm</a>]</li> +<li>Second panel (representatives from Myspace, Bit.ly, LinkedIn) [<a class="reference" href="ssm2010_second_panel.html">html</a>, <a class="reference" href="ssm2010_second_panel.mm">mm</a>]</li> </ul> </dd> </dl> </div> - - <div class="footer"> this page is hosted on github : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> </div> </div> </body> </html> diff --git a/index.rst b/index.rst index 7f0df63..86e324e 100644 --- a/index.rst +++ b/index.rst @@ -1,19 +1,21 @@ SSM2010 ======= SSM2010 ======= About SSM2010 -------------- -The Third Annual Workshop on Search in Social Media (SSM 2010) took place. +The Third Annual Workshop on Search in Social Media (`SSM 2010 <http://ir.mathcs.emory.edu/SSM2010/>`__) took place in New York on February 3rd 2010. It came to my attention because of tweets by Hilary Mason (`@hmason <http://twitter.com/hmason>`__). The topics discussed are of great interest to me nowadays (informal proceedings by all the speakers are `available in PDF format <http://ir.mathcs.emory.edu/SSM2010/proceedings.html>`__). Notes ------ -In FreeMind format: - - `First panel <ssm2010_first_panel.mm>`__ - - `Second panel <ssm2010_second_panel.mm>`__ +Thanks to the tweets from the audience (especially Gene Golovchinsky `@ HCIR_GeneG <http://twitter.com/HCIR_GeneG>`__) it was possible to follow discussions during the panels. Ian Soboroff `@ian_soboroff <http://twitter.com/ian_soboroff>`__ initiated archiving of tweets hashtaged with #ssm2010 at http://twapperkeeper.com/ssm2010/ + +It was fun to follow the discussions during the meeting with Twitter search. To somewhat systemitize thoughts I used `mind mapping <http://en.wikipedia.org/wiki/Mind_map>`__ approach with `FreeMind <http://freemind.sourceforge.net/>`__ software. Below are the files for the first and the second panels exported to HTML and in native FreeMind format: + - First panel (Yahoo!, Microsoft, Google representatives) [`html <ssm2010_first_panel.html>`__, `mm <ssm2010_first_panel.mm>`__] + - Second panel (representatives from Myspace, Bit.ly, LinkedIn) [`html <ssm2010_second_panel.html>`__, `mm <ssm2010_second_panel.mm>`__] diff --git a/ssm2010_first_panel.html b/ssm2010_first_panel.html new file mode 100644 index 0000000..3f50ed2 --- /dev/null +++ b/ssm2010_first_panel.html @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="iso-8859-1"?><?xml-stylesheet href="treestyles.css" type="text/css"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> +<html xml:lang="fi" xmlns="http://www.w3.org/1999/xhtml"><head><title>#ssm2010 first panel</title><link rel="stylesheet" href="ssm2010_first_panel.html_files/treestyles.css" type="text/css"/><script type="text/javascript" src="ssm2010_first_panel.html_files/marktree.js">  </script></head><body><div class="basetop"><a href="#" onclick="expandAll(document.getElementById('base'))">Expand</a> - <a href="#" onclick="collapseAll(document.getElementById('base'))">Collapse</a></div><div id="base" class="basetext"><ul><li class="col" style="" id="FMFreemind_Link_180953392FM"><span style="">#ssm2010 first panel</span><ul class="subexp"><li class="exp" style="" id="FMFreemind_Link_1230387569FM"><span style="">People</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_266182439FM"><span style="">Sihem Amer-Yahia, Yahoo! research </span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_999832029FM"><span style="">ian_soboroff: #ssm2010 Sihem Amer-Yahia, Yahoo! research </span></li></ul></li><li class="basic" style="" id="FMFreemind_Link_156039090FM"><span style="">Jeremy Hylton, Google</span></li><li class="basic" style="" id="FMFreemind_Link_1607804504FM"><span style="">Matt Hurst, Microsoft</span></li></ul></li><li class="exp" style="" id="FM_FM"><span style="">Companies</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1878883213FM"><span style="">Baidu</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1434796548FM"><span style="">TaoBao</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1758601062FM"><span style="">jny2: William Chang of Baidu: China's version of eBay--called TaoBao--is 1% or 2% percent of GDP. OMG, did I just hear that correctly?! #ssm2010</span></li><li class="basic" style="" id="FMFreemind_Link_1105832984FM"><span style="">Search is bad but they do (decent) recommendations @nitya</span></li></ul></li><li class="basic" style="" id="FMFreemind_Link_544851444FM"><span style="">forum search</span></li><li class="col" style="" id="FMFreemind_Link_881033084FM"><span style="">Observations</span><ul class="subexp"><li class="basic" style="" id="FMFreemind_Link_450105447FM"><span style="">HCIR_GeneG: #ssm2010 google delivers baidu content in China</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_423627865FM"><span style="">Yahoo</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_737877236FM"><span style="">HCIR_GeneG: #ssm2010 Amer-Yahia: in travel , most queries are tag-browsing, not text-typing</span></li><li class="basic" style="" id="FMFreemind_Link_1680587614FM"><span style=""><a href="#Freemind_Link_813826843">Yahoo Answers</a> <a href="#Freemind_Link_813826843"><img src="ssm2010_first_panel.html_files/icons/Link.png" alt="" style="border-width:0"/></a></span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_709914783FM"><span style="">Microsoft</span><ul class="sub"><li class="col" style="" id="FMFreemind_Link_625324909FM"><span style="">Bing Local</span><ul class="subexp"><li class="basic" style="" id="FMFreemind_Link_1917644998FM"><span style="">ian_soboroff: #ssm2010 bing local lens - surfacing hyperlocal content</span></li><li class="basic" style="" id="FMFreemind_Link_769522831FM"><span style="">HCIR_GeneG: #ssm2010 Hurst: local lens: crawing and minig hyper-local blog content</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_189590157FM"><span style="">Google</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1427352657FM"><span style="">Relevance of Social Search</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1287322606FM"><span style="">HCIR_GeneG: #ssm2010 a q: has google social search been evaluated for relevance?</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_723806724FM"><span style="">Naver</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_183951216FM"><span style="">nitya: #ssm2010 naver has branded advertising mixed in with search results (how naver makes portal work)</span></li><li class="basic" style="" id="FMFreemind_Link_813826843FM"><span style="">HCIR_GeneG: #ssm2010 Petersen: yahoo answers an attempt to recrate Naver in the US. Didn't work due to lack of high level of authority. No social graph</span></li><li class="basic" style="" id="FMFreemind_Link_762332142FM"><span style="">HCIR_GeneG: #ssm2010 Petersen: yahoo answers degenerated into chatting in part due to optional anonymity</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_139605643FM"><span style="">Aardvark</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1107943FM"><span style="">nitya: #ssm2010 Jan talking about @vark http://vark.com/aardvarkFinalWWW2010.pdf for the paper he cited. I highly recommend it -- great insights</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_9424424FM"><span style="">Twitter</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1106977666FM"><span style="">Observations</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1505949185FM"><span style="">HCIR_GeneG: #ssm2010 Petersen: breaking news on twitter peaks within two minutes of event</span></li><li class="basic" style="" id="FMFreemind_Link_958478883FM"><span style="">jny2: "It's not so much the tweet itself, but the referring content," says Jan Pederson. Show the page to which the tweet points! #ssm2010</span></li><li class="basic" style="" id="FMFreemind_Link_590363872FM"><span style="">nitya: #ssm2010 nice point made about Twitter providing "observable" propagation of information (RT, via, @replies etc...)</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1388855541FM"><span style="">Spam on Twitter</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1420488927FM"><span style="">nitya: #ssm2010 in the context of twitter and spam -- a great article on bots and spam detection http://bit.ly/4zekRD</span></li><li class="basic" style="" id="FMFreemind_Link_615168068FM"><span style="">jny2: On twitter, it's easy to detect spam. A "naturally connected community" is very different from a "spam marketing campaign." #ssm2010 Huh!</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1992659151FM"><span style="">Trends</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1224337196FM"><span style="">jny2: Matthew Hurst sez: There's a loop in which things "trend on twitter just because they trend on twitter." #ssm2010 We need to unwind that.</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1653779855FM"><span style="">Paper on Retweeting</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_198951219FM"><span style="">No figures :(</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_751034946FM"><span style="">nitya: #ssm2010 Re: the retweeting as indicator of peaking, @zephoria paper on Retweets is a must-read to understand intents http://bit.ly/PCKTo</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1219317989FM"><span style="">Breacking News</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1546684485FM"><span style="">HCIR_GeneG: #ssm2010 Petersen: breaking news on twitter peaks within two minutes of event</span></li><li class="basic" style="" id="FMFreemind_Link_1783116050FM"><span style="">nitya: #ssm2010 Next Use Case: Breaking News -- emergency events like earthquakes etc. (USGS looking at Twitter for detection http://bit.ly/aAejiA</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1243291700FM"><span style="">General Observations</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1050956729FM"><span style="">Identities</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1440985821FM"><span style="">HCIR_GeneG: #ssm2010 chang: trust people in social network. don't worry about strangers</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1326526688FM"><span style="">Search vs. Monitoring</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_883208911FM"><span style="">HCIR_GeneG: #ssm2010 hylton: implicit queries. What's going on here, what's trending in my social network?</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_21606023FM"><span style="">Algoritm vs. Recommendation</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_244043529FM"><span style="">HCIR_GeneG: #ssm2010 hurst: answer from a specific person carries different weight than aggregated data.</span></li><li class="basic" style="" id="FMFreemind_Link_1182822588FM"><span style="">HCIR_GeneG: #ssm2010 hurst: might mistrust algorithm more than known (trusted) expert</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1986986882FM"><span style="">Information Needs not Social Search</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1700779959FM"><span style="">HCIR_GeneG: #ssm2010 hylton: define specific information needs rather than social search. Web has always been social. e.g: home page.</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_325278824FM"><span style="">Social vs. Simple Search</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1155606501FM"><span style="">HCIR_GeneG: #ssm2010 Petersen: web search is driven by metadata; social media aslo has minable metadata</span></li></ul></li></ul></li></ul></li></ul></div></body></html> \ No newline at end of file diff --git a/ssm2010_first_panel.html_files/icons/Mail.png b/ssm2010_first_panel.html_files/icons/Mail.png new file mode 100644 index 0000000..beea00e Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/Mail.png differ diff --git a/ssm2010_first_panel.html_files/icons/attach.png b/ssm2010_first_panel.html_files/icons/attach.png new file mode 100644 index 0000000..b03a77e Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/attach.png differ diff --git a/ssm2010_first_panel.html_files/icons/back.png b/ssm2010_first_panel.html_files/icons/back.png new file mode 100644 index 0000000..5a86cd8 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/back.png differ diff --git a/ssm2010_first_panel.html_files/icons/bell.png b/ssm2010_first_panel.html_files/icons/bell.png new file mode 100644 index 0000000..8afab9d Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/bell.png differ diff --git a/ssm2010_first_panel.html_files/icons/bookmark.png b/ssm2010_first_panel.html_files/icons/bookmark.png new file mode 100644 index 0000000..67f1832 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/bookmark.png differ diff --git a/ssm2010_first_panel.html_files/icons/button_cancel.png b/ssm2010_first_panel.html_files/icons/button_cancel.png new file mode 100644 index 0000000..a9c624a Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/button_cancel.png differ diff --git a/ssm2010_first_panel.html_files/icons/button_ok.png b/ssm2010_first_panel.html_files/icons/button_ok.png new file mode 100644 index 0000000..9a817fd Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/button_ok.png differ diff --git a/ssm2010_first_panel.html_files/icons/clanbomber.png b/ssm2010_first_panel.html_files/icons/clanbomber.png new file mode 100644 index 0000000..16679ba Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/clanbomber.png differ diff --git a/ssm2010_first_panel.html_files/icons/desktop_new.png b/ssm2010_first_panel.html_files/icons/desktop_new.png new file mode 100644 index 0000000..366368f Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/desktop_new.png differ diff --git a/ssm2010_first_panel.html_files/icons/flag.png b/ssm2010_first_panel.html_files/icons/flag.png new file mode 100644 index 0000000..e9defd1 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/flag.png differ diff --git a/ssm2010_first_panel.html_files/icons/forward.png b/ssm2010_first_panel.html_files/icons/forward.png new file mode 100644 index 0000000..b80d28a Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/forward.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-1.png b/ssm2010_first_panel.html_files/icons/full-1.png new file mode 100644 index 0000000..80a6c66 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-1.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-2.png b/ssm2010_first_panel.html_files/icons/full-2.png new file mode 100644 index 0000000..bc26aef Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-2.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-3.png b/ssm2010_first_panel.html_files/icons/full-3.png new file mode 100644 index 0000000..e419464 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-3.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-4.png b/ssm2010_first_panel.html_files/icons/full-4.png new file mode 100644 index 0000000..d82ee2f Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-4.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-5.png b/ssm2010_first_panel.html_files/icons/full-5.png new file mode 100644 index 0000000..2860401 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-5.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-6.png b/ssm2010_first_panel.html_files/icons/full-6.png new file mode 100644 index 0000000..10ef02a Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-6.png differ diff --git a/ssm2010_first_panel.html_files/icons/full-7.png b/ssm2010_first_panel.html_files/icons/full-7.png new file mode 100644 index 0000000..e55f3ff Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/full-7.png differ diff --git a/ssm2010_first_panel.html_files/icons/gohome.png b/ssm2010_first_panel.html_files/icons/gohome.png new file mode 100644 index 0000000..17bf02f Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/gohome.png differ diff --git a/ssm2010_first_panel.html_files/icons/help.png b/ssm2010_first_panel.html_files/icons/help.png new file mode 100644 index 0000000..d6391a2 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/help.png differ diff --git a/ssm2010_first_panel.html_files/icons/idea.png b/ssm2010_first_panel.html_files/icons/idea.png new file mode 100644 index 0000000..8d18b02 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/idea.png differ diff --git a/ssm2010_first_panel.html_files/icons/kaddressbook.png b/ssm2010_first_panel.html_files/icons/kaddressbook.png new file mode 100644 index 0000000..8bfe4ae Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/kaddressbook.png differ diff --git a/ssm2010_first_panel.html_files/icons/knotify.png b/ssm2010_first_panel.html_files/icons/knotify.png new file mode 100644 index 0000000..0104e72 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/knotify.png differ diff --git a/ssm2010_first_panel.html_files/icons/korn.png b/ssm2010_first_panel.html_files/icons/korn.png new file mode 100644 index 0000000..a4e9107 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/korn.png differ diff --git a/ssm2010_first_panel.html_files/icons/ksmiletris.png b/ssm2010_first_panel.html_files/icons/ksmiletris.png new file mode 100644 index 0000000..b95f903 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/ksmiletris.png differ diff --git a/ssm2010_first_panel.html_files/icons/licq.png b/ssm2010_first_panel.html_files/icons/licq.png new file mode 100644 index 0000000..34f8cce Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/licq.png differ diff --git a/ssm2010_first_panel.html_files/icons/messagebox_warning.png b/ssm2010_first_panel.html_files/icons/messagebox_warning.png new file mode 100644 index 0000000..afc9c9c Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/messagebox_warning.png differ diff --git a/ssm2010_first_panel.html_files/icons/password.png b/ssm2010_first_panel.html_files/icons/password.png new file mode 100644 index 0000000..5e86bbb Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/password.png differ diff --git a/ssm2010_first_panel.html_files/icons/pencil.png b/ssm2010_first_panel.html_files/icons/pencil.png new file mode 100644 index 0000000..575dd32 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/pencil.png differ diff --git a/ssm2010_first_panel.html_files/icons/penguin.png b/ssm2010_first_panel.html_files/icons/penguin.png new file mode 100644 index 0000000..0f61ec5 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/penguin.png differ diff --git a/ssm2010_first_panel.html_files/icons/stop.png b/ssm2010_first_panel.html_files/icons/stop.png new file mode 100644 index 0000000..981c4cf Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/stop.png differ diff --git a/ssm2010_first_panel.html_files/icons/wizard.png b/ssm2010_first_panel.html_files/icons/wizard.png new file mode 100644 index 0000000..93a1d91 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/wizard.png differ diff --git a/ssm2010_first_panel.html_files/icons/xmag.png b/ssm2010_first_panel.html_files/icons/xmag.png new file mode 100644 index 0000000..32a4a15 Binary files /dev/null and b/ssm2010_first_panel.html_files/icons/xmag.png differ diff --git a/ssm2010_first_panel.html_files/marktree.js b/ssm2010_first_panel.html_files/marktree.js new file mode 100644 index 0000000..10bba60 --- /dev/null +++ b/ssm2010_first_panel.html_files/marktree.js @@ -0,0 +1,475 @@ +/* MarkTree JavaScript code + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * Miika Nurminen, 12.7.2004. + */ + +/* cross-browser (tested with ie5, mozilla 1 and opera 5) keypress detection */ +function get_keycode(evt) { + // IE + code = document.layers ? evt.which + : document.all ? event.keyCode // event.keyCode!=evt.keyCode! + : evt.keyCode; + + if (code==0) + code=evt.which; // for NS + return code; +} + +var lastnode=null; +var listnodes = null; +var list_index=1; +var lastnodetype=''; // determines if node is a link, input or text; + +// up, left, down, right, keypress codes +//ijkl +//var keys = new Array(105,106,107,108); +//num arrows +//var keys = new Array(56,52,50,54); +//wasd +// var press2 = new Array(119,97,115,100); + var press = new Array(47,45,42,43); + +// keydown codes + // var keys2=new Array(87,65,83,68); + var keys= new Array(38,37,40,39); + + // keyset 1 = keydown, otherwise press +function checkup(keyset,n) { + if (keyset==1) return (n==keys[0]); + return ((n==press[0]) /*|| (n==press2[0])*/) +} + +function checkdn(keyset,n) { + if (keyset==1) return (n==keys[2]); + return ((n==press[2]) /*|| (n==press2[2])*/) +} + +function checkl(keyset,n) { + if (keyset==1) return (n==keys[1]); + return ((n==press[1]) /*|| (n==press2[1])*/) +} + +function checkr(keyset,n) { + if (keyset==1) return (n==keys[3]); + return ((n==press[3]) /*|| (n==press2[3])*/) +} + + + + + +function is_exp(n) { + if (n==null) return false; + return ((n.className=='exp') || (n.className=='exp_active')); +} + +function is_col(n) { + if (n==null) return false; + return ((n.className=='col') || (n.className=='col_active')); +} + +function is_basic(n) { + if (n==null) return false; + return ((n.className=='basic') || (n.className=='basic_active')); +} + + + +/* returns i>=0 if true */ +function is_active(node) { + if (node.className==null) return false + return node.className.indexOf('_active'); +} + +function toggle_class(node) { + if ((node==null) || (node.className==null)) return; + str=node.className; + result=""; + i = str.indexOf('_active'); + if (i>0) + result= str.substr(0,i); + else + result= str+"_active"; + node.className=result; + return node; +} + +function activate(node) { + node.style.backgroundColor='#eeeeff'; +} + +function deactivate(node) { + node.style.backgroundColor='#ffffff'; +} + +function is_list_node(n) { + if (n==null) return false; + if (n.className==null) return false; + if ( (is_exp(n)) || + (is_col(n)) || + (is_basic(n)) ) + return true; else return false; +} + + +function get_href(n) { + alist=n.attributes; + if (alist!=null) { + hr = alist.getNamedItem('href'); + if (hr!=null) return hr.nodeValue; + } + if (n.childNodes.length==0) return ''; + for (var i=0; i<n.childNodes.length; i++) { + s = get_href(n.childNodes[i]); + if (s!='') return s; + } + return ''; +} + +function get_link(n) { + if (n==null) return null; + if (n.style==null) return null; + + // disabling uncontrolled recursion to prevent error messages on IE + // when trying to focus to invisible links (readonly mode) +// alert(n.nodeName+' '+n.className); + if ((n.nodeName=='UL') && (n.className=='sub')) return null; + + if (n.nodeName=='A') return n; + if (n.childNodes.length==0) return null; + for (var i=0; i<n.childNodes.length; i++) { + s = get_link(n.childNodes[i]); + if (s!=null) return s; + } + return null; +} + +function set_lastnode(n) { +/*var d = new Date(); +var t_mil = d.getMilliseconds();*/ +// testattu nopeuksia explorerilla, ei merkittäviä eroja + if (lastnode==n) return; +/* deactivate(lastnode) + lastnode=n; + activate(lastnode);*/ + + if (is_active(lastnode)>=0) + toggle_class(lastnode); + lastnode=n; + if (!(is_active(lastnode)>=0)) + toggle_class(lastnode); + + +/*var d2 = new Date(); +var t_mil2 = d2.getMilliseconds(); + window.alert(t_mil2-t_mil);*/ +} + +function next_list_node() { + tempIndex = list_index; + while (tempIndex<listnodes.length-1) { + tempIndex++; + var x = listnodes[tempIndex]; + if (is_list_node(x)) { + list_index=tempIndex; + return; + } + } +} + +function prev_list_node() { + tempIndex = list_index; + while (tempIndex>0) { + tempIndex--; + var x = listnodes[tempIndex]; + if (is_list_node(x)) { + list_index=tempIndex; + return; + } + } +} + + + +function getsub (li) { + if (li.childNodes.length==0) return null; + for (var c = 0; c < li.childNodes.length; c++) + if ( (li.childNodes[c].className == 'sub') || (li.childNodes[c].className == 'subexp') ) + return li.childNodes[c]; +} + +function find_listnode_recursive (li) { + if (is_list_node(li)) return li; + if (li.childNodes.length==0) return null; + result=null; + for (var c = 0; c < li.childNodes.length; c++) { + result=find_listnode_recursive(li.childNodes[c]); + if (result!=null) return result; + } + return null; +} + +function next_child_listnode(li) { + var result=null; + for (var i=0; i<li.childNodes.length; i++) { + result=find_listnode_recursive(li.childNodes[i]); + if (result!=null) return result; + } + return null; +} + +function next_actual_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + while (1) { + var n = temp.nextSibling; + if (n==null) { + n=parent_listnode(temp); + return next_actual_sibling_listnode(n); + } + if (is_list_node(n)) return n; + temp=n; + } +} + +function next_sibling_listnode(li) { +if (li==null) return null; + var result=null; + var temp=li; + if (is_col(temp)) return next_child_listnode(temp); + while (1) { + var n = temp.nextSibling; + if (n==null) { + n=parent_listnode(temp); + return next_actual_sibling_listnode(n); + } + if (is_list_node(n)) return n; + temp=n; + } +} + +function last_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + var last=null; + while(1) { + var n = temp.nextSibling; + if (is_list_node(temp)) + last = temp; + if (n==null) { + if (is_col(last)) return last_sibling_listnode(next_child_listnode(last)); + else return last; + } + temp = n; + } +} + +function prev_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + var n = null; + while (1) { + n = temp.previousSibling; + if (n==null) { + return parent_listnode(li); + } + if (is_list_node(n)) { + if (is_col(n)) { + return last_sibling_listnode(next_child_listnode(n)); + } + else { + return n; + } + } + temp=n; + } +} + + +function parent_listnode(li) { + // added 12.7.2004 to prevent IE error when readonly mode==true + if (li==null) return null; + n=li; + while (1) { + n=n.parentNode; + if (n==null) return null; + if (is_list_node(n)) return n; + } +} + +function getVisibleParents(id) { + var n = document.getElementById(id); + while(1) { + expand(n); + n = parent_listnode(n); + if (n==null) return; + } +} + +function onClickHandler (evt) { +if (lastnode==null) +{ +listnodes = document.getElementsByTagName('li'); +lastnode=listnodes[1]; +temp=listnodes[1]; +} + + + var target = evt ? evt.target : event.srcElement; + if (!is_list_node(target)) return; + toggle(target); + set_lastnode(target); +} + + +function expand(node) { + if (!is_exp(node)) return; + if (node.className=='exp_active') + node.className='col_active'; + else + node.className='col'; + setSubClass(node,'subexp'); + // getsub(node).className='subexp'; +} + +function collapse(node) { + if (!is_col(node)) return; + +if (node.className=='col_active') + node.className='exp_active' + else + node.className='exp'; + + setSubClass(node,'sub'); +// getsub(node).className='sub'; + +} + +function setSubClass(node,name) { + sub = getsub(node); + if (sub==null) return; + sub.className=name; +} + +function toggle(target) { + if (!is_list_node(target)) return; + if (is_col(target)) { + target.className='exp'; + setSubClass(target,'sub'); + // getsub(target).className='sub'; + } + else if (is_exp(target)) { + target.className='col'; + setSubClass(target,'subexp'); + // getsub(target).className='subexp'; + } + +} + +function expandAll(node) { + if (node.className=='exp') { + node.className='col'; + setSubClass(node,'subexp'); +// getsub(node).className='subexp'; + } + var i; + if (node.childNodes!=null) +// if (node.hasChildNodes()) + for ( i = 0; i<node.childNodes.length; i++) + expandAll(node.childNodes[i]); +} + +function collapseAll(node) { + if (node.className=='col') { + node.className='exp'; + setSubClass(node,'sub'); +// getsub(node).className='sub'; + } + var i; + if (node.childNodes!=null) +// for opera if (node.hasChildNodes()) + for ( i = 0; i<node.childNodes.length; i++) + collapseAll(node.childNodes[i]); +} + + + +function unFocus(node) { + // unfocuses potential link that is to be hidden (if a==null there is no link so it should not be blurred). + // tested with mozilla 1.7, 12.7.2004. /mn ( + intemp=parent_listnode(node); + a = get_link(intemp); // added 6.4. to get keyboard working with + // moved before collapse to prevent an error message with IE when readonly==true + if (a!=null) a.blur(); // netscape after collapsing a focused node + return intemp; +} + +// mode: 0==keypress, 1==keyup +function keyfunc(evt,mode) { + var c = get_keycode(evt); + var temp = null; + var a = null; + + if (lastnode==null) { + listnodes = document.getElementsByTagName('li'); + lastnode=listnodes[1]; + temp=listnodes[1]; + } + + //window.alert(c); + if (checkup(mode,c)) { // i + temp=prev_sibling_listnode(lastnode); + } + else if (checkdn(mode,c)) { // k + temp=next_sibling_listnode(lastnode); + } + else if (checkr(mode,c)) { // l + expand(lastnode); + // temp=next_child_listnode(lastnode); + // if (temp==null) { + a = get_link(lastnode); + if (a!=null) a.focus(); else self.focus(); + //} + } + else if (checkl(mode,c)) { // j + if (is_col(lastnode)) { + unFocus(lastnode); + collapse(lastnode); + } + else { + temp=unFocus(lastnode); + collapse(temp); + } + // if (temp==null) lastnode.focus(); // forces focus to correct div (try mozilla typesearch) (doesn't seem to work -mn/6.4.2004) + } + else return; + if (temp!=null) set_lastnode(temp); + + // alert('pressed ' + String.fromCharCode(c) + '(' + c + ')'); + return true; +} + + +function keytest (evt) { + return keyfunc(evt,1); +}; + + +function presstest (evt) { + return keyfunc(evt,0); +}; + + + document.onclick = onClickHandler; + document.onkeypress = presstest; + document.onkeyup = keytest; diff --git a/ssm2010_first_panel.html_files/minus.png b/ssm2010_first_panel.html_files/minus.png new file mode 100644 index 0000000..4956850 Binary files /dev/null and b/ssm2010_first_panel.html_files/minus.png differ diff --git a/ssm2010_first_panel.html_files/plus.png b/ssm2010_first_panel.html_files/plus.png new file mode 100644 index 0000000..e09ee95 Binary files /dev/null and b/ssm2010_first_panel.html_files/plus.png differ diff --git a/ssm2010_first_panel.html_files/treestyles.css b/ssm2010_first_panel.html_files/treestyles.css new file mode 100644 index 0000000..aecb6e1 --- /dev/null +++ b/ssm2010_first_panel.html_files/treestyles.css @@ -0,0 +1,161 @@ + +body { + background-color: #eeeeee; + color: #000000; + font-family:sans-serif; +} + +:link { color: #0000ff; text-decoration:none;} +:visited { color: #6666ff; text-decoration:none; } +a:active { color: #0000ff; text-decoration:none;} +a:hover {color: #0000ff; text-decoration:underline; } + +div.basetext { + background-color:#ffffff; + margin-top:11px; + margin-bottom:11px; + margin-left:1%; + margin-right:1%; + padding-top:11px; + padding-left:11px; + padding-right:11px; + padding-bottom:11px; + text-align:left; + font-weight:normal; + border-width:thin; + border-style:solid; + border-color:#dddddd; +} + +div.basetop { + position: fixed; + width:auto; + height:auto; + right:0em; + top:0em; + left:auto; + top:0; + background-color:#ffffff; + margin-top:0; + margin-bottom:0; + margin-left:1%; + margin-right:1%; + padding-top:2px; + padding-left:11px; + padding-right:11px; + padding-bottom:2px; + text-align:left; + font-weight:normal; +text-align:right; + border-width:thin; + border-style:solid; + border-color:#dddddd; +} + +h1 { + text-align:center; +} + +span.h2 { + font-family:sans-serif; + font-weight:bold; +} + +div.year { + margin-right:2%; + background-color:#eeeeee; +} + +div.form { +} + +span.cpt { + color:#005500; + font-weight:bold; +} + +span.cm { + color:#666666; +} + +.fl { + color:#0000FF; + font-style:italic; +} + +ul { + margin-top:1px; + margin-bottom:1px; + margin-left:0px; + padding-left:3%; +} + +li { + list-style:outside; + margin-top:10px; + margin-bottom:10px; +} + +ul li { + list-style:square; + font-family:sans-serif; + font-weight:normal; +} + +li.basic { + list-style:square; + list-style-image:none; + margin-top:2px; + margin-bottom:2px; +} + +span.links { +} + + + + +.sub { display: none; } +.subexp {display: block; } +.sub { display: none; } + +.subexp {display: block; } + +li.exp { + list-style-image:url("plus.png"); + margin-top:10px; + margin-bottom:10px; + cursor:pointer; +} + +li.col { + list-style-image:url("minus.png"); + margin-top:10px; + margin-bottom:10px; + cursor:pointer; +} + +li.exp_active { + list-style-image:url("plus.png"); + margin-top:10px; + margin-bottom:10px; + background-color:#eeeeff; + cursor:pointer; +} + +li.col_active { + list-style-image:url("minus.png"); + margin-top:10px; + margin-bottom:10px; + background-color:#eeeeff; + cursor:pointer; /* if not included, bullets are not shown right in moz*/ +} + + +li.basic_active { + list-style:square; + list-style-image:none; + background-color:#eeeeff; + margin-top:2px; + margin-bottom:2px; +} diff --git a/ssm2010_second_panel.html b/ssm2010_second_panel.html new file mode 100644 index 0000000..0e44223 --- /dev/null +++ b/ssm2010_second_panel.html @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="iso-8859-1"?><?xml-stylesheet href="treestyles.css" type="text/css"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> +<html xml:lang="fi" xmlns="http://www.w3.org/1999/xhtml"><head><title> #ssm2010 second panel</title><link rel="stylesheet" href="ssm2010_second_panel.html_files/treestyles.css" type="text/css"/><script type="text/javascript" src="ssm2010_second_panel.html_files/marktree.js">  </script></head><body><div class="basetop"><a href="#" onclick="expandAll(document.getElementById('base'))">Expand</a> - <a href="#" onclick="collapseAll(document.getElementById('base'))">Collapse</a></div><div id="base" class="basetext"><ul><li class="col" style="" id="FMFreemind_Link_609047317FM"><span style=""> #ssm2010 second panel</span><ul class="subexp"><li class="exp" style="" id="FMFreemind_Link_1101727269FM"><span style="">People</span><ul class="sub"><li class="basic" style=""><span style="">David Hendi, MySpace</span></li><li class="basic" style=""><span style="">Hilary Mason, bit.ly</span></li><li class="basic" style="" id="FMFreemind_Link_405799441FM"><span style="">Igor Perisic, LinkedIn</span></li></ul></li><li class="exp" style="" id="FM_FM"><span style="">Companies</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1762556587FM"><span style="">MySpace</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1816861261FM"><span style="">HCIR_GeneG #ssm2010 David Hendi (myspace): People want to see what are up to</span></li><li class="basic" style="" id="FMFreemind_Link_1410070725FM"><span style="">HCIR_GeneG #ssm2010 hendi: both search and browsing</span></li><li class="basic" style="" id="FMFreemind_Link_750155603FM"><span style="">HCIR_GeneG #ssm2010 hendi without social graph, cannot do anything.</span></li><li class="basic" style="" id="FMFreemind_Link_1115270761FM"><span style="">HCIR_GeneG: #ssm2010 hendi: myspace has dashboard to show users to see who is interacting with them</span></li><li class="col" style="" id="FMFreemind_Link_808054147FM"><span style="">Graph public?</span><ul class="subexp"><li class="basic" style="" id="FMFreemind_Link_1594395103FM"><span style="">HCIR_GeneG: #ssm2010 hendi myspace would like others to build on top of their data.</span></li></ul></li><li class="basic" style="" id="FMFreemind_Link_825782212FM"><span style="">HCIR_GeneG: #ssm2010 hendi MySpace user base has changed a lot over last few years; goal to figure out what they want. Always a catchup game.</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_618107527FM"><span style="">Bit.ly</span><ul class="sub"><li class="basic" style=""><span style="">HCIR_GeneG #ssm2010 mason: bit.ly analytics/data are public</span></li><li class="basic" style=""><span style="">HCIR_GeneG #ssm2010 mason: bit.ly spends lots of resources detecting spam</span></li><li class="basic" style=""><span style="">HCIR_GeneG #ssm2010 mason: half the clicks on a link occur within ten minutes of it being shared</span></li><li class="basic" style=""><span style="">nitya #ssm2010 half-life of a new bit.ly link is 10 minutes</span></li><li class="basic" style=""><span style=""><a href="http://bitly.tv">HCIR_GeneG #ssm2010 mason: http://bitly.tv what are the cool videos on the net right now?</a> <a href="http://bitly.tv"><img src="ssm2010_second_panel.html_files/icons/Link.png" alt="" style="border-width:0"/></a></span></li><li class="basic" style="" id="FMFreemind_Link_643726124FM"><span style="">HCIR_GeneG: #ssm2010 mason: bit.ly will release history search soon; encourages people to build on their APIs</span></li><li class="basic" style="" id="FMFreemind_Link_1277341994FM"><span style="">HCIR_GeneG: #ssm2010 @matthewhurst bit.ly could focus on brand, not just social search</span></li><li class="basic" style="" id="FMFreemind_Link_1994341444FM"><span style="">#ssm2010 mason: will offer service to publishers, brand-conscious customers soon</span></li><li class="col" style="" id="FMFreemind_Link_1271100791FM"><span style="">Structure of links</span><ul class="subexp"><li class="basic" style=""><span style="">HCIR_GeneG: #ssm2010 mason: 27% of links on tech; 0.03% on weather</span></li></ul></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1025381078FM"><span style="">LinkedIn</span><ul class="sub"><li class="exp" style="" id="FMFreemind_Link_1672673668FM"><span style="">Search what</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_498983571FM"><span style="">HCIR_GeneG #ssm2010 Igor Perisic (LinkedIn): search for people, companies, jobs, discussions, etc. People search is most dominant.</span></li><li class="basic" style="" id="FMFreemind_Link_939841425FM"><span style="">HCIR_GeneG #ssm2010 Perisic: search in linkedin is intrinsically personal, hard to define relevance</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_1332075582FM"><span style="">Graph partitioning</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_784537038FM"><span style="">[re: graph partitioning] HCIR_GeneG: #ssm2010 perisic: we use distributed hash as part of the solution. Don't know the full answer yet! Check back in 8 months</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_654854464FM"><span style="">Revenue</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_522227595FM"><span style="">HCIR_GeneG: #ssm2010 perisic: one of the revenue streams is subscriptions. "Who viewed my job?" has value. Am I targeting the right people?</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_706686321FM"><span style="">Friend suggest</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1753230301FM"><span style="">No commets</span></li></ul></li><li class="exp" style="" id="FMFreemind_Link_466314224FM"><span style="">How much of the graph is public</span><ul class="sub"><li class="basic" style="" id="FMFreemind_Link_1899665356FM"><span style="">HCIR_GeneG: #ssm2010 perisic: would not give up the graph, but your profile is public. How much should be in public vs. private profile?</span></li></ul></li></ul></li></ul></li></ul></li></ul></div></body></html> \ No newline at end of file diff --git a/ssm2010_second_panel.html_files/icons/Mail.png b/ssm2010_second_panel.html_files/icons/Mail.png new file mode 100644 index 0000000..beea00e Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/Mail.png differ diff --git a/ssm2010_second_panel.html_files/icons/attach.png b/ssm2010_second_panel.html_files/icons/attach.png new file mode 100644 index 0000000..b03a77e Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/attach.png differ diff --git a/ssm2010_second_panel.html_files/icons/back.png b/ssm2010_second_panel.html_files/icons/back.png new file mode 100644 index 0000000..5a86cd8 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/back.png differ diff --git a/ssm2010_second_panel.html_files/icons/bell.png b/ssm2010_second_panel.html_files/icons/bell.png new file mode 100644 index 0000000..8afab9d Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/bell.png differ diff --git a/ssm2010_second_panel.html_files/icons/bookmark.png b/ssm2010_second_panel.html_files/icons/bookmark.png new file mode 100644 index 0000000..67f1832 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/bookmark.png differ diff --git a/ssm2010_second_panel.html_files/icons/button_cancel.png b/ssm2010_second_panel.html_files/icons/button_cancel.png new file mode 100644 index 0000000..a9c624a Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/button_cancel.png differ diff --git a/ssm2010_second_panel.html_files/icons/button_ok.png b/ssm2010_second_panel.html_files/icons/button_ok.png new file mode 100644 index 0000000..9a817fd Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/button_ok.png differ diff --git a/ssm2010_second_panel.html_files/icons/clanbomber.png b/ssm2010_second_panel.html_files/icons/clanbomber.png new file mode 100644 index 0000000..16679ba Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/clanbomber.png differ diff --git a/ssm2010_second_panel.html_files/icons/desktop_new.png b/ssm2010_second_panel.html_files/icons/desktop_new.png new file mode 100644 index 0000000..366368f Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/desktop_new.png differ diff --git a/ssm2010_second_panel.html_files/icons/flag.png b/ssm2010_second_panel.html_files/icons/flag.png new file mode 100644 index 0000000..e9defd1 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/flag.png differ diff --git a/ssm2010_second_panel.html_files/icons/forward.png b/ssm2010_second_panel.html_files/icons/forward.png new file mode 100644 index 0000000..b80d28a Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/forward.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-1.png b/ssm2010_second_panel.html_files/icons/full-1.png new file mode 100644 index 0000000..80a6c66 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-1.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-2.png b/ssm2010_second_panel.html_files/icons/full-2.png new file mode 100644 index 0000000..bc26aef Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-2.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-3.png b/ssm2010_second_panel.html_files/icons/full-3.png new file mode 100644 index 0000000..e419464 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-3.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-4.png b/ssm2010_second_panel.html_files/icons/full-4.png new file mode 100644 index 0000000..d82ee2f Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-4.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-5.png b/ssm2010_second_panel.html_files/icons/full-5.png new file mode 100644 index 0000000..2860401 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-5.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-6.png b/ssm2010_second_panel.html_files/icons/full-6.png new file mode 100644 index 0000000..10ef02a Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-6.png differ diff --git a/ssm2010_second_panel.html_files/icons/full-7.png b/ssm2010_second_panel.html_files/icons/full-7.png new file mode 100644 index 0000000..e55f3ff Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/full-7.png differ diff --git a/ssm2010_second_panel.html_files/icons/gohome.png b/ssm2010_second_panel.html_files/icons/gohome.png new file mode 100644 index 0000000..17bf02f Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/gohome.png differ diff --git a/ssm2010_second_panel.html_files/icons/help.png b/ssm2010_second_panel.html_files/icons/help.png new file mode 100644 index 0000000..d6391a2 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/help.png differ diff --git a/ssm2010_second_panel.html_files/icons/idea.png b/ssm2010_second_panel.html_files/icons/idea.png new file mode 100644 index 0000000..8d18b02 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/idea.png differ diff --git a/ssm2010_second_panel.html_files/icons/kaddressbook.png b/ssm2010_second_panel.html_files/icons/kaddressbook.png new file mode 100644 index 0000000..8bfe4ae Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/kaddressbook.png differ diff --git a/ssm2010_second_panel.html_files/icons/knotify.png b/ssm2010_second_panel.html_files/icons/knotify.png new file mode 100644 index 0000000..0104e72 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/knotify.png differ diff --git a/ssm2010_second_panel.html_files/icons/korn.png b/ssm2010_second_panel.html_files/icons/korn.png new file mode 100644 index 0000000..a4e9107 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/korn.png differ diff --git a/ssm2010_second_panel.html_files/icons/ksmiletris.png b/ssm2010_second_panel.html_files/icons/ksmiletris.png new file mode 100644 index 0000000..b95f903 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/ksmiletris.png differ diff --git a/ssm2010_second_panel.html_files/icons/licq.png b/ssm2010_second_panel.html_files/icons/licq.png new file mode 100644 index 0000000..34f8cce Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/licq.png differ diff --git a/ssm2010_second_panel.html_files/icons/messagebox_warning.png b/ssm2010_second_panel.html_files/icons/messagebox_warning.png new file mode 100644 index 0000000..afc9c9c Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/messagebox_warning.png differ diff --git a/ssm2010_second_panel.html_files/icons/password.png b/ssm2010_second_panel.html_files/icons/password.png new file mode 100644 index 0000000..5e86bbb Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/password.png differ diff --git a/ssm2010_second_panel.html_files/icons/pencil.png b/ssm2010_second_panel.html_files/icons/pencil.png new file mode 100644 index 0000000..575dd32 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/pencil.png differ diff --git a/ssm2010_second_panel.html_files/icons/penguin.png b/ssm2010_second_panel.html_files/icons/penguin.png new file mode 100644 index 0000000..0f61ec5 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/penguin.png differ diff --git a/ssm2010_second_panel.html_files/icons/stop.png b/ssm2010_second_panel.html_files/icons/stop.png new file mode 100644 index 0000000..981c4cf Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/stop.png differ diff --git a/ssm2010_second_panel.html_files/icons/wizard.png b/ssm2010_second_panel.html_files/icons/wizard.png new file mode 100644 index 0000000..93a1d91 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/wizard.png differ diff --git a/ssm2010_second_panel.html_files/icons/xmag.png b/ssm2010_second_panel.html_files/icons/xmag.png new file mode 100644 index 0000000..32a4a15 Binary files /dev/null and b/ssm2010_second_panel.html_files/icons/xmag.png differ diff --git a/ssm2010_second_panel.html_files/marktree.js b/ssm2010_second_panel.html_files/marktree.js new file mode 100644 index 0000000..10bba60 --- /dev/null +++ b/ssm2010_second_panel.html_files/marktree.js @@ -0,0 +1,475 @@ +/* MarkTree JavaScript code + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * Miika Nurminen, 12.7.2004. + */ + +/* cross-browser (tested with ie5, mozilla 1 and opera 5) keypress detection */ +function get_keycode(evt) { + // IE + code = document.layers ? evt.which + : document.all ? event.keyCode // event.keyCode!=evt.keyCode! + : evt.keyCode; + + if (code==0) + code=evt.which; // for NS + return code; +} + +var lastnode=null; +var listnodes = null; +var list_index=1; +var lastnodetype=''; // determines if node is a link, input or text; + +// up, left, down, right, keypress codes +//ijkl +//var keys = new Array(105,106,107,108); +//num arrows +//var keys = new Array(56,52,50,54); +//wasd +// var press2 = new Array(119,97,115,100); + var press = new Array(47,45,42,43); + +// keydown codes + // var keys2=new Array(87,65,83,68); + var keys= new Array(38,37,40,39); + + // keyset 1 = keydown, otherwise press +function checkup(keyset,n) { + if (keyset==1) return (n==keys[0]); + return ((n==press[0]) /*|| (n==press2[0])*/) +} + +function checkdn(keyset,n) { + if (keyset==1) return (n==keys[2]); + return ((n==press[2]) /*|| (n==press2[2])*/) +} + +function checkl(keyset,n) { + if (keyset==1) return (n==keys[1]); + return ((n==press[1]) /*|| (n==press2[1])*/) +} + +function checkr(keyset,n) { + if (keyset==1) return (n==keys[3]); + return ((n==press[3]) /*|| (n==press2[3])*/) +} + + + + + +function is_exp(n) { + if (n==null) return false; + return ((n.className=='exp') || (n.className=='exp_active')); +} + +function is_col(n) { + if (n==null) return false; + return ((n.className=='col') || (n.className=='col_active')); +} + +function is_basic(n) { + if (n==null) return false; + return ((n.className=='basic') || (n.className=='basic_active')); +} + + + +/* returns i>=0 if true */ +function is_active(node) { + if (node.className==null) return false + return node.className.indexOf('_active'); +} + +function toggle_class(node) { + if ((node==null) || (node.className==null)) return; + str=node.className; + result=""; + i = str.indexOf('_active'); + if (i>0) + result= str.substr(0,i); + else + result= str+"_active"; + node.className=result; + return node; +} + +function activate(node) { + node.style.backgroundColor='#eeeeff'; +} + +function deactivate(node) { + node.style.backgroundColor='#ffffff'; +} + +function is_list_node(n) { + if (n==null) return false; + if (n.className==null) return false; + if ( (is_exp(n)) || + (is_col(n)) || + (is_basic(n)) ) + return true; else return false; +} + + +function get_href(n) { + alist=n.attributes; + if (alist!=null) { + hr = alist.getNamedItem('href'); + if (hr!=null) return hr.nodeValue; + } + if (n.childNodes.length==0) return ''; + for (var i=0; i<n.childNodes.length; i++) { + s = get_href(n.childNodes[i]); + if (s!='') return s; + } + return ''; +} + +function get_link(n) { + if (n==null) return null; + if (n.style==null) return null; + + // disabling uncontrolled recursion to prevent error messages on IE + // when trying to focus to invisible links (readonly mode) +// alert(n.nodeName+' '+n.className); + if ((n.nodeName=='UL') && (n.className=='sub')) return null; + + if (n.nodeName=='A') return n; + if (n.childNodes.length==0) return null; + for (var i=0; i<n.childNodes.length; i++) { + s = get_link(n.childNodes[i]); + if (s!=null) return s; + } + return null; +} + +function set_lastnode(n) { +/*var d = new Date(); +var t_mil = d.getMilliseconds();*/ +// testattu nopeuksia explorerilla, ei merkittäviä eroja + if (lastnode==n) return; +/* deactivate(lastnode) + lastnode=n; + activate(lastnode);*/ + + if (is_active(lastnode)>=0) + toggle_class(lastnode); + lastnode=n; + if (!(is_active(lastnode)>=0)) + toggle_class(lastnode); + + +/*var d2 = new Date(); +var t_mil2 = d2.getMilliseconds(); + window.alert(t_mil2-t_mil);*/ +} + +function next_list_node() { + tempIndex = list_index; + while (tempIndex<listnodes.length-1) { + tempIndex++; + var x = listnodes[tempIndex]; + if (is_list_node(x)) { + list_index=tempIndex; + return; + } + } +} + +function prev_list_node() { + tempIndex = list_index; + while (tempIndex>0) { + tempIndex--; + var x = listnodes[tempIndex]; + if (is_list_node(x)) { + list_index=tempIndex; + return; + } + } +} + + + +function getsub (li) { + if (li.childNodes.length==0) return null; + for (var c = 0; c < li.childNodes.length; c++) + if ( (li.childNodes[c].className == 'sub') || (li.childNodes[c].className == 'subexp') ) + return li.childNodes[c]; +} + +function find_listnode_recursive (li) { + if (is_list_node(li)) return li; + if (li.childNodes.length==0) return null; + result=null; + for (var c = 0; c < li.childNodes.length; c++) { + result=find_listnode_recursive(li.childNodes[c]); + if (result!=null) return result; + } + return null; +} + +function next_child_listnode(li) { + var result=null; + for (var i=0; i<li.childNodes.length; i++) { + result=find_listnode_recursive(li.childNodes[i]); + if (result!=null) return result; + } + return null; +} + +function next_actual_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + while (1) { + var n = temp.nextSibling; + if (n==null) { + n=parent_listnode(temp); + return next_actual_sibling_listnode(n); + } + if (is_list_node(n)) return n; + temp=n; + } +} + +function next_sibling_listnode(li) { +if (li==null) return null; + var result=null; + var temp=li; + if (is_col(temp)) return next_child_listnode(temp); + while (1) { + var n = temp.nextSibling; + if (n==null) { + n=parent_listnode(temp); + return next_actual_sibling_listnode(n); + } + if (is_list_node(n)) return n; + temp=n; + } +} + +function last_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + var last=null; + while(1) { + var n = temp.nextSibling; + if (is_list_node(temp)) + last = temp; + if (n==null) { + if (is_col(last)) return last_sibling_listnode(next_child_listnode(last)); + else return last; + } + temp = n; + } +} + +function prev_sibling_listnode(li) { + if (li==null) return null; + var temp=li; + var n = null; + while (1) { + n = temp.previousSibling; + if (n==null) { + return parent_listnode(li); + } + if (is_list_node(n)) { + if (is_col(n)) { + return last_sibling_listnode(next_child_listnode(n)); + } + else { + return n; + } + } + temp=n; + } +} + + +function parent_listnode(li) { + // added 12.7.2004 to prevent IE error when readonly mode==true + if (li==null) return null; + n=li; + while (1) { + n=n.parentNode; + if (n==null) return null; + if (is_list_node(n)) return n; + } +} + +function getVisibleParents(id) { + var n = document.getElementById(id); + while(1) { + expand(n); + n = parent_listnode(n); + if (n==null) return; + } +} + +function onClickHandler (evt) { +if (lastnode==null) +{ +listnodes = document.getElementsByTagName('li'); +lastnode=listnodes[1]; +temp=listnodes[1]; +} + + + var target = evt ? evt.target : event.srcElement; + if (!is_list_node(target)) return; + toggle(target); + set_lastnode(target); +} + + +function expand(node) { + if (!is_exp(node)) return; + if (node.className=='exp_active') + node.className='col_active'; + else + node.className='col'; + setSubClass(node,'subexp'); + // getsub(node).className='subexp'; +} + +function collapse(node) { + if (!is_col(node)) return; + +if (node.className=='col_active') + node.className='exp_active' + else + node.className='exp'; + + setSubClass(node,'sub'); +// getsub(node).className='sub'; + +} + +function setSubClass(node,name) { + sub = getsub(node); + if (sub==null) return; + sub.className=name; +} + +function toggle(target) { + if (!is_list_node(target)) return; + if (is_col(target)) { + target.className='exp'; + setSubClass(target,'sub'); + // getsub(target).className='sub'; + } + else if (is_exp(target)) { + target.className='col'; + setSubClass(target,'subexp'); + // getsub(target).className='subexp'; + } + +} + +function expandAll(node) { + if (node.className=='exp') { + node.className='col'; + setSubClass(node,'subexp'); +// getsub(node).className='subexp'; + } + var i; + if (node.childNodes!=null) +// if (node.hasChildNodes()) + for ( i = 0; i<node.childNodes.length; i++) + expandAll(node.childNodes[i]); +} + +function collapseAll(node) { + if (node.className=='col') { + node.className='exp'; + setSubClass(node,'sub'); +// getsub(node).className='sub'; + } + var i; + if (node.childNodes!=null) +// for opera if (node.hasChildNodes()) + for ( i = 0; i<node.childNodes.length; i++) + collapseAll(node.childNodes[i]); +} + + + +function unFocus(node) { + // unfocuses potential link that is to be hidden (if a==null there is no link so it should not be blurred). + // tested with mozilla 1.7, 12.7.2004. /mn ( + intemp=parent_listnode(node); + a = get_link(intemp); // added 6.4. to get keyboard working with + // moved before collapse to prevent an error message with IE when readonly==true + if (a!=null) a.blur(); // netscape after collapsing a focused node + return intemp; +} + +// mode: 0==keypress, 1==keyup +function keyfunc(evt,mode) { + var c = get_keycode(evt); + var temp = null; + var a = null; + + if (lastnode==null) { + listnodes = document.getElementsByTagName('li'); + lastnode=listnodes[1]; + temp=listnodes[1]; + } + + //window.alert(c); + if (checkup(mode,c)) { // i + temp=prev_sibling_listnode(lastnode); + } + else if (checkdn(mode,c)) { // k + temp=next_sibling_listnode(lastnode); + } + else if (checkr(mode,c)) { // l + expand(lastnode); + // temp=next_child_listnode(lastnode); + // if (temp==null) { + a = get_link(lastnode); + if (a!=null) a.focus(); else self.focus(); + //} + } + else if (checkl(mode,c)) { // j + if (is_col(lastnode)) { + unFocus(lastnode); + collapse(lastnode); + } + else { + temp=unFocus(lastnode); + collapse(temp); + } + // if (temp==null) lastnode.focus(); // forces focus to correct div (try mozilla typesearch) (doesn't seem to work -mn/6.4.2004) + } + else return; + if (temp!=null) set_lastnode(temp); + + // alert('pressed ' + String.fromCharCode(c) + '(' + c + ')'); + return true; +} + + +function keytest (evt) { + return keyfunc(evt,1); +}; + + +function presstest (evt) { + return keyfunc(evt,0); +}; + + + document.onclick = onClickHandler; + document.onkeypress = presstest; + document.onkeyup = keytest; diff --git a/ssm2010_second_panel.html_files/minus.png b/ssm2010_second_panel.html_files/minus.png new file mode 100644 index 0000000..4956850 Binary files /dev/null and b/ssm2010_second_panel.html_files/minus.png differ diff --git a/ssm2010_second_panel.html_files/plus.png b/ssm2010_second_panel.html_files/plus.png new file mode 100644 index 0000000..e09ee95 Binary files /dev/null and b/ssm2010_second_panel.html_files/plus.png differ diff --git a/ssm2010_second_panel.html_files/treestyles.css b/ssm2010_second_panel.html_files/treestyles.css new file mode 100644 index 0000000..aecb6e1 --- /dev/null +++ b/ssm2010_second_panel.html_files/treestyles.css @@ -0,0 +1,161 @@ + +body { + background-color: #eeeeee; + color: #000000; + font-family:sans-serif; +} + +:link { color: #0000ff; text-decoration:none;} +:visited { color: #6666ff; text-decoration:none; } +a:active { color: #0000ff; text-decoration:none;} +a:hover {color: #0000ff; text-decoration:underline; } + +div.basetext { + background-color:#ffffff; + margin-top:11px; + margin-bottom:11px; + margin-left:1%; + margin-right:1%; + padding-top:11px; + padding-left:11px; + padding-right:11px; + padding-bottom:11px; + text-align:left; + font-weight:normal; + border-width:thin; + border-style:solid; + border-color:#dddddd; +} + +div.basetop { + position: fixed; + width:auto; + height:auto; + right:0em; + top:0em; + left:auto; + top:0; + background-color:#ffffff; + margin-top:0; + margin-bottom:0; + margin-left:1%; + margin-right:1%; + padding-top:2px; + padding-left:11px; + padding-right:11px; + padding-bottom:2px; + text-align:left; + font-weight:normal; +text-align:right; + border-width:thin; + border-style:solid; + border-color:#dddddd; +} + +h1 { + text-align:center; +} + +span.h2 { + font-family:sans-serif; + font-weight:bold; +} + +div.year { + margin-right:2%; + background-color:#eeeeee; +} + +div.form { +} + +span.cpt { + color:#005500; + font-weight:bold; +} + +span.cm { + color:#666666; +} + +.fl { + color:#0000FF; + font-style:italic; +} + +ul { + margin-top:1px; + margin-bottom:1px; + margin-left:0px; + padding-left:3%; +} + +li { + list-style:outside; + margin-top:10px; + margin-bottom:10px; +} + +ul li { + list-style:square; + font-family:sans-serif; + font-weight:normal; +} + +li.basic { + list-style:square; + list-style-image:none; + margin-top:2px; + margin-bottom:2px; +} + +span.links { +} + + + + +.sub { display: none; } +.subexp {display: block; } +.sub { display: none; } + +.subexp {display: block; } + +li.exp { + list-style-image:url("plus.png"); + margin-top:10px; + margin-bottom:10px; + cursor:pointer; +} + +li.col { + list-style-image:url("minus.png"); + margin-top:10px; + margin-bottom:10px; + cursor:pointer; +} + +li.exp_active { + list-style-image:url("plus.png"); + margin-top:10px; + margin-bottom:10px; + background-color:#eeeeff; + cursor:pointer; +} + +li.col_active { + list-style-image:url("minus.png"); + margin-top:10px; + margin-bottom:10px; + background-color:#eeeeff; + cursor:pointer; /* if not included, bullets are not shown right in moz*/ +} + + +li.basic_active { + list-style:square; + list-style-image:none; + background-color:#eeeeff; + margin-top:2px; + margin-bottom:2px; +}
dudarev/ssm2010
d87dbe88e3731fa2cec81ea00b481937de8805ae
started index in reStructuredText format, added freemind files for two sections
diff --git a/.gitignore b/.gitignore index 1377554..02fcfa8 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.swp +tmp.html diff --git a/index.html b/index.html index bb651f7..c238678 100644 --- a/index.html +++ b/index.html @@ -1,61 +1,76 @@ <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>dudarev/ssm2010 @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: #fff; font-family: "Helvetica,Arial,FreeSans"; color: #000000; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; } h1 .small { font-size: 0.4em; } h1 a { text-decoration: none } h2 { font-size: 1.5em; color: #000000; } h3 { text-align: center; color: #000000; } a { color: #000000; } .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> <div id="container"> <h1><a href="http://github.com/dudarev/ssm2010">ssm2010</a> </h1> <div class="description"> My notes on tweets related to Search in Social Media 2010 workshop - </div> + </div> + + + +<div class="section"> +<h2><a id="about-ssm2010" name="about-ssm2010">About SSM2010</a></h2> +<p>The Third Annual Workshop on Search in Social Media (SSM 2010) took place.</p> +</div> +<div class="section"> +<h2><a id="notes" name="notes">Notes</a></h2> +<dl class="docutils"> +<dt>In FreeMind format:</dt> +<dd><ul class="first last simple"> +<li><a class="reference" href="ssm2010_first_panel.mm">First panel</a></li> +<li><a class="reference" href="ssm2010_second_panel.mm">Second panel</a></li> +</ul> +</dd> +</dl> +</div> + - <h2>About SSM2010</h2> - <p>The Third Annual Workshop on Search in Social Media (SSM 2010) took place.</p> - <h2>Notes</h2> - <p>In FreeMind format.</p> <div class="footer"> this page is hosted on github : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> </div> </div> </body> </html> diff --git a/index.rst b/index.rst new file mode 100644 index 0000000..7f0df63 --- /dev/null +++ b/index.rst @@ -0,0 +1,19 @@ +SSM2010 +======= + +SSM2010 +======= + + + +About SSM2010 +-------------- + +The Third Annual Workshop on Search in Social Media (SSM 2010) took place. + +Notes +------ + +In FreeMind format: + - `First panel <ssm2010_first_panel.mm>`__ + - `Second panel <ssm2010_second_panel.mm>`__ diff --git a/ssm2010_first_panel.mm b/ssm2010_first_panel.mm new file mode 100644 index 0000000..724fdbe --- /dev/null +++ b/ssm2010_first_panel.mm @@ -0,0 +1,88 @@ +<map version="0.8.1"> +<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net --> +<node CREATED="1265214699583" ID="Freemind_Link_180953392" MODIFIED="1265214706260" TEXT="#ssm2010"> +<node CREATED="1265214732687" ID="_" MODIFIED="1265214737674" POSITION="right" TEXT="Companies"> +<node CREATED="1265214740449" FOLDED="true" ID="Freemind_Link_1878883213" MODIFIED="1265214742898" TEXT="Baidu"> +<node CREATED="1265214794892" FOLDED="true" ID="Freemind_Link_1434796548" MODIFIED="1265214803488" TEXT="TaoBao"> +<node CREATED="1265214745826" ID="Freemind_Link_1758601062" MODIFIED="1265214777185" TEXT="jny2: William Chang of Baidu: China&apos;s version of eBay--called TaoBao--is 1% or 2% percent of GDP. OMG, did I just hear that correctly?! #ssm2010"/> +<node CREATED="1265214833618" ID="Freemind_Link_1105832984" MODIFIED="1265214858119" TEXT="Search is bad but they do (decent) recommendations @nitya"/> +</node> +<node CREATED="1265214976369" ID="Freemind_Link_544851444" MODIFIED="1265214979973" TEXT="forum search"/> +<node CREATED="1265219468608" ID="Freemind_Link_881033084" MODIFIED="1265219471405" TEXT="Observations"> +<node CREATED="1265219472402" ID="Freemind_Link_450105447" MODIFIED="1265219474809" TEXT="HCIR_GeneG: #ssm2010 google delivers baidu content in China"/> +</node> +</node> +<node CREATED="1265215093471" ID="Freemind_Link_423627865" MODIFIED="1265215096973" TEXT="Yahoo"> +<node CREATED="1265215102643" ID="Freemind_Link_737877236" MODIFIED="1265215104466" TEXT="HCIR_GeneG: #ssm2010 Amer-Yahia: in travel , most queries are tag-browsing, not text-typing"/> +<node CREATED="1265220240503" ID="Freemind_Link_1680587614" LINK="#Freemind_Link_813826843" MODIFIED="1265220294647" TEXT="Yahoo Answers"/> +</node> +<node CREATED="1265215506919" FOLDED="true" ID="Freemind_Link_709914783" MODIFIED="1265215509672" TEXT="Microsoft"> +<node CREATED="1265215525532" ID="Freemind_Link_625324909" MODIFIED="1265215528540" TEXT="Bing Local"> +<node CREATED="1265215511471" ID="Freemind_Link_1917644998" MODIFIED="1265215513529" TEXT="ian_soboroff: #ssm2010 bing local lens - surfacing hyperlocal content"/> +<node CREATED="1265215551269" ID="Freemind_Link_769522831" MODIFIED="1265215552739" TEXT="HCIR_GeneG: #ssm2010 Hurst: local lens: crawing and minig hyper-local blog content"/> +</node> +</node> +<node CREATED="1265215835305" FOLDED="true" ID="Freemind_Link_189590157" MODIFIED="1265215837376" TEXT="Google"> +<node CREATED="1265215839691" FOLDED="true" ID="Freemind_Link_1427352657" MODIFIED="1265215847245" TEXT="Relevance of Social Search"> +<node CREATED="1265215848650" ID="Freemind_Link_1287322606" MODIFIED="1265215850326" TEXT="HCIR_GeneG: #ssm2010 a q: has google social search been evaluated for relevance?"/> +</node> +</node> +<node CREATED="1265219857365" ID="Freemind_Link_723806724" MODIFIED="1265219859169" TEXT="Naver"> +<node CREATED="1265219876872" ID="Freemind_Link_183951216" MODIFIED="1265219878479" TEXT="nitya: #ssm2010 naver has branded advertising mixed in with search results (how naver makes portal work)"/> +<node CREATED="1265219910384" ID="Freemind_Link_813826843" MODIFIED="1265219911260" TEXT="HCIR_GeneG: #ssm2010 Petersen: yahoo answers an attempt to recrate Naver in the US. Didn&apos;t work due to lack of high level of authority. No social graph"/> +<node CREATED="1265219953336" ID="Freemind_Link_762332142" MODIFIED="1265219954495" TEXT="HCIR_GeneG: #ssm2010 Petersen: yahoo answers degenerated into chatting in part due to optional anonymity"/> +</node> +<node CREATED="1265220165502" FOLDED="true" ID="Freemind_Link_139605643" MODIFIED="1265220166476" TEXT="Aardvark"> +<node CREATED="1265220185478" ID="Freemind_Link_1107943" MODIFIED="1265220201429" TEXT="nitya: #ssm2010 Jan talking about @vark http://vark.com/aardvarkFinalWWW2010.pdf for the paper he cited. I highly recommend it -- great insights"/> +</node> +</node> +<node CREATED="1265215283704" ID="Freemind_Link_1243291700" MODIFIED="1265218715656" POSITION="left" TEXT="General Observations"> +<node CREATED="1265215413544" FOLDED="true" ID="Freemind_Link_1050956729" MODIFIED="1265215416916" TEXT="Identities"> +<node CREATED="1265215725798" ID="Freemind_Link_1440985821" MODIFIED="1265215727076" TEXT="HCIR_GeneG: #ssm2010 chang: trust people in social network. don&apos;t worry about strangers"/> +</node> +<node CREATED="1265215682899" FOLDED="true" ID="Freemind_Link_1326526688" MODIFIED="1265215688993" TEXT="Search vs. Monitoring"> +<node CREATED="1265215692119" ID="Freemind_Link_883208911" MODIFIED="1265215693629" TEXT="HCIR_GeneG: #ssm2010 hylton: implicit queries. What&apos;s going on here, what&apos;s trending in my social network?"/> +</node> +<node CREATED="1265216456614" FOLDED="true" ID="Freemind_Link_21606023" MODIFIED="1265216466245" TEXT="Algoritm vs. Recommendation"> +<node CREATED="1265216487473" ID="Freemind_Link_244043529" MODIFIED="1265216489046" TEXT="HCIR_GeneG: #ssm2010 hurst: answer from a specific person carries different weight than aggregated data."/> +<node CREATED="1265216504181" ID="Freemind_Link_1182822588" MODIFIED="1265216506381" TEXT="HCIR_GeneG: #ssm2010 hurst: might mistrust algorithm more than known (trusted) expert"/> +</node> +<node CREATED="1265216572308" FOLDED="true" ID="Freemind_Link_1986986882" MODIFIED="1265216591531" TEXT="Information Needs not Social Search"> +<node CREATED="1265216593456" ID="Freemind_Link_1700779959" MODIFIED="1265216596934" TEXT="HCIR_GeneG: #ssm2010 hylton: define specific information needs rather than social search. Web has always been social. e.g: home page."/> +</node> +<node CREATED="1265219282998" ID="Freemind_Link_325278824" MODIFIED="1265219289076" TEXT="Social vs. Simple Search"> +<node CREATED="1265219290024" ID="Freemind_Link_1155606501" MODIFIED="1265219291763" TEXT="HCIR_GeneG: #ssm2010 Petersen: web search is driven by metadata; social media aslo has minable metadata"/> +</node> +</node> +<node CREATED="1265215303751" ID="Freemind_Link_1230387569" MODIFIED="1265215307565" POSITION="right" TEXT="People"> +<node CREATED="1265215471188" FOLDED="true" ID="Freemind_Link_266182439" MODIFIED="1265215479902" TEXT="Sihem Amer-Yahia, Yahoo! research "> +<node CREATED="1265215467427" ID="Freemind_Link_999832029" MODIFIED="1265215469080" TEXT="ian_soboroff: #ssm2010 Sihem Amer-Yahia, Yahoo! research "/> +</node> +<node CREATED="1265219765623" ID="Freemind_Link_156039090" MODIFIED="1265219767171" TEXT="Jeremy Hylton, Google"/> +<node CREATED="1265219774064" ID="Freemind_Link_1607804504" MODIFIED="1265219775436" TEXT="Matt Hurst, Microsoft"/> +</node> +<node CREATED="1265217007420" ID="Freemind_Link_9424424" MODIFIED="1265217009586" POSITION="left" TEXT="Twitter"> +<node CREATED="1265217010667" FOLDED="true" ID="Freemind_Link_1106977666" MODIFIED="1265217013103" TEXT="Observations"> +<node CREATED="1265217015500" ID="Freemind_Link_1505949185" MODIFIED="1265217017050" TEXT="HCIR_GeneG: #ssm2010 Petersen: breaking news on twitter peaks within two minutes of event"/> +<node CREATED="1265217055321" ID="Freemind_Link_958478883" MODIFIED="1265217058013" TEXT="jny2: &quot;It&apos;s not so much the tweet itself, but the referring content,&quot; says Jan Pederson. Show the page to which the tweet points! #ssm2010"/> +<node CREATED="1265217553970" ID="Freemind_Link_590363872" MODIFIED="1265217555383" TEXT="nitya: #ssm2010 nice point made about Twitter providing &quot;observable&quot; propagation of information (RT, via, @replies etc...)"/> +</node> +<node CREATED="1265215948704" FOLDED="true" ID="Freemind_Link_1388855541" MODIFIED="1265215952188" TEXT="Spam on Twitter"> +<node CREATED="1265215954806" ID="Freemind_Link_1420488927" MODIFIED="1265215956968" TEXT="nitya: #ssm2010 in the context of twitter and spam -- a great article on bots and spam detection http://bit.ly/4zekRD"/> +<node CREATED="1265215986344" ID="Freemind_Link_615168068" MODIFIED="1265215986344" TEXT="jny2: On twitter, it&apos;s easy to detect spam. A &quot;naturally connected community&quot; is very different from a &quot;spam marketing campaign.&quot; #ssm2010 Huh!"/> +</node> +<node CREATED="1265215398700" FOLDED="true" ID="Freemind_Link_1992659151" MODIFIED="1265215736246" TEXT="Trends"> +<node CREATED="1265215288671" ID="Freemind_Link_1224337196" MODIFIED="1265215293509" TEXT="jny2: Matthew Hurst sez: There&apos;s a loop in which things &quot;trend on twitter just because they trend on twitter.&quot; #ssm2010 We need to unwind that."/> +</node> +<node CREATED="1265216067741" FOLDED="true" ID="Freemind_Link_1653779855" MODIFIED="1265216074125" TEXT="Paper on Retweeting"> +<node CREATED="1265216076091" FOLDED="true" ID="Freemind_Link_198951219" MODIFIED="1265216102961" TEXT="No figures :("> +<node CREATED="1265216085370" ID="Freemind_Link_751034946" MODIFIED="1265216087398" TEXT="nitya: #ssm2010 Re: the retweeting as indicator of peaking, @zephoria paper on Retweets is a must-read to understand intents http://bit.ly/PCKTo"/> +</node> +</node> +<node CREATED="1265220355528" ID="Freemind_Link_1219317989" MODIFIED="1265220361226" TEXT="Breacking News"> +<node CREATED="1265220365017" ID="Freemind_Link_1546684485" MODIFIED="1265220366340" TEXT="HCIR_GeneG: #ssm2010 Petersen: breaking news on twitter peaks within two minutes of event"/> +<node CREATED="1265220411057" ID="Freemind_Link_1783116050" MODIFIED="1265220412061" TEXT="nitya: #ssm2010 Next Use Case: Breaking News -- emergency events like earthquakes etc. (USGS looking at Twitter for detection http://bit.ly/aAejiA"/> +</node> +</node> +</node> +</map> diff --git a/ssm2010_second_panel.mm b/ssm2010_second_panel.mm new file mode 100644 index 0000000..41fa122 --- /dev/null +++ b/ssm2010_second_panel.mm @@ -0,0 +1,53 @@ +<map version="0.8.1"> +<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net --> +<node CREATED="1265221832619" ID="Freemind_Link_609047317" MODIFIED="1265221851351" TEXT=" #ssm2010 second panel"> +<node CREATED="1265223066834" FOLDED="true" ID="Freemind_Link_1101727269" MODIFIED="1265223068748" POSITION="right" TEXT="People"> +<node CREATED="1265223076021" MODIFIED="1265223076021" TEXT="David Hendi, MySpace"/> +<node CREATED="1265223083516" MODIFIED="1265223083516" TEXT="Hilary Mason, bit.ly"/> +<node CREATED="1265223089679" ID="Freemind_Link_405799441" MODIFIED="1265223089679" TEXT="Igor Perisic, LinkedIn"/> +</node> +<node CREATED="1265223064079" FOLDED="true" ID="_" MODIFIED="1265223066195" POSITION="right" TEXT="Companies"> +<node CREATED="1265223125946" FOLDED="true" ID="Freemind_Link_1762556587" MODIFIED="1265223227875" TEXT="MySpace" VSHIFT="-17"> +<node CREATED="1265224185231" ID="Freemind_Link_1816861261" MODIFIED="1265224186504" TEXT="HCIR_GeneG #ssm2010 David Hendi (myspace): People want to see what are up to"/> +<node CREATED="1265224202824" ID="Freemind_Link_1410070725" MODIFIED="1265224204197" TEXT="HCIR_GeneG #ssm2010 hendi: both search and browsing"/> +<node CREATED="1265224212945" ID="Freemind_Link_750155603" MODIFIED="1265224213718" TEXT="HCIR_GeneG #ssm2010 hendi without social graph, cannot do anything."/> +<node CREATED="1265224429923" ID="Freemind_Link_1115270761" MODIFIED="1265224430760" TEXT="HCIR_GeneG: #ssm2010 hendi: myspace has dashboard to show users to see who is interacting with them"/> +<node CREATED="1265225719222" ID="Freemind_Link_808054147" MODIFIED="1265225727067" TEXT="Graph public?"> +<node CREATED="1265225728854" ID="Freemind_Link_1594395103" MODIFIED="1265225729480" TEXT="HCIR_GeneG: #ssm2010 hendi myspace would like others to build on top of their data."/> +</node> +<node CREATED="1265225868266" ID="Freemind_Link_825782212" MODIFIED="1265225869276" TEXT="HCIR_GeneG: #ssm2010 hendi MySpace user base has changed a lot over last few years; goal to figure out what they want. Always a catchup game."/> +</node> +<node CREATED="1265223229833" FOLDED="true" ID="Freemind_Link_618107527" MODIFIED="1265223232307" TEXT="Bit.ly"> +<node CREATED="1265223246367" MODIFIED="1265223246367" TEXT="HCIR_GeneG #ssm2010 mason: bit.ly analytics/data are public"/> +<node CREATED="1265223252988" MODIFIED="1265223252988" TEXT="HCIR_GeneG #ssm2010 mason: bit.ly spends lots of resources detecting spam"/> +<node CREATED="1265223263463" MODIFIED="1265223263463" TEXT="HCIR_GeneG #ssm2010 mason: half the clicks on a link occur within ten minutes of it being shared"/> +<node CREATED="1265223273318" MODIFIED="1265223273318" TEXT="nitya #ssm2010 half-life of a new bit.ly link is 10 minutes"/> +<node CREATED="1265223324615" LINK="http://bitly.tv" MODIFIED="1265223324615" TEXT="HCIR_GeneG #ssm2010 mason: http://bitly.tv what are the cool videos on the net right now?"/> +<node CREATED="1265224007038" ID="Freemind_Link_643726124" MODIFIED="1265224008259" TEXT="HCIR_GeneG: #ssm2010 mason: bit.ly will release history search soon; encourages people to build on their APIs"/> +<node CREATED="1265224319347" ID="Freemind_Link_1277341994" MODIFIED="1265224320515" TEXT="HCIR_GeneG: #ssm2010 @matthewhurst bit.ly could focus on brand, not just social search"/> +<node CREATED="1265224334039" ID="Freemind_Link_1994341444" MODIFIED="1265224335575" TEXT="#ssm2010 mason: will offer service to publishers, brand-conscious customers soon"/> +<node CREATED="1265225826852" ID="Freemind_Link_1271100791" MODIFIED="1265225831581" TEXT="Structure of links"> +<node CREATED="1265225832684" MODIFIED="1265225832684" TEXT="HCIR_GeneG: #ssm2010 mason: 27% of links on tech; 0.03% on weather"/> +</node> +</node> +<node CREATED="1265223397148" FOLDED="true" ID="Freemind_Link_1025381078" MODIFIED="1265223402508" TEXT="LinkedIn"> +<node CREATED="1265224546512" FOLDED="true" ID="Freemind_Link_1672673668" MODIFIED="1265224554599" TEXT="Search what"> +<node CREATED="1265223404337" ID="Freemind_Link_498983571" MODIFIED="1265223406722" TEXT="HCIR_GeneG #ssm2010 Igor Perisic (LinkedIn): search for people, companies, jobs, discussions, etc. People search is most dominant."/> +<node CREATED="1265223453031" ID="Freemind_Link_939841425" MODIFIED="1265223454143" TEXT="HCIR_GeneG #ssm2010 Perisic: search in linkedin is intrinsically personal, hard to define relevance"/> +</node> +<node CREATED="1265224572544" FOLDED="true" ID="Freemind_Link_1332075582" MODIFIED="1265224576251" TEXT="Graph partitioning"> +<node CREATED="1265224144119" ID="Freemind_Link_784537038" MODIFIED="1265224154572" TEXT="[re: graph partitioning] HCIR_GeneG: #ssm2010 perisic: we use distributed hash as part of the solution. Don&apos;t know the full answer yet! Check back in 8 months"/> +</node> +<node CREATED="1265224596574" FOLDED="true" ID="Freemind_Link_654854464" MODIFIED="1265224611066" TEXT="Revenue"> +<node CREATED="1265224420739" ID="Freemind_Link_522227595" MODIFIED="1265224421713" TEXT="HCIR_GeneG: #ssm2010 perisic: one of the revenue streams is subscriptions. &quot;Who viewed my job?&quot; has value. Am I targeting the right people?"/> +</node> +<node CREATED="1265224510224" FOLDED="true" HGAP="23" ID="Freemind_Link_706686321" MODIFIED="1265224528551" TEXT="Friend suggest" VSHIFT="-16"> +<node CREATED="1265224514989" ID="Freemind_Link_1753230301" MODIFIED="1265225681093" TEXT="No commets"/> +</node> +<node CREATED="1265225682713" FOLDED="true" ID="Freemind_Link_466314224" MODIFIED="1265225696235" TEXT="How much of the graph is public"> +<node CREATED="1265225699729" ID="Freemind_Link_1899665356" MODIFIED="1265225700530" TEXT="HCIR_GeneG: #ssm2010 perisic: would not give up the graph, but your profile is public. How much should be in public vs. private profile?"/> +</node> +</node> +</node> +</node> +</map>
dudarev/ssm2010
16bf5c242177ebf3776c6ac5be13edf491eca885
gitignore and initial edit
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1377554 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.swp diff --git a/index.html b/index.html index a64f2b7..bb651f7 100644 --- a/index.html +++ b/index.html @@ -1,76 +1,61 @@ <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>dudarev/ssm2010 @ GitHub</title> <style type="text/css"> body { margin-top: 1.0em; background-color: #fff; font-family: "Helvetica,Arial,FreeSans"; color: #000000; } #container { margin: 0 auto; width: 700px; } h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; } h1 .small { font-size: 0.4em; } h1 a { text-decoration: none } h2 { font-size: 1.5em; color: #000000; } h3 { text-align: center; color: #000000; } a { color: #000000; } .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} .download { float: right; } pre { background: #000; color: #fff; padding: 15px;} hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} .footer { text-align:center; padding-top:30px; font-style: italic; } </style> </head> <body> - <a href="http://github.com/dudarev/ssm2010"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> <div id="container"> - <div class="download"> - <a href="http://github.com/dudarev/ssm2010/zipball/master"> - <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> - <a href="http://github.com/dudarev/ssm2010/tarball/master"> - <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> - </div> - <h1><a href="http://github.com/dudarev/ssm2010">ssm2010</a> - <span class="small">by <a href="http://github.com/dudarev">dudarev</a></span></h1> + </h1> <div class="description"> - My notes on tweets related to Search in Social Media 2010 workshop. + My notes on tweets related to Search in Social Media 2010 workshop </div> - + <h2>About SSM2010</h2> + <p>The Third Annual Workshop on Search in Social Media (SSM 2010) took place.</p> + + <h2>Notes</h2> + <p>In FreeMind format.</p> - <h2>Download</h2> - <p> - You can download this project in either - <a href="http://github.com/dudarev/ssm2010/zipball/master">zip</a> or - <a href="http://github.com/dudarev/ssm2010/tarball/master">tar</a> formats. - </p> - <p>You can also clone the project with <a href="http://git-scm.com">Git</a> - by running: - <pre>$ git clone git://github.com/dudarev/ssm2010</pre> - </p> - <div class="footer"> - get the source code on GitHub : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> + this page is hosted on github : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> </div> </div> </body> </html>
dudarev/ssm2010
02944e664ddae6ba20963dd337ff2c8a83a272e8
github generated gh-pages branch
diff --git a/index.html b/index.html new file mode 100644 index 0000000..a64f2b7 --- /dev/null +++ b/index.html @@ -0,0 +1,76 @@ +<!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> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + + <title>dudarev/ssm2010 @ GitHub</title> + + <style type="text/css"> + body { + margin-top: 1.0em; + background-color: #fff; + font-family: "Helvetica,Arial,FreeSans"; + color: #000000; + } + #container { + margin: 0 auto; + width: 700px; + } + h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; } + h1 .small { font-size: 0.4em; } + h1 a { text-decoration: none } + h2 { font-size: 1.5em; color: #000000; } + h3 { text-align: center; color: #000000; } + a { color: #000000; } + .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} + .download { float: right; } + pre { background: #000; color: #fff; padding: 15px;} + hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} + .footer { text-align:center; padding-top:30px; font-style: italic; } + </style> + +</head> + +<body> + <a href="http://github.com/dudarev/ssm2010"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> + + <div id="container"> + + <div class="download"> + <a href="http://github.com/dudarev/ssm2010/zipball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> + <a href="http://github.com/dudarev/ssm2010/tarball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> + </div> + + <h1><a href="http://github.com/dudarev/ssm2010">ssm2010</a> + <span class="small">by <a href="http://github.com/dudarev">dudarev</a></span></h1> + + <div class="description"> + My notes on tweets related to Search in Social Media 2010 workshop. + </div> + + + + <h2>Download</h2> + <p> + You can download this project in either + <a href="http://github.com/dudarev/ssm2010/zipball/master">zip</a> or + <a href="http://github.com/dudarev/ssm2010/tarball/master">tar</a> formats. + </p> + <p>You can also clone the project with <a href="http://git-scm.com">Git</a> + by running: + <pre>$ git clone git://github.com/dudarev/ssm2010</pre> + </p> + + <div class="footer"> + get the source code on GitHub : <a href="http://github.com/dudarev/ssm2010">dudarev/ssm2010</a> + </div> + + </div> + + +</body> +</html>
chrisforbes/dbgtool
f868dfe509b64dfcba09cc714f38495d10750cf7
use psapi to lookup mapped file names, because dbgapi just gives you NULL.
diff --git a/Ijw.Cricket.NasmApi.Tests/Ijw.Cricket.NasmApi.Tests.csproj b/Ijw.Cricket.NasmApi.Tests/Ijw.Cricket.NasmApi.Tests.csproj index ebd1e7f..d016bac 100644 --- a/Ijw.Cricket.NasmApi.Tests/Ijw.Cricket.NasmApi.Tests.csproj +++ b/Ijw.Cricket.NasmApi.Tests/Ijw.Cricket.NasmApi.Tests.csproj @@ -1,68 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{CF583BF3-08EC-4527-9C45-6E0583BA617B}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Ijw.Cricket.NasmApi.Tests</RootNamespace> <AssemblyName>Ijw.Cricket.NasmApi.Tests</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> - <Reference Include="nunit.framework, Version=2.5.2.9222, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" /> + <Reference Include="nunit.framework, Version=2.5.2.9222, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Ijw.Cricket.NasmApi\Ijw.Cricket.NasmApi.csproj"> <Project>{251B8668-A494-46F3-B18D-119CF51DB6D5}</Project> <Name>Ijw.Cricket.NasmApi</Name> </ProjectReference> </ItemGroup> <ItemGroup> <Compile Include="TestDisassembly.cs" /> </ItemGroup> <ItemGroup> <Folder Include="Properties\" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Ijw.Cricket.NativeDebugApi/Ijw.Cricket.NativeDebugApi.csproj b/Ijw.Cricket.NativeDebugApi/Ijw.Cricket.NativeDebugApi.csproj index 7e26a94..64c9a72 100644 --- a/Ijw.Cricket.NativeDebugApi/Ijw.Cricket.NativeDebugApi.csproj +++ b/Ijw.Cricket.NativeDebugApi/Ijw.Cricket.NativeDebugApi.csproj @@ -1,64 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{58F53891-BD37-41F1-8EF8-79BD76142DD6}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Ijw.Cricket.NativeDebugApi</RootNamespace> <AssemblyName>Ijw.Cricket.NativeDebugApi</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="DebugEvent.cs" /> <Compile Include="Kernel32.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="Psapi.cs" /> <Compile Include="RandomEnums.cs" /> <Compile Include="StartupInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Ijw.Cricket.NativeDebugApi/Psapi.cs b/Ijw.Cricket.NativeDebugApi/Psapi.cs new file mode 100644 index 0000000..bcc6cb2 --- /dev/null +++ b/Ijw.Cricket.NativeDebugApi/Psapi.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; + +namespace Ijw.Cricket.NativeDebugApi +{ + public static class Psapi + { + [DllImport("psapi.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetMappedFileName(IntPtr hProcess, IntPtr ptr, StringBuilder sb, int size); + } +} diff --git a/Ijw.Cricket.Ui/Target.cs b/Ijw.Cricket.Ui/Target.cs index d5471d5..d65929b 100644 --- a/Ijw.Cricket.Ui/Target.cs +++ b/Ijw.Cricket.Ui/Target.cs @@ -1,113 +1,121 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ijw.Cricket.NativeDebugApi; +using System.Runtime.InteropServices; namespace Ijw.Cricket.Ui { public class Target : IDisposable { PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); DebugEvent lastEvent; public TargetState State { get; private set; } public Target(string commandLine, string arguments, string workingDirectory) { State = TargetState.Starting; Program.OutputMessage("Starting target..."); if (!Kernel32.CreateProcess(commandLine, arguments, IntPtr.Zero, IntPtr.Zero, false, CreateProcessFlags.DebugOnlyThisProcess, IntPtr.Zero, workingDirectory, new STARTUPINFO(), pi)) throw new InvalidOperationException("The target process could not be started"); State = TargetState.Running; Program.OutputMessage("Successfully connected to target."); } bool disposed; public void Dispose() { if (disposed) return; disposed = true; if (pi != null) { Kernel32.TerminateProcess(pi.hProcess, 1); Program.OutputMessage("Target terminated."); pi = null; } GC.SuppressFinalize(this); } ~Target() { Dispose(); } public void Detach() { if (pi == null) throw new InvalidOperationException("There is no process to detach from"); Kernel32.DebugSetProcessKillOnExit(false); Kernel32.DebugActiveProcessStop(pi.dwProcessId); State = TargetState.Detached; pi = null; Program.OutputMessage("Detached."); } public void Continue(ContinueStatus status) { if (State != TargetState.Paused) throw new InvalidOperationException("Continue requires a Paused target"); if (!Kernel32.ContinueDebugEvent(lastEvent.ProcessId, lastEvent.ThreadId, status)) throw new InvalidOperationException("ContinueDebugEvent failed"); State = (lastEvent.EventCode == DebugEventCode.RipEvent | lastEvent.EventCode == DebugEventCode.ExitProcess) ? TargetState.Exited /* todo: handle this properly */ : TargetState.Running; } public void CollectEvents() { if (State != TargetState.Running) throw new InvalidOperationException("CollectEvents requires a Running target"); while (Kernel32.WaitForDebugEvent(out lastEvent, 0)) DispatchEvent(lastEvent); } void DispatchEvent(DebugEvent e) { Program.OutputMessage("DispatchEvent code={0} pid=0x{1:X8} tid=0x{2:X8}", e.EventCode, e.ProcessId, e.ThreadId); State = TargetState.Paused; /* todo: do something with some of these events! */ + + if (e.EventCode == DebugEventCode.LoadDll) + { + var sb = new StringBuilder(1024); + Psapi.GetMappedFileName(pi.hProcess, e.LoadDll.lpBaseOfDll, sb, sb.Capacity); + Program.OutputMessage("LoadDll: {0} @ 0x{1:X8}", sb.ToString(), (uint)(ulong)e.LoadDll.lpBaseOfDll.ToInt64()); + } } public ContinueStatus GetDefaultContinue() { /* gets an appropriate continuation action for the last event */ if (lastEvent.EventCode != DebugEventCode.Exception) return ContinueStatus.Continue; if (lastEvent.Exception.dwFirstChance != 0 && lastEvent.Exception.ExceptionRecord.ExceptionCode == ExceptionCode.STATUS_BREAKPOINT) return ContinueStatus.Continue; return ContinueStatus.ExceptionNotHandled; /* send the exception to the usual handler! */ } } public enum TargetState { Starting, Running, Paused, Exited, Detached, } } diff --git a/native/nasmapi/nasmapi.vcproj b/native/nasmapi/nasmapi.vcproj index f124aee..1ad8eef 100644 --- a/native/nasmapi/nasmapi.vcproj +++ b/native/nasmapi/nasmapi.vcproj @@ -1,269 +1,357 @@ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="nasmapi" ProjectGUID="{D851B138-B43A-4077-A75E-A33E026A8B4A}" RootNamespace="nasmapi" Keyword="Win32Proj" TargetFrameworkVersion="196613" > <Platforms> <Platform Name="Win32" /> </Platforms> <ToolFiles> </ToolFiles> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="$(SolutionDir)Ijw.Cricket.NasmApi\" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" CharacterSet="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="." PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;NASMAPI_EXPORTS;HAVE__VSNPRINT" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" LinkIncremental="2" GenerateDebugInformation="true" SubSystem="2" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="$(SolutionDir)$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" CharacterSet="1" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="2" EnableIntrinsicFunctions="true" AdditionalIncludeDirectories="." PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;NASMAPI_EXPORTS" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" LinkIncremental="1" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="nasm" > <File RelativePath=".\compiler.h" > </File> <File RelativePath=".\disasm.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\disasm.h" > </File> <File RelativePath=".\insnsb.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\insnsd.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\insnsi.h" > </File> <File RelativePath=".\insnsn.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\inttypes.h" > </File> <File RelativePath=".\nasm.h" > </File> <File RelativePath=".\nasmlib.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\nasmlib.h" > </File> <File RelativePath=".\ndisasm.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\preproc.h" > </File> <File RelativePath=".\regdis.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\regdis.h" > </File> <File RelativePath=".\regs.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\regs.h" > </File> <File RelativePath=".\snprintf.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\sync.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> <File RelativePath=".\sync.h" > </File> <File RelativePath=".\tables.h" > </File> <File RelativePath=".\ver.c" > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + WarningLevel="0" + /> + </FileConfiguration> </File> </Filter> <File RelativePath=".\nasmapi.c" > </File> </Files> <Globals> </Globals> </VisualStudioProject>
galaxycats/haz_enum
fa6cf0e5d5d75dc23d7e42feedb5c68cb865d768
added spec for validations
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index 1eabaa2..f00104d 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,97 +1,102 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Enum" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end + it "should be transparent for validations" do + object = ClassWithEnum.new + object.save.should be_false + end + it "should have has_<association>? method" do class_with_enum = ClassWithEnum.new(:product => "Silver") class_with_enum.has_product?(Products::Silver).should == true class_with_enum.has_product?(Products::Gold).should == false end it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end it "should work without renum (just ruby module with classes)" do role_enum = ClassWithEnum.new(:module_role => ModuleRoles::Admin) role_enum.has_module_role?(ModuleRoles::Admin).should == true end it "should handle blank parameter of setter" do ClassWithEnum.new(:product => nil).product.should be_nil ClassWithEnum.new(:product => "").product.should be_nil end it "should be able to set the class_name manually" do main_product_enum = ClassWithCustomNameField.new(:main_product => Products::Silver) main_product_enum.main_product.should == Products::Silver main_product_enum.save ClassWithCustomNameField.find(main_product_enum.id).main_product.should == Products::Silver end it "should be able to set the enum class manually" do sub_product_enum = ClassWithCustomNameField.new(:sub_product => Products::Gold) sub_product_enum.sub_product.should == Products::Gold sub_product_enum.save ClassWithCustomNameField.find(sub_product_enum.id).sub_product.should == Products::Gold end after(:all) do teardown_db end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6261a80..93a5d32 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,128 +1,130 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :module_role, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_fields do |t| t.column :title, :string t.column :main_product, :string t.column :sub_product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :module_roles_yml, :text t.column :extended_roles_yml, :text t.column :module_bitfield_roles_bitfield, :integer t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] module ModuleRoles class Admin; def self.name; "Admin"; end; end class Supervisor; def self.name; "Supervisor"; end; end class ContentManager; def self.name; "ContentManager"; end; end end module ModuleBitfieldRoles class Admin def self.bitfield_index; 1; end end class Supervisor def self.bitfield_index; 2; end end class ContentManager def self.bitfield_index; 3; end end class <<self def values ModuleBitfieldRoles.constants.collect { |c| ModuleBitfieldRoles.const_get(c) } end end end setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product has_enum :module_role + + validates :product, presence: true end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithCustomNameField < ActiveRecord::Base has_enum :main_product, :class_name => "Products" has_enum :sub_product, :enum => Products end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end has_set :module_roles has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base self.table_name = "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards
galaxycats/haz_enum
e2b81a01788f37c57966ff66c76cb42b02cd6a1a
bump version
diff --git a/lib/version.rb b/lib/version.rb index 1f0715e..55a0f88 100644 --- a/lib/version.rb +++ b/lib/version.rb @@ -1,3 +1,3 @@ module HazEnum - VERSION = "0.5.4" -end \ No newline at end of file + VERSION = "0.5.5" +end
galaxycats/haz_enum
9166bce179f2643c7f1f251992a166f1a800c7f5
new way to specify enum class
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb index 1cac2ea..b60780c 100644 --- a/lib/haz_enum/enum.rb +++ b/lib/haz_enum/enum.rb @@ -1,53 +1,59 @@ module HazEnum module Enum def has_enum(enum_name, options={}) enum_name = enum_name.to_s enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name - enum_class = options.has_key?(:class_name) ? options[:class_name].constantize : enum_name.pluralize.camelize.constantize + enum_class = if options.has_key?(:class_name) + options[:class_name].constantize + elsif options[:enum] + options[:enum] + else + enum_name.pluralize.camelize.constantize + end self.attr_protected("#{enum_column}") if enum_name != enum_column self.validate "#{enum_column}_check_for_valid_enum_value" define_method "#{enum_name}" do begin return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"] return nil rescue NameError => e return nil end end define_method "#{enum_name}=" do |enum_to_set| if enum_to_set.blank? self["#{enum_column}"] = nil elsif enum_to_set.respond_to?(:name) self["#{enum_column}"] = enum_to_set.name else self["#{enum_column}"] = enum_class.const_get(enum_to_set).name end end define_method "has_#{enum_name}?" do |enum| send(enum_name) == enum end define_method "#{enum_name}_changed?" do send("#{enum_column}_changed?") end if enum_name != enum_column define_method "#{enum_column}_check_for_valid_enum_value" do return true if self["#{enum_column}"].nil? begin enum_class.const_get(self["#{enum_column}"]) rescue NameError => e message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name) self.errors.add(enum_name.to_sym, message) end end end end end diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index 6ab12ff..1eabaa2 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,90 +1,97 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Enum" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end it "should have has_<association>? method" do class_with_enum = ClassWithEnum.new(:product => "Silver") class_with_enum.has_product?(Products::Silver).should == true class_with_enum.has_product?(Products::Gold).should == false end it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end it "should work without renum (just ruby module with classes)" do role_enum = ClassWithEnum.new(:module_role => ModuleRoles::Admin) role_enum.has_module_role?(ModuleRoles::Admin).should == true end it "should handle blank parameter of setter" do ClassWithEnum.new(:product => nil).product.should be_nil ClassWithEnum.new(:product => "").product.should be_nil end - it "should be able to set the enum class manually" do + it "should be able to set the class_name manually" do main_product_enum = ClassWithCustomNameField.new(:main_product => Products::Silver) main_product_enum.main_product.should == Products::Silver main_product_enum.save - ClassWithCustomNameField.first.main_product.should == Products::Silver + ClassWithCustomNameField.find(main_product_enum.id).main_product.should == Products::Silver + end + + it "should be able to set the enum class manually" do + sub_product_enum = ClassWithCustomNameField.new(:sub_product => Products::Gold) + sub_product_enum.sub_product.should == Products::Gold + sub_product_enum.save + ClassWithCustomNameField.find(sub_product_enum.id).sub_product.should == Products::Gold end after(:all) do teardown_db end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 885bd29..6261a80 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,126 +1,128 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :module_role, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_fields do |t| t.column :title, :string t.column :main_product, :string + t.column :sub_product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :module_roles_yml, :text t.column :extended_roles_yml, :text t.column :module_bitfield_roles_bitfield, :integer t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] module ModuleRoles class Admin; def self.name; "Admin"; end; end class Supervisor; def self.name; "Supervisor"; end; end class ContentManager; def self.name; "ContentManager"; end; end end module ModuleBitfieldRoles class Admin def self.bitfield_index; 1; end end class Supervisor def self.bitfield_index; 2; end end class ContentManager def self.bitfield_index; 3; end end class <<self def values ModuleBitfieldRoles.constants.collect { |c| ModuleBitfieldRoles.const_get(c) } end end end setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product has_enum :module_role end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithCustomNameField < ActiveRecord::Base has_enum :main_product, :class_name => "Products" + has_enum :sub_product, :enum => Products end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end has_set :module_roles has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base self.table_name = "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards
galaxycats/haz_enum
27f626f418b6aa586d4e00d942ab24e6a1f71e04
added specs for setting class_name
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb index f4a5bd1..1cac2ea 100644 --- a/lib/haz_enum/enum.rb +++ b/lib/haz_enum/enum.rb @@ -1,53 +1,53 @@ module HazEnum module Enum def has_enum(enum_name, options={}) enum_name = enum_name.to_s enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name enum_class = options.has_key?(:class_name) ? options[:class_name].constantize : enum_name.pluralize.camelize.constantize - + self.attr_protected("#{enum_column}") if enum_name != enum_column self.validate "#{enum_column}_check_for_valid_enum_value" - + define_method "#{enum_name}" do begin return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"] return nil rescue NameError => e return nil end end - + define_method "#{enum_name}=" do |enum_to_set| if enum_to_set.blank? self["#{enum_column}"] = nil elsif enum_to_set.respond_to?(:name) self["#{enum_column}"] = enum_to_set.name else self["#{enum_column}"] = enum_class.const_get(enum_to_set).name end end - + define_method "has_#{enum_name}?" do |enum| send(enum_name) == enum end - + define_method "#{enum_name}_changed?" do send("#{enum_column}_changed?") end if enum_name != enum_column - + define_method "#{enum_column}_check_for_valid_enum_value" do return true if self["#{enum_column}"].nil? begin enum_class.const_get(self["#{enum_column}"]) rescue NameError => e - + message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name) - + self.errors.add(enum_name.to_sym, message) end end end end -end \ No newline at end of file +end diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index ccfdf5f..6ab12ff 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,83 +1,90 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do - + describe "Enum" do - + before(:all) do setup_db end - + it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end - + it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end - + it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end - + it "should have has_<association>? method" do class_with_enum = ClassWithEnum.new(:product => "Silver") class_with_enum.has_product?(Products::Silver).should == true class_with_enum.has_product?(Products::Gold).should == false end - + it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end - + it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end - + it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end - + it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end - + it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end - + it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end - + it "should work without renum (just ruby module with classes)" do role_enum = ClassWithEnum.new(:module_role => ModuleRoles::Admin) role_enum.has_module_role?(ModuleRoles::Admin).should == true end - + it "should handle blank parameter of setter" do ClassWithEnum.new(:product => nil).product.should be_nil ClassWithEnum.new(:product => "").product.should be_nil end - + + it "should be able to set the enum class manually" do + main_product_enum = ClassWithCustomNameField.new(:main_product => Products::Silver) + main_product_enum.main_product.should == Products::Silver + main_product_enum.save + ClassWithCustomNameField.first.main_product.should == Products::Silver + end + after(:all) do teardown_db end - + end -end \ No newline at end of file +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 4a0d158..885bd29 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,115 +1,126 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :module_role, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end + create_table :class_with_custom_name_fields do |t| + t.column :title, :string + t.column :main_product, :string + t.column :created_at, :datetime + t.column :updated_at, :datetime + end + create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :module_roles_yml, :text t.column :extended_roles_yml, :text t.column :module_bitfield_roles_bitfield, :integer t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] module ModuleRoles class Admin; def self.name; "Admin"; end; end class Supervisor; def self.name; "Supervisor"; end; end class ContentManager; def self.name; "ContentManager"; end; end end module ModuleBitfieldRoles class Admin def self.bitfield_index; 1; end end class Supervisor def self.bitfield_index; 2; end end class ContentManager def self.bitfield_index; 3; end end class <<self def values ModuleBitfieldRoles.constants.collect { |c| ModuleBitfieldRoles.const_get(c) } end end end setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product has_enum :module_role end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end +class ClassWithCustomNameField < ActiveRecord::Base + has_enum :main_product, :class_name => "Products" +end + class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end has_set :module_roles has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base self.table_name = "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards
galaxycats/haz_enum
2512c50dcec4087c35ce6e171f5f990d248748cd
use just 1.9.3 for testing
diff --git a/.travis.yml b/.travis.yml index 0b4bc45..83fd3bc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,4 @@ language: ruby rvm: - - "1.8.7" - - "1.9.2" - "1.9.3" - - jruby-18mode # JRuby in 1.8 mode - - jruby-19mode # JRuby in 1.9 mode - - rbx-18mode - - rbx-19mode + diff --git a/Rakefile b/Rakefile index 0702ca3..e97bf99 100644 --- a/Rakefile +++ b/Rakefile @@ -1,17 +1,9 @@ require 'rubygems' require "bundler" require 'rake' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) task :default => :spec - -require 'rdoc/task' -Rake::RDocTask.new do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "haz_enum" - rdoc.rdoc_files.include('README*') - rdoc.rdoc_files.include('lib/**/*.rb') -end
galaxycats/haz_enum
ae34b1d56c0ef4a4a16430a9c46a26cd180f2344
added travis config
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..0b4bc45 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: ruby +rvm: + - "1.8.7" + - "1.9.2" + - "1.9.3" + - jruby-18mode # JRuby in 1.8 mode + - jruby-19mode # JRuby in 1.9 mode + - rbx-18mode + - rbx-19mode
galaxycats/haz_enum
c2b2c573bd068e8d1a5493954a6e8c69d223ea03
version number is DRY again, but this time in ruby
diff --git a/VERSION b/VERSION deleted file mode 100644 index c52db98..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.5.3 \ No newline at end of file diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 961fe90..736dd6a 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,31 +1,32 @@ # -*- encoding: utf-8 -*- +require File.join(File.dirname(__FILE__), *%w[lib version]) Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.5.4" + s.version = HazEnum::VERSION s.platform = Gem::Platform::RUBY s.rubyforge_project = "haz_enum" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2011-05-25} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = `git ls-files`.split("\n") s.homepage = %q{http://github.com/galaxycats/haz_enum} s.require_paths = ["lib"] s.rubygems_version = %q{1.5.0} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = `git ls-files -- spec/*`.split("\n") s.add_runtime_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) s.add_development_dependency(%q<rake>, ["~> 0.9"]) s.add_development_dependency(%q<sqlite3>, ["~> 1.3"]) end diff --git a/lib/version.rb b/lib/version.rb new file mode 100644 index 0000000..1f0715e --- /dev/null +++ b/lib/version.rb @@ -0,0 +1,3 @@ +module HazEnum + VERSION = "0.5.4" +end \ No newline at end of file
galaxycats/haz_enum
fd1577631cc7bcf66262fe5f82c85a4ed4f4dc0f
Simplify RDoc task. Why is there rdoc at all? No method is documented, there only exists the readme file
diff --git a/Rakefile b/Rakefile index 5ca692c..e4bbfe5 100644 --- a/Rakefile +++ b/Rakefile @@ -1,27 +1,25 @@ require 'rubygems' require "bundler" require 'rake' require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :default => :spec require 'rdoc/task' Rake::RDocTask.new do |rdoc| - version = File.exist?('VERSION') ? File.read('VERSION') : "" - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "haz_enum #{version}" + rdoc.title = "haz_enum" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
galaxycats/haz_enum
4e539ff64928cf66c689b78a2c219ff1c43d95de
Using bundler with gemspec instead of jeweler
diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..c80ee36 --- /dev/null +++ b/Gemfile @@ -0,0 +1,3 @@ +source "http://rubygems.org" + +gemspec diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..9b9237c --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,39 @@ +PATH + remote: . + specs: + haz_enum (0.5.4) + activerecord (>= 2.3.0) + +GEM + remote: http://rubygems.org/ + specs: + activemodel (3.2.8) + activesupport (= 3.2.8) + builder (~> 3.0.0) + activerecord (3.2.8) + activemodel (= 3.2.8) + activesupport (= 3.2.8) + arel (~> 3.0.2) + tzinfo (~> 0.3.29) + activesupport (3.2.8) + i18n (~> 0.6) + multi_json (~> 1.0) + arel (3.0.2) + builder (3.0.4) + i18n (0.6.1) + multi_json (1.3.6) + rake (0.9.2.2) + renum (1.3.1) + rspec (1.3.2) + sqlite3 (1.3.6) + tzinfo (0.3.34) + +PLATFORMS + ruby + +DEPENDENCIES + haz_enum! + rake (~> 0.9) + renum (~> 1.3.1) + rspec (~> 1.3.0) + sqlite3 (~> 1.3) diff --git a/Rakefile b/Rakefile index 298deb4..5ca692c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,27 @@ require 'rubygems' +require "bundler" require 'rake' -begin - require 'jeweler' - Jeweler::Tasks.new do |gem| - gem.name = "haz_enum" - gem.summary = %Q{has_set and has_enum for ActiveRecord} - gem.description = %Q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} - gem.email = "[email protected]" - gem.homepage = "http://github.com/galaxycats/haz_enum" - gem.authors = ["thyphoon"] - gem.add_dependency "activerecord", ">= 2.3.0" - gem.add_development_dependency "rspec", "~> 1.3.0" - gem.add_development_dependency "renum", "~> 1.3.1" - # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings - end - Jeweler::GemcutterTasks.new -rescue LoadError - puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" -end - require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end -task :spec => :check_dependencies - task :default => :spec require 'rdoc/task' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "haz_enum #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/haz_enum.gemspec b/haz_enum.gemspec index f4d41d8..961fe90 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,63 +1,31 @@ -# Generated by jeweler -# DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.5.3" - + s.version = "0.5.4" + s.platform = Gem::Platform::RUBY + s.rubyforge_project = "haz_enum" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2011-05-25} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] - s.files = [ - ".document", - "CHANGESET", - "LICENSE", - "README.rdoc", - "Rakefile", - "VERSION", - "haz_enum.gemspec", - "lib/haz_enum.rb", - "lib/haz_enum/enum.rb", - "lib/haz_enum/set.rb", - "spec/enum_spec.rb", - "spec/set_spec.rb", - "spec/spec.opts", - "spec/spec_helper.rb" - ] + s.files = `git ls-files`.split("\n") + s.homepage = %q{http://github.com/galaxycats/haz_enum} s.require_paths = ["lib"] s.rubygems_version = %q{1.5.0} s.summary = %q{has_set and has_enum for ActiveRecord} - s.test_files = [ - "spec/enum_spec.rb", - "spec/set_spec.rb", - "spec/spec_helper.rb" - ] - - if s.respond_to? :specification_version then - s.specification_version = 3 + s.test_files = `git ls-files -- spec/*`.split("\n") - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q<activerecord>, [">= 2.3.0"]) - s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) - s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) - else - s.add_dependency(%q<activerecord>, [">= 2.3.0"]) - s.add_dependency(%q<rspec>, ["~> 1.3.0"]) - s.add_dependency(%q<renum>, ["~> 1.3.1"]) - end - else - s.add_dependency(%q<activerecord>, [">= 2.3.0"]) - s.add_dependency(%q<rspec>, ["~> 1.3.0"]) - s.add_dependency(%q<renum>, ["~> 1.3.1"]) - end + s.add_runtime_dependency(%q<activerecord>, [">= 2.3.0"]) + s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) + s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) + s.add_development_dependency(%q<rake>, ["~> 0.9"]) + s.add_development_dependency(%q<sqlite3>, ["~> 1.3"]) end
galaxycats/haz_enum
9ed9d7963badc3a011420665d4b83cb5969ca7a0
Using new rdoc rake tasks cause rake's own are deprecated
diff --git a/Rakefile b/Rakefile index be5d08f..298deb4 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,47 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "haz_enum" gem.summary = %Q{has_set and has_enum for ActiveRecord} gem.description = %Q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} gem.email = "[email protected]" gem.homepage = "http://github.com/galaxycats/haz_enum" gem.authors = ["thyphoon"] gem.add_dependency "activerecord", ">= 2.3.0" gem.add_development_dependency "rspec", "~> 1.3.0" gem.add_development_dependency "renum", "~> 1.3.1" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec -require 'rake/rdoctask' +require 'rdoc/task' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "haz_enum #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
galaxycats/haz_enum
13197bac9a25b6890b2b8b6506c774c662c2da12
Regenerate gemspec for version 0.5.3
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index c08657f..f4d41d8 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,63 +1,63 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.5.2" + s.version = "0.5.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2011-05-25} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.require_paths = ["lib"] s.rubygems_version = %q{1.5.0} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) else s.add_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end else s.add_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end end
galaxycats/haz_enum
169145cc8c1099c804692f8ed8574c1b8900503c
Version bump to 0.5.3
diff --git a/VERSION b/VERSION index 2411653..c52db98 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.5.2 \ No newline at end of file +0.5.3 \ No newline at end of file
galaxycats/haz_enum
8e98108b78725bd21cf7c74d62a196eca15dd7ce
works now with ActiveRecord 2.3.0 and higher
diff --git a/Rakefile b/Rakefile index f9601c9..be5d08f 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,47 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "haz_enum" gem.summary = %Q{has_set and has_enum for ActiveRecord} gem.description = %Q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} gem.email = "[email protected]" gem.homepage = "http://github.com/galaxycats/haz_enum" gem.authors = ["thyphoon"] - gem.add_dependency "activerecord", "~> 3.0.0" + gem.add_dependency "activerecord", ">= 2.3.0" gem.add_development_dependency "rspec", "~> 1.3.0" gem.add_development_dependency "renum", "~> 1.3.1" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "haz_enum #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 96a27e3..c08657f 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,64 +1,63 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} s.version = "0.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] - s.date = %q{2011-05-12} + s.date = %q{2011-05-25} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.require_paths = ["lib"] - s.rubygems_version = %q{1.3.6} + s.rubygems_version = %q{1.5.0} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then - current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 - if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q<activerecord>, ["~> 3.0.0"]) + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + s.add_runtime_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) else - s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) + s.add_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end else - s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) + s.add_dependency(%q<activerecord>, [">= 2.3.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end end
galaxycats/haz_enum
b2f707f6353a91bcae3cc7c60061c08c9fdb0b45
Regenerate gemspec for version 0.5.2
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 44b632c..96a27e3 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,66 +1,64 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.5.1" + s.version = "0.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] - s.date = %q{2011-03-20} + s.date = %q{2011-05-12} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", - "README.rdoc" + "README.rdoc" ] s.files = [ ".document", - ".gitignore", - "CHANGESET", - "LICENSE", - "README.rdoc", - "Rakefile", - "VERSION", - "haz_enum.gemspec", - "lib/haz_enum.rb", - "lib/haz_enum/enum.rb", - "lib/haz_enum/set.rb", - "spec/enum_spec.rb", - "spec/set_spec.rb", - "spec/spec.opts", - "spec/spec_helper.rb" + "CHANGESET", + "LICENSE", + "README.rdoc", + "Rakefile", + "VERSION", + "haz_enum.gemspec", + "lib/haz_enum.rb", + "lib/haz_enum/enum.rb", + "lib/haz_enum/set.rb", + "spec/enum_spec.rb", + "spec/set_spec.rb", + "spec/spec.opts", + "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} - s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", - "spec/set_spec.rb", - "spec/spec_helper.rb" + "spec/set_spec.rb", + "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) else s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end else s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end end
galaxycats/haz_enum
eafc1a4c53e7b7ffda31bc2930cb28a626e915e1
Version bump to 0.5.2
diff --git a/VERSION b/VERSION index 4b9fcbe..2411653 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.5.1 +0.5.2 \ No newline at end of file
galaxycats/haz_enum
cef0248582df4b708d81844ce80bebe8cd1fcc2a
handle blank setter parameters
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb index c8d773f..f4a5bd1 100644 --- a/lib/haz_enum/enum.rb +++ b/lib/haz_enum/enum.rb @@ -1,51 +1,53 @@ module HazEnum module Enum def has_enum(enum_name, options={}) enum_name = enum_name.to_s enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name enum_class = options.has_key?(:class_name) ? options[:class_name].constantize : enum_name.pluralize.camelize.constantize self.attr_protected("#{enum_column}") if enum_name != enum_column self.validate "#{enum_column}_check_for_valid_enum_value" define_method "#{enum_name}" do begin return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"] return nil rescue NameError => e return nil end end define_method "#{enum_name}=" do |enum_to_set| - if enum_to_set.respond_to?(:name) + if enum_to_set.blank? + self["#{enum_column}"] = nil + elsif enum_to_set.respond_to?(:name) self["#{enum_column}"] = enum_to_set.name else self["#{enum_column}"] = enum_class.const_get(enum_to_set).name end end define_method "has_#{enum_name}?" do |enum| send(enum_name) == enum end define_method "#{enum_name}_changed?" do send("#{enum_column}_changed?") end if enum_name != enum_column define_method "#{enum_column}_check_for_valid_enum_value" do return true if self["#{enum_column}"].nil? begin enum_class.const_get(self["#{enum_column}"]) rescue NameError => e message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name) self.errors.add(enum_name.to_sym, message) end end end end end \ No newline at end of file diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index cab6dbf..ccfdf5f 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,78 +1,83 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Enum" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end it "should have has_<association>? method" do class_with_enum = ClassWithEnum.new(:product => "Silver") class_with_enum.has_product?(Products::Silver).should == true class_with_enum.has_product?(Products::Gold).should == false end it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end it "should work without renum (just ruby module with classes)" do role_enum = ClassWithEnum.new(:module_role => ModuleRoles::Admin) role_enum.has_module_role?(ModuleRoles::Admin).should == true end + it "should handle blank parameter of setter" do + ClassWithEnum.new(:product => nil).product.should be_nil + ClassWithEnum.new(:product => "").product.should be_nil + end + after(:all) do teardown_db end end end \ No newline at end of file
galaxycats/haz_enum
719cc0ecc84e4a3b0019f633977a9cf8db0480e6
gemspec for version 0.5.1
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 5d98abd..44b632c 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,66 +1,66 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.5.0" + s.version = "0.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] - s.date = %q{2010-09-16} + s.date = %q{2011-03-20} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) else s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end else s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) s.add_dependency(%q<rspec>, ["~> 1.3.0"]) s.add_dependency(%q<renum>, ["~> 1.3.1"]) end end
galaxycats/haz_enum
4f41f042555c2e8c9269dd5405d60c9bfacfdfe1
Version bump to 0.5.1
diff --git a/VERSION b/VERSION index 8f0916f..4b9fcbe 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.5.0 +0.5.1
galaxycats/haz_enum
db52432d451074719cf1a7d4b9140344293a44b2
use constantize instead of classify
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb index 167db06..c8d773f 100644 --- a/lib/haz_enum/enum.rb +++ b/lib/haz_enum/enum.rb @@ -1,51 +1,51 @@ module HazEnum module Enum def has_enum(enum_name, options={}) enum_name = enum_name.to_s enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name - enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.pluralize.camelize) + enum_class = options.has_key?(:class_name) ? options[:class_name].constantize : enum_name.pluralize.camelize.constantize self.attr_protected("#{enum_column}") if enum_name != enum_column self.validate "#{enum_column}_check_for_valid_enum_value" define_method "#{enum_name}" do begin return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"] return nil rescue NameError => e return nil end end define_method "#{enum_name}=" do |enum_to_set| if enum_to_set.respond_to?(:name) self["#{enum_column}"] = enum_to_set.name else self["#{enum_column}"] = enum_class.const_get(enum_to_set).name end end define_method "has_#{enum_name}?" do |enum| send(enum_name) == enum end define_method "#{enum_name}_changed?" do send("#{enum_column}_changed?") end if enum_name != enum_column define_method "#{enum_column}_check_for_valid_enum_value" do return true if self["#{enum_column}"].nil? begin enum_class.const_get(self["#{enum_column}"]) rescue NameError => e message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name) self.errors.add(enum_name.to_sym, message) end end end end end \ No newline at end of file
galaxycats/haz_enum
99a6e0df439904bf2c224670fa27ca16bbc84970
generated gemspec for 0.5.0
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index be472fa..5d98abd 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,63 +1,66 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.4.3" + s.version = "0.5.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] - s.date = %q{2010-06-29} + s.date = %q{2010-09-16} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) - s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) + s.add_runtime_dependency(%q<activerecord>, ["~> 3.0.0"]) + s.add_development_dependency(%q<rspec>, ["~> 1.3.0"]) + s.add_development_dependency(%q<renum>, ["~> 1.3.1"]) else - s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) - s.add_dependency(%q<rspec>, [">= 1.2.9"]) + s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) + s.add_dependency(%q<rspec>, ["~> 1.3.0"]) + s.add_dependency(%q<renum>, ["~> 1.3.1"]) end else - s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) - s.add_dependency(%q<rspec>, [">= 1.2.9"]) + s.add_dependency(%q<activerecord>, ["~> 3.0.0"]) + s.add_dependency(%q<rspec>, ["~> 1.3.0"]) + s.add_dependency(%q<renum>, ["~> 1.3.1"]) end end
galaxycats/haz_enum
1acddf5d3ab6431c488474c267d785d5fba687d3
Version bump to 0.5.0
diff --git a/VERSION b/VERSION index 17b2ccd..8f0916f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.3 +0.5.0
galaxycats/haz_enum
8c9ab537a8100b45d5f27a3283a96fa6fc112179
use activerecord 3.0
diff --git a/Rakefile b/Rakefile index e4f0c47..f9601c9 100644 --- a/Rakefile +++ b/Rakefile @@ -1,46 +1,47 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "haz_enum" gem.summary = %Q{has_set and has_enum for ActiveRecord} gem.description = %Q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} gem.email = "[email protected]" gem.homepage = "http://github.com/galaxycats/haz_enum" gem.authors = ["thyphoon"] - gem.add_dependency "activerecord", ">= 3.0.0.beta3" - gem.add_development_dependency "rspec", ">= 1.2.9" + gem.add_dependency "activerecord", "~> 3.0.0" + gem.add_development_dependency "rspec", "~> 1.3.0" + gem.add_development_dependency "renum", "~> 1.3.1" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "haz_enum #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
galaxycats/haz_enum
adddea471c43030b7839d5984c350a61ccc4a9f6
wrote some rdoc usage-examples
diff --git a/README.rdoc b/README.rdoc index 82a2384..f69d8b2 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,17 +1,119 @@ = haz_enum -Description goes here. +haz_enum is a ActiveRecord extension to allow associations to enumerations. + +== Installation + +haz_enum is hostet on rubygems.org, so yoou can just do + + gem install haz_enum + +or if you use bundler, just add the following line to your Gemfile: + + gem "haz_enum" + + +== Example with renum + +renum is a perfect library for enumerations in ruby (see http://github.com/duelinmarkers/renum). Here is a simple renum definition: + + enum :Roles do + Admin() + Supervisor() + ContentManager() + end + +in your AR-model you can now write + + class User < ActiveRecord + has_enum :role + end + +what you need is a column in your db named <code>role</code> with type <code>string</code>. + + user = User.create(:role => Roles::Admin) + user.has_role?(Roles::Admin) => true + user.has_role?(Roles::Supervisor) => false + +The example above realizes one role per user. But what if you want to have multiple Roles per user? Just change <code>has_enum</code> to <code>has_set</code> and rename the column to <code>roles</code>: + + class User < ActiveRecord + has_set :roles + end + + user = User.create(:roles => Roles::Admin) + user.has_role?(Roles::Admin) => true + user.has_role?(Roles::Supervisor) => false + +or + + user = User.create(:roles => [Roles::Admin, Roles::Supervisor]) + user.has_role?(Roles::Admin) => true + user.has_role?(Roles::Supervisor) => true + +now <code>roles</code> behaves just like an array, so you can also do + + user = User.create(:roles => Roles::Admin) + user.roles << Roles::Supervisor + user.has_role?(Roles::Admin) => true + user.has_role?(Roles::Supervisor) => true + +== Using bitfields + +If you have an enum with many possible values you can switch from :yml to field_type :bitfield. + + class User < ActiveRecord + has_set :roles, :field_type => :bitfield + end + +Your db-column has to be an integer for field_type bitfield. If you use mysql with int(11) you are able to have up to 64 different values in your enumeration. + +== You do not need renum + +...but it really makes sense to use this library. If you really do not want to use it you have to implement against an interface. Here is a simple ruby module example to get the same results as above for has_enum: + + module Roles + class Admin; def self.name; "Admin"; end; end + class Supervisor; def self.name; "Supervisor"; end; end + class ContentManager; def self.name; "ContentManager"; end; end + end + +You cannot use this for <code>has_set</code> and <code>field_type :yml</code> since you cannot dump anonymous classes. But you can use <code>field_type :bitfield</code>. Then your class could look something like that: + + module Roles + class Admin + def self.bitfield_index; 1; end + end + class Supervisor + def self.bitfield_index; 2; end + end + class ContentManager + def self.bitfield_index; 3; end + end + class <<self + def values + Roles.constants.collect { |c| Roles.const_get(c) } + end + end + end + +As you can see, your classes have to respond to <code>bitfield_index</code> and your wrapping module has to respond to values and return all available classes. So now you could do: + + class User < ActiveRecord + has_enum :role, :field_type => :bitfield + end + == Note on Patches/Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. == Copyright Copyright (c) 2010 Galaxy Cats IT Consulting GmbH. See LICENSE for details.
galaxycats/haz_enum
a415eeb66f1bfdb16c714b2d6543a79a146e1f67
has_enum should also work without renum
diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index 81596c8..cab6dbf 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,73 +1,78 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Enum" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end it "should have has_<association>? method" do class_with_enum = ClassWithEnum.new(:product => "Silver") class_with_enum.has_product?(Products::Silver).should == true class_with_enum.has_product?(Products::Gold).should == false end it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end + it "should work without renum (just ruby module with classes)" do + role_enum = ClassWithEnum.new(:module_role => ModuleRoles::Admin) + role_enum.has_module_role?(ModuleRoles::Admin).should == true + end + after(:all) do teardown_db end end end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d249634..c529727 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,109 +1,117 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' require 'spec' require 'spec/autorun' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] +module ModuleRoles + class Admin; def self.name; "Admin"; end; end + class Supervisor; def self.name; "Supervisor"; end; end + class ContentManager; def self.name; "ContentManager"; end; end +end + module ModuleBitfieldRoles class Admin def self.bitfield_index; 1; end end class Supervisor def self.bitfield_index; 2; end end class ContentManager def self.bitfield_index; 3; end end class <<self def values - [Admin, Supervisor, ContentManager] + ModuleBitfieldRoles.constants.collect { |c| ModuleBitfieldRoles.const_get(c) } end end end setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product + has_enum :module_role end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end + has_set :module_roles has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base set_table_name "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards Spec::Runner.configure do |config| end
galaxycats/haz_enum
5e77b8b2fc726d485cfe9301f3bd3707b34b2c00
kicked no_renum example for has_set
diff --git a/spec/set_spec.rb b/spec/set_spec.rb index ad8ebea..3b57154 100644 --- a/spec/set_spec.rb +++ b/spec/set_spec.rb @@ -1,101 +1,91 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Set" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithSet.should respond_to(:has_set) end it "should be able to set set-values via hash in initializer" do ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User) ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) end it "should have empty array as default-value" do ClassWithSet.new.roles.should == [] end it "should have has_<association>? method" do class_with_enum = ClassWithSet.new(:roles => Roles::Admin) class_with_enum.has_role?(Roles::Admin).should == true class_with_enum.has_role?(Roles::User).should == false end it "should be able to save values as yml" do YmlSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) yml_set = YmlSet.create(:roles => [Roles::User, Roles::Admin]) yml_set.reload yml_set.roles[1].should be(Roles::Admin) end it "should not be able to set set-values by colum-name via hash in initializer" do lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error end it "colum_name should be configurable" do ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin) end it "should know if set-attribute has changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.roles_changed?.should be(true) roles_set.save roles_set.roles_changed?.should be(false) roles_set.roles = [Roles::Supervisor] roles_set.roles_changed?.should be(true) end it "should know if enum-attribute has not really changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles = [Roles::Admin] roles_set.roles_changed?.should be(false) end it "should be able to add set-value" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles << Roles::Supervisor roles_set.save roles_set.reload roles_set.has_role?(Roles::Admin).should == true roles_set.has_role?(Roles::Supervisor).should == true end it "should be able to define association methods" do extended = ClassWithSet.new(:extended_roles => [Roles::Admin, Roles::Supervisor, Roles::User]) extended.to_s.should == "Admin, Supervisor, User" end - it "should be able to work without renum" do - roles_set = ClassWithSet.new(:no_renum_roles => [NoRenumRoles.admin, NoRenumRoles.supervisor]) - roles_set.has_no_renum_role?(NoRenumRoles.admin).should == true - roles_set.has_no_renum_role?(NoRenumRoles.supervisor).should == true - roles_set.save - roles_set.reload - roles_set.has_no_renum_role?(NoRenumRoles.admin).should == true - roles_set.has_no_renum_role?(NoRenumRoles.supervisor).should == true - end - it "should be able to work without renum and bitfield" do roles_set = ClassWithSet.new(:module_bitfield_roles => [ModuleBitfieldRoles::Admin, ModuleBitfieldRoles::Supervisor]) roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Admin).should == true roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Supervisor).should == true roles_set.save roles_set.reload roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Admin).should == true roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Supervisor).should == true end after(:all) do teardown_db end end end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 71ae1ac..d249634 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,130 +1,109 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' require 'spec' require 'spec/autorun' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] -class NoRenumRoles - attr_accessor :name - def initialize(attributes) - attributes.symbolize_keys! - @name = attributes[:name] - end - def self.admin - self.new(:name => "Admin") - end - def self.supervisor - self.new(:name => "Supervisor") - end - def self.content_manager - self.new(:name => "ContentManager") - end - def ==(other) - self.name == other.name - end -end - module ModuleBitfieldRoles class Admin def self.bitfield_index; 1; end end class Supervisor def self.bitfield_index; 2; end end class ContentManager def self.bitfield_index; 3; end end class <<self def values [Admin, Supervisor, ContentManager] end end end setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end - has_set :no_renum_roles has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base set_table_name "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards Spec::Runner.configure do |config| end
galaxycats/haz_enum
5907a8ecaaceb5a21297f4e33c9020b6b1749c00
has_set should work without renum
diff --git a/spec/set_spec.rb b/spec/set_spec.rb index f3cbd77..ad8ebea 100644 --- a/spec/set_spec.rb +++ b/spec/set_spec.rb @@ -1,81 +1,101 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Set" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithSet.should respond_to(:has_set) end it "should be able to set set-values via hash in initializer" do ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User) ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) end it "should have empty array as default-value" do ClassWithSet.new.roles.should == [] end it "should have has_<association>? method" do class_with_enum = ClassWithSet.new(:roles => Roles::Admin) class_with_enum.has_role?(Roles::Admin).should == true class_with_enum.has_role?(Roles::User).should == false end it "should be able to save values as yml" do YmlSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) yml_set = YmlSet.create(:roles => [Roles::User, Roles::Admin]) yml_set.reload yml_set.roles[1].should be(Roles::Admin) end it "should not be able to set set-values by colum-name via hash in initializer" do lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error end it "colum_name should be configurable" do ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin) end it "should know if set-attribute has changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.roles_changed?.should be(true) roles_set.save roles_set.roles_changed?.should be(false) roles_set.roles = [Roles::Supervisor] roles_set.roles_changed?.should be(true) end it "should know if enum-attribute has not really changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles = [Roles::Admin] roles_set.roles_changed?.should be(false) end it "should be able to add set-value" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles << Roles::Supervisor roles_set.save roles_set.reload roles_set.has_role?(Roles::Admin).should == true roles_set.has_role?(Roles::Supervisor).should == true end it "should be able to define association methods" do extended = ClassWithSet.new(:extended_roles => [Roles::Admin, Roles::Supervisor, Roles::User]) extended.to_s.should == "Admin, Supervisor, User" end + it "should be able to work without renum" do + roles_set = ClassWithSet.new(:no_renum_roles => [NoRenumRoles.admin, NoRenumRoles.supervisor]) + roles_set.has_no_renum_role?(NoRenumRoles.admin).should == true + roles_set.has_no_renum_role?(NoRenumRoles.supervisor).should == true + roles_set.save + roles_set.reload + roles_set.has_no_renum_role?(NoRenumRoles.admin).should == true + roles_set.has_no_renum_role?(NoRenumRoles.supervisor).should == true + end + + it "should be able to work without renum and bitfield" do + roles_set = ClassWithSet.new(:module_bitfield_roles => [ModuleBitfieldRoles::Admin, ModuleBitfieldRoles::Supervisor]) + roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Admin).should == true + roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Supervisor).should == true + roles_set.save + roles_set.reload + roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Admin).should == true + roles_set.has_module_bitfield_role?(ModuleBitfieldRoles::Supervisor).should == true + end + after(:all) do teardown_db end end end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 555549f..71ae1ac 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,92 +1,130 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' require 'spec' require 'spec/autorun' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer t.column :roles_yml, :text t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] - enum :Roles, [:Admin, :Supervisor, :User] +class NoRenumRoles + attr_accessor :name + def initialize(attributes) + attributes.symbolize_keys! + @name = attributes[:name] + end + def self.admin + self.new(:name => "Admin") + end + def self.supervisor + self.new(:name => "Supervisor") + end + def self.content_manager + self.new(:name => "ContentManager") + end + def ==(other) + self.name == other.name + end +end + +module ModuleBitfieldRoles + class Admin + def self.bitfield_index; 1; end + end + class Supervisor + def self.bitfield_index; 2; end + end + class ContentManager + def self.bitfield_index; 3; end + end + class <<self + def values + [Admin, Supervisor, ContentManager] + end + end +end + setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end + has_set :no_renum_roles + has_set :module_bitfield_roles, :field_type => :bitfield end class YmlSet < ActiveRecord::Base set_table_name "class_with_sets" has_set :roles, :field_type => :yml end class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards Spec::Runner.configure do |config| end
galaxycats/haz_enum
2f496dc389ba9c5490458d8d409254e02a435679
added method available_field_types_for_sets
diff --git a/lib/haz_enum.rb b/lib/haz_enum.rb index 7fbe94d..563ee7b 100644 --- a/lib/haz_enum.rb +++ b/lib/haz_enum.rb @@ -1,8 +1,13 @@ require "haz_enum/enum" require "haz_enum/set" module HazEnum + class <<self + def available_field_types_for_sets + [:yml, :bitfield] + end + end end ActiveRecord::Base.extend HazEnum::Enum ActiveRecord::Base.extend HazEnum::Set \ No newline at end of file
galaxycats/haz_enum
8f8ce663cc99025df0555047e30f3ffbfbbcf3b6
changed default field_type to yml
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index c296c09..0798760 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,84 +1,84 @@ module HazEnum module Set def has_set(set_name, options={}) - field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" + field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "yml" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do instance_variable_get("@#{set_name}") || send("initialize_#{set_name}_from_#{field_type}") end define_method("#{set_name}=") do |value| value = [value].flatten value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) value.instance_variable_set("@separator", separator) class <<value define_method :human do self.collect do |enum| enum.respond_to?(:model_name) ? enum.model_name.human : enum.name end.join(@separator) end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = (YAML::load(self[set_column] || "--- \n") || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
f6f0932c5e5893f09e13f0db04df2188f1cd71ac
initialization/setting with no array (has_set)
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index b3e65f8..c296c09 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,83 +1,84 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do instance_variable_get("@#{set_name}") || send("initialize_#{set_name}_from_#{field_type}") end define_method("#{set_name}=") do |value| + value = [value].flatten value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) value.instance_variable_set("@separator", separator) class <<value define_method :human do self.collect do |enum| enum.respond_to?(:model_name) ? enum.model_name.human : enum.name end.join(@separator) end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = (YAML::load(self[set_column] || "--- \n") || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
adea78f9e215b1ca0e6291875d97f5c15631221c
new method has_<association>? for has_enum
diff --git a/lib/haz_enum/enum.rb b/lib/haz_enum/enum.rb index ebafc7e..167db06 100644 --- a/lib/haz_enum/enum.rb +++ b/lib/haz_enum/enum.rb @@ -1,47 +1,51 @@ module HazEnum module Enum def has_enum(enum_name, options={}) enum_name = enum_name.to_s enum_column = options.has_key?(:column_name) ? options[:column_name].to_s : enum_name enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.classify) : Object.const_get(enum_name.pluralize.camelize) self.attr_protected("#{enum_column}") if enum_name != enum_column self.validate "#{enum_column}_check_for_valid_enum_value" define_method "#{enum_name}" do begin return enum_class.const_get(self["#{enum_column}"]) if self["#{enum_column}"] return nil rescue NameError => e return nil end end define_method "#{enum_name}=" do |enum_to_set| if enum_to_set.respond_to?(:name) self["#{enum_column}"] = enum_to_set.name else self["#{enum_column}"] = enum_class.const_get(enum_to_set).name end end + define_method "has_#{enum_name}?" do |enum| + send(enum_name) == enum + end + define_method "#{enum_name}_changed?" do send("#{enum_column}_changed?") end if enum_name != enum_column define_method "#{enum_column}_check_for_valid_enum_value" do return true if self["#{enum_column}"].nil? begin enum_class.const_get(self["#{enum_column}"]) rescue NameError => e message = I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.attributes.#{enum_name}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate("activerecord.errors.models.#{self.class.name.underscore}.enum_value_invalid", :value => self["#{enum_column}"], :name => enum_name) || I18n.translate(:'activerecord.errors.messages.enum_value_invalid', :value => self["#{enum_column}"], :name => enum_name) self.errors.add(enum_name.to_sym, message) end end end end end \ No newline at end of file diff --git a/spec/enum_spec.rb b/spec/enum_spec.rb index e432e87..81596c8 100644 --- a/spec/enum_spec.rb +++ b/spec/enum_spec.rb @@ -1,67 +1,73 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Enum" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithEnum.should respond_to(:has_enum) end it "should be able to set enum-attribute via hash in initializer" do ClassWithEnum.new(:product => Products::Silver).product.should be(Products::Silver) ClassWithCustomNameEnum.new(:product => Products::Silver).product.should be(Products::Silver) end it "should be able to set enum-value as string in initializer" do ClassWithEnum.new(:product => "Silver").product.should be(Products::Silver) end + it "should have has_<association>? method" do + class_with_enum = ClassWithEnum.new(:product => "Silver") + class_with_enum.has_product?(Products::Silver).should == true + class_with_enum.has_product?(Products::Gold).should == false + end + it "should not be able to set enum-attribute by colum-name via hash in initializer" do ClassWithCustomNameEnum.new(:custom_name => Products::Silver).product.should_not be(Products::Silver) ClassWithCustomNameEnum.new(:custom_name => Products::Silver.name).product.should_not be(Products::Silver) end it "should have a enum_value attribute" do ClassWithCustomNameEnum.new(:product => Products::Gold).custom_name.should be(Products::Gold.name) end it "colum_name should be configurable" do ClassWithCustomNameEnum.new(:product => Products::Gold).product.should be(Products::Gold) end it "should know if enum-attribute has changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.product_changed?.should be(true) product_enum.save product_enum.product_changed?.should be(false) product_enum.product = Products::Gold product_enum.product_changed?.should be(true) end it "should know if enum-attribute has not really changed" do product_enum = ClassWithEnum.new(:product => Products::Silver) product_enum.save product_enum.product = Products::Silver product_enum.product_changed?.should be(false) end it "should validate enum-value" do enum_mixin = ClassWithEnum.new platin = "Platin" class <<platin; def name;"Platin";end;end enum_mixin.product = platin enum_mixin.valid?.should_not be(true) enum_mixin.errors[:product].size.should > 0 end after(:all) do teardown_db end end end \ No newline at end of file
galaxycats/haz_enum
11417fe209f379671ab2622dacebf6886297f65e
to_s is now called human
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index 3457b5b..b3e65f8 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,81 +1,83 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do instance_variable_get("@#{set_name}") || send("initialize_#{set_name}_from_#{field_type}") end define_method("#{set_name}=") do |value| value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) value.instance_variable_set("@separator", separator) class <<value - define_method :to_s do - self.join(@separator) + define_method :human do + self.collect do |enum| + enum.respond_to?(:model_name) ? enum.model_name.human : enum.name + end.join(@separator) end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = (YAML::load(self[set_column] || "--- \n") || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
cae27a6cf550cf80a26787675c8c3e3b8d9c15d1
regenerated gemspec
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 96a945b..be472fa 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,63 +1,63 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.4.2" + s.version = "0.4.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2010-06-29} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end
galaxycats/haz_enum
a5c93614497f0056e3e0bc72ef633664fe8a2620
Version bump to 0.4.3
diff --git a/VERSION b/VERSION index 2b7c5ae..17b2ccd 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.2 +0.4.3
galaxycats/haz_enum
7d31b589b59a9af6beeb624832c3bee30b369ed1
fixed default-value
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index 95241ee..3457b5b 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,81 +1,81 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do instance_variable_get("@#{set_name}") || send("initialize_#{set_name}_from_#{field_type}") end define_method("#{set_name}=") do |value| value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) value.instance_variable_set("@separator", separator) class <<value define_method :to_s do self.join(@separator) end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do - deserialized_value = (YAML::load(self[set_column]) || []) + deserialized_value = (YAML::load(self[set_column] || "--- \n") || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file diff --git a/spec/set_spec.rb b/spec/set_spec.rb index 0d6c6a5..9b8dcfd 100644 --- a/spec/set_spec.rb +++ b/spec/set_spec.rb @@ -1,71 +1,75 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Set" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithSet.should respond_to(:has_set) end it "should be able to set set-values via hash in initializer" do ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User) ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) end + it "should have empty array as default-value" do + ClassWithSet.new.roles.should == [] + end + it "should be able to save values as yml" do YmlSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) yml_set = YmlSet.create(:roles => [Roles::User, Roles::Admin]) yml_set.reload yml_set.roles[1].should be(Roles::Admin) end it "should not be able to set set-values by colum-name via hash in initializer" do lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error end it "colum_name should be configurable" do ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin) end it "should know if set-attribute has changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.roles_changed?.should be(true) roles_set.save roles_set.roles_changed?.should be(false) roles_set.roles = [Roles::Supervisor] roles_set.roles_changed?.should be(true) end it "should know if enum-attribute has not really changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles = [Roles::Admin] roles_set.roles_changed?.should be(false) end it "should be able to add set-value" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles << Roles::Supervisor roles_set.save roles_set.reload roles_set.has_role?(Roles::Admin).should == true roles_set.has_role?(Roles::Supervisor).should == true end it "should be able to define association methods" do extended = ClassWithSet.new(:extended_roles => [Roles::Admin, Roles::Supervisor, Roles::User]) extended.to_s.should == "Admin, Supervisor, User" end after(:all) do teardown_db end end end \ No newline at end of file
galaxycats/haz_enum
5700609613c5b3a87f7136ef9fcf49aa22938d6c
Version bump to 0.4.2
diff --git a/VERSION b/VERSION index 267577d..2b7c5ae 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.1 +0.4.2 diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 4b6dd48..96a945b 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,63 +1,63 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.4.1" + s.version = "0.4.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2010-06-29} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index 50c5ed5..95241ee 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,81 +1,81 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do - instance_variable_get("@#{set_name}") || "initialize_#{set_name}_from_#{field_type}" + instance_variable_get("@#{set_name}") || send("initialize_#{set_name}_from_#{field_type}") end define_method("#{set_name}=") do |value| value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) value.instance_variable_set("@separator", separator) class <<value define_method :to_s do self.join(@separator) end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = (YAML::load(self[set_column]) || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
fffc04726966baf72689639a113373036eff50ef
Version bump to 0.4.1
diff --git a/VERSION b/VERSION index 1d0ba9e..267577d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.0 +0.4.1
galaxycats/haz_enum
74f2a340707d8caffa2a06244ea195c09d350d8d
to_s with separator defined
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index 9c6b6a5..50c5ed5 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,79 +1,81 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize + separator = options.has_key?(:separator) ? options[:separator].to_s : ", " after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do - instance_variable_get("@#{set_name}") || instance_variable_set("@#{set_name}", []) + instance_variable_get("@#{set_name}") || "initialize_#{set_name}_from_#{field_type}" end define_method("#{set_name}=") do |value| - value.constantize rescue value if value.is_a?(String) + value.collect! { |val| val.is_a?(String) ? val.constantize : val }.compact! if value.is_a?(Array) + value.instance_variable_set("@separator", separator) class <<value + define_method :to_s do + self.join(@separator) + end yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 - if send(set_name) + unless send(set_name).blank? send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 + send("#{set_name}=", []) end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do - deserialized_value = unless self[set_column].is_a?(String) && self[set_column] =~ /^---/ - self[set_column] - else - (YAML::load(self[set_column]) || []) rescue self[set_column] - end + deserialized_value = (YAML::load(self[set_column]) || []) send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
212aa024ac38c3532e0322c24b4d8f2ce3380276
strings in setter will be constantized
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index a7713bb..9c6b6a5 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,78 +1,79 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do instance_variable_get("@#{set_name}") || instance_variable_set("@#{set_name}", []) end define_method("#{set_name}=") do |value| + value.constantize rescue value if value.is_a?(String) class <<value yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 if send(set_name) send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = unless self[set_column].is_a?(String) && self[set_column] =~ /^---/ self[set_column] else (YAML::load(self[set_column]) || []) rescue self[set_column] end send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
810b7f1db9ad608ece635cd27b0e469c0f1e8d86
default to [] for has_set if nil
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index b6c0afe..a7713bb 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,78 +1,78 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do - instance_variable_get("@#{set_name}") + instance_variable_get("@#{set_name}") || instance_variable_set("@#{set_name}", []) end define_method("#{set_name}=") do |value| class <<value yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 if send(set_name) send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = unless self[set_column].is_a?(String) && self[set_column] =~ /^---/ self[set_column] else (YAML::load(self[set_column]) || []) rescue self[set_column] end send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
a5d93ff784f33713949001aa69a8b1ffe9fcd422
use haz_enum 0.4.0
diff --git a/haz_enum.gemspec b/haz_enum.gemspec index f2134b2..b826e08 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,62 +1,63 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} s.version = "0.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] s.date = %q{2010-06-28} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", + "CHANGESET", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end
galaxycats/haz_enum
1dd85829257fb52cd580f43fc32cbf5273c70ead
build 0.4.0 gem
diff --git a/CHANGESET b/CHANGESET new file mode 100644 index 0000000..4c00f59 --- /dev/null +++ b/CHANGESET @@ -0,0 +1,2 @@ +- 0.4.0 [2001-06-28] + * you can now use :yml instead of :bitfield as field_type \ No newline at end of file diff --git a/haz_enum.gemspec b/haz_enum.gemspec index 767e602..f2134b2 100644 --- a/haz_enum.gemspec +++ b/haz_enum.gemspec @@ -1,62 +1,62 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{haz_enum} - s.version = "0.3.0" + s.version = "0.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["thyphoon"] - s.date = %q{2010-06-15} + s.date = %q{2010-06-28} s.description = %q{use has_set and has_enum in your ActiveRecord models if you want to have one (has_enum) value from a defined enumeration or more (has_set))} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "haz_enum.gemspec", "lib/haz_enum.rb", "lib/haz_enum/enum.rb", "lib/haz_enum/set.rb", "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/galaxycats/haz_enum} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{has_set and has_enum for ActiveRecord} s.test_files = [ "spec/enum_spec.rb", "spec/set_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<activerecord>, [">= 3.0.0.beta3"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index bf1e398..b6c0afe 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,78 +1,78 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize after_find "initialize_#{set_name}_from_#{field_type}" before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do - instance_variable_get("@#{set_name}") || [] + instance_variable_get("@#{set_name}") end define_method("#{set_name}=") do |value| class <<value yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end if field_type == "bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 if send(set_name) send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 end end elsif field_type == "yml" define_method("convert_#{set_name}_to_yml") do self[set_column] = YAML::dump(send(set_name)) end define_method("initialize_#{set_name}_from_yml") do deserialized_value = unless self[set_column].is_a?(String) && self[set_column] =~ /^---/ self[set_column] else - YAML::load(self[set_column]) rescue self[set_column] + (YAML::load(self[set_column]) || []) rescue self[set_column] end send("#{set_name}=", deserialized_value) end end end end end \ No newline at end of file
galaxycats/haz_enum
f4b829ddf1cb8ba18a3ec8eb5332f8cbcd25aaee
Version bump to 0.4.0
diff --git a/VERSION b/VERSION index 0d91a54..1d0ba9e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.3.0 +0.4.0
galaxycats/haz_enum
b05cb27b484df79aa09bb7d50ca829c6b43757d2
you can now have the field_type :yml
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index ae5fb97..bf1e398 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,59 +1,78 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize - after_find "initialize_#{set_name}_from_bitfield" - before_save "convert_#{set_name}_to_bitfield" - - enum_class.class_eval do - def bitfield_index - index + 1 - end - end unless enum_class.method_defined?(:bitfield_index) + after_find "initialize_#{set_name}_from_#{field_type}" + before_save "convert_#{set_name}_to_#{field_type}" define_method("#{set_name}") do - instance_variable_get("@#{set_name}") + instance_variable_get("@#{set_name}") || [] end define_method("#{set_name}=") do |value| class <<value yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do - send("convert_#{set_name}_to_bitfield") + send("convert_#{set_name}_to_#{field_type}") send("#{set_column}_changed?") end - define_method("convert_#{set_name}_to_bitfield") do - self[set_column] = 0 - if send(set_name) - send(set_name).each do |element| - 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index + if field_type == "bitfield" + + enum_class.class_eval do + def bitfield_index + index + 1 + end + end unless enum_class.method_defined?(:bitfield_index) + + define_method("convert_#{set_name}_to_bitfield") do + self[set_column] = 0 + if send(set_name) + send(set_name).each do |element| + 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index + end end end - end - define_method("initialize_#{set_name}_from_bitfield") do - if self[set_column] - set_elements = enum_class.values.collect do |enum_element| - enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) - end.compact - send("#{set_name}=", set_elements) - else - self[set_column] = 0 + define_method("initialize_#{set_name}_from_bitfield") do + if self[set_column] + set_elements = enum_class.values.collect do |enum_element| + enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) + end.compact + send("#{set_name}=", set_elements) + else + self[set_column] = 0 + end + end + + elsif field_type == "yml" + + define_method("convert_#{set_name}_to_yml") do + self[set_column] = YAML::dump(send(set_name)) + end + + define_method("initialize_#{set_name}_from_yml") do + deserialized_value = unless self[set_column].is_a?(String) && self[set_column] =~ /^---/ + self[set_column] + else + YAML::load(self[set_column]) rescue self[set_column] + end + send("#{set_name}=", deserialized_value) end + end end end end \ No newline at end of file diff --git a/spec/set_spec.rb b/spec/set_spec.rb index 5fe79e7..0d6c6a5 100644 --- a/spec/set_spec.rb +++ b/spec/set_spec.rb @@ -1,64 +1,71 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "HazEnum" do describe "Set" do before(:all) do setup_db end it "should have class method has_enum" do ClassWithSet.should respond_to(:has_set) end it "should be able to set set-values via hash in initializer" do ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[0].should be(Roles::User) ClassWithSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) end + it "should be able to save values as yml" do + YmlSet.new(:roles => [Roles::User, Roles::Admin]).roles[1].should be(Roles::Admin) + yml_set = YmlSet.create(:roles => [Roles::User, Roles::Admin]) + yml_set.reload + yml_set.roles[1].should be(Roles::Admin) + end + it "should not be able to set set-values by colum-name via hash in initializer" do lambda { ClassWithEnum.new(:roles_bitfield => 3) }.should raise_error end it "colum_name should be configurable" do ClassWithCustomNameSet.new(:roles => [Roles::Admin]).roles.first.should be(Roles::Admin) end it "should know if set-attribute has changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.roles_changed?.should be(true) roles_set.save roles_set.roles_changed?.should be(false) roles_set.roles = [Roles::Supervisor] roles_set.roles_changed?.should be(true) end it "should know if enum-attribute has not really changed" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles = [Roles::Admin] roles_set.roles_changed?.should be(false) end it "should be able to add set-value" do roles_set = ClassWithSet.new(:roles => [Roles::Admin]) roles_set.save roles_set.roles << Roles::Supervisor roles_set.save roles_set.reload roles_set.has_role?(Roles::Admin).should == true roles_set.has_role?(Roles::Supervisor).should == true end it "should be able to define association methods" do extended = ClassWithSet.new(:extended_roles => [Roles::Admin, Roles::Supervisor, Roles::User]) extended.to_s.should == "Admin, Supervisor, User" end after(:all) do teardown_db end end end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 7b352e7..555549f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,86 +1,92 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require "rubygems" require "active_record" require 'renum' require 'haz_enum' require 'spec' require 'spec/autorun' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false def setup_db ActiveRecord::Base.silence do ActiveRecord::Schema.define(:version => 1) do create_table :class_with_enums do |t| t.column :title, :string t.column :product, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_enums do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_sets do |t| t.column :title, :string t.column :roles_bitfield, :integer + t.column :roles_yml, :text t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :class_with_custom_name_sets do |t| t.column :title, :string t.column :custom_name, :string t.column :created_at, :datetime t.column :updated_at, :datetime end end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end enum :Fakes, [:NOT_DEFINIED] enum :Products, [:Silver, :Gold, :Titanium] enum :Roles, [:Admin, :Supervisor, :User] setup_db # Init the database for class creation class ClassWithEnum < ActiveRecord::Base has_enum :product end class ClassWithCustomNameEnum < ActiveRecord::Base has_enum :product, :column_name => :custom_name end class ClassWithSet < ActiveRecord::Base has_set :roles has_set :extended_roles, :class_name => :roles do def to_s extended_roles.collect(&:name).join(", ") end end end +class YmlSet < ActiveRecord::Base + set_table_name "class_with_sets" + has_set :roles, :field_type => :yml +end + class ClassWithCustomNameSet < ActiveRecord::Base has_set :roles, :column_name => :custom_name end teardown_db # And drop them right afterwards Spec::Runner.configure do |config| end
galaxycats/haz_enum
4f065f897e91204ee259933fff5ab66eee8ba542
use constantize instead of const_get
diff --git a/lib/haz_enum/set.rb b/lib/haz_enum/set.rb index 30f456f..ae5fb97 100644 --- a/lib/haz_enum/set.rb +++ b/lib/haz_enum/set.rb @@ -1,59 +1,59 @@ module HazEnum module Set def has_set(set_name, options={}) field_type = options.has_key?(:field_type) ? options[:field_type].to_s : "bitfield" set_column = options.has_key?(:column_name) ? options[:column_name].to_s : "#{set_name}_#{field_type}" - enum_class = options.has_key?(:class_name) ? Object.const_get(options[:class_name].to_s.camelize) : Object.const_get(set_name.to_s.camelize) + enum_class = options.has_key?(:class_name) ? options[:class_name].to_s.camelize.constantize : set_name.to_s.camelize.constantize after_find "initialize_#{set_name}_from_bitfield" before_save "convert_#{set_name}_to_bitfield" enum_class.class_eval do def bitfield_index index + 1 end end unless enum_class.method_defined?(:bitfield_index) define_method("#{set_name}") do instance_variable_get("@#{set_name}") end define_method("#{set_name}=") do |value| class <<value yield if block_given? end instance_variable_set("@#{set_name}", value) end define_method("has_#{set_name.to_s.singularize}?") do |set_value| send(set_name).include?(set_value) end define_method("#{set_name}_changed?") do send("convert_#{set_name}_to_bitfield") send("#{set_column}_changed?") end define_method("convert_#{set_name}_to_bitfield") do self[set_column] = 0 if send(set_name) send(set_name).each do |element| 2**element.bitfield_index & self[set_column] == 2**element.bitfield_index ? next : self[set_column] += 2**element.bitfield_index end end end define_method("initialize_#{set_name}_from_bitfield") do if self[set_column] set_elements = enum_class.values.collect do |enum_element| enum_element if ((2**enum_element.bitfield_index & self[set_column]) == 2**enum_element.bitfield_index) end.compact send("#{set_name}=", set_elements) else self[set_column] = 0 end end end end end \ No newline at end of file
galaxycats/haz_enum
e116f8cb97b95301a2beecca086997f89580a502
Version bump to 0.3.0
diff --git a/VERSION b/VERSION index 0ea3a94..0d91a54 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0