From f86e39c7bd447720b385d2da901694a30cfbdbe5 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Wed, 31 May 2017 22:45:56 -0700 Subject: pbot: new primitive gif filter bot --- tg/pbot/main.go | 139 + tg/pbot/puush.go | 93 + tg/pbot/vendor-log | 22 + tg/pbot/vendor/github.com/Xe/uuid/dce.go | 84 + tg/pbot/vendor/github.com/Xe/uuid/doc.go | 8 + tg/pbot/vendor/github.com/Xe/uuid/hash.go | 53 + tg/pbot/vendor/github.com/Xe/uuid/node.go | 101 + tg/pbot/vendor/github.com/Xe/uuid/time.go | 132 + tg/pbot/vendor/github.com/Xe/uuid/util.go | 43 + tg/pbot/vendor/github.com/Xe/uuid/uuid.go | 163 + tg/pbot/vendor/github.com/Xe/uuid/version1.go | 41 + tg/pbot/vendor/github.com/Xe/uuid/version4.go | 25 + tg/pbot/vendor/github.com/fogleman/gg/bezier.go | 59 + tg/pbot/vendor/github.com/fogleman/gg/context.go | 795 +++ tg/pbot/vendor/github.com/fogleman/gg/gradient.go | 202 + tg/pbot/vendor/github.com/fogleman/gg/matrix.go | 88 + tg/pbot/vendor/github.com/fogleman/gg/path.go | 140 + tg/pbot/vendor/github.com/fogleman/gg/pattern.go | 123 + tg/pbot/vendor/github.com/fogleman/gg/point.go | 25 + tg/pbot/vendor/github.com/fogleman/gg/util.go | 117 + tg/pbot/vendor/github.com/fogleman/gg/wrap.go | 58 + .../fogleman/primitive/primitive/color.go | 44 + .../fogleman/primitive/primitive/core.go | 124 + .../fogleman/primitive/primitive/ellipse.go | 179 + .../fogleman/primitive/primitive/heatmap.go | 59 + .../github.com/fogleman/primitive/primitive/log.go | 23 + .../fogleman/primitive/primitive/model.go | 174 + .../fogleman/primitive/primitive/optimize.go | 75 + .../fogleman/primitive/primitive/polygon.go | 111 + .../fogleman/primitive/primitive/quadratic.go | 100 + .../fogleman/primitive/primitive/raster.go | 46 + .../fogleman/primitive/primitive/rectangle.go | 198 + .../fogleman/primitive/primitive/scanline.go | 29 + .../fogleman/primitive/primitive/shape.go | 25 + .../fogleman/primitive/primitive/state.go | 48 + .../fogleman/primitive/primitive/triangle.go | 171 + .../fogleman/primitive/primitive/util.go | 195 + .../fogleman/primitive/primitive/worker.go | 108 + .../github.com/golang/freetype/raster/geom.go | 245 + .../github.com/golang/freetype/raster/paint.go | 287 + .../github.com/golang/freetype/raster/raster.go | 601 ++ .../github.com/golang/freetype/raster/stroke.go | 483 ++ .../github.com/golang/freetype/truetype/face.go | 507 ++ .../github.com/golang/freetype/truetype/glyph.go | 522 ++ .../github.com/golang/freetype/truetype/hint.go | 1770 ++++++ .../github.com/golang/freetype/truetype/opcodes.go | 289 + .../golang/freetype/truetype/truetype.go | 653 ++ .../github.com/hullerob/go.farbfeld/farbfeld.go | 96 + .../github.com/joho/godotenv/autoload/autoload.go | 15 + .../vendor/github.com/joho/godotenv/godotenv.go | 247 + .../multipartstreamer/multipartstreamer.go | 101 + tg/pbot/vendor/golang.org/x/image/bmp/reader.go | 199 + tg/pbot/vendor/golang.org/x/image/bmp/writer.go | 166 + tg/pbot/vendor/golang.org/x/image/draw/draw.go | 43 + tg/pbot/vendor/golang.org/x/image/draw/gen.go | 1403 ++++ tg/pbot/vendor/golang.org/x/image/draw/go1_8.go | 49 + tg/pbot/vendor/golang.org/x/image/draw/go1_9.go | 57 + tg/pbot/vendor/golang.org/x/image/draw/impl.go | 6668 ++++++++++++++++++++ tg/pbot/vendor/golang.org/x/image/draw/scale.go | 527 ++ .../vendor/golang.org/x/image/draw/stdlib_test.go | 96 + .../golang.org/x/image/font/basicfont/basicfont.go | 126 + .../golang.org/x/image/font/basicfont/data.go | 1456 +++++ .../golang.org/x/image/font/basicfont/gen.go | 115 + tg/pbot/vendor/golang.org/x/image/font/font.go | 359 ++ tg/pbot/vendor/golang.org/x/image/math/f64/f64.go | 37 + .../vendor/golang.org/x/image/math/fixed/fixed.go | 410 ++ tg/pbot/vendor/golang.org/x/image/riff/riff.go | 193 + tg/pbot/vendor/golang.org/x/image/tiff/buffer.go | 69 + tg/pbot/vendor/golang.org/x/image/tiff/compress.go | 58 + tg/pbot/vendor/golang.org/x/image/tiff/consts.go | 133 + .../vendor/golang.org/x/image/tiff/lzw/reader.go | 272 + tg/pbot/vendor/golang.org/x/image/tiff/reader.go | 681 ++ tg/pbot/vendor/golang.org/x/image/tiff/writer.go | 438 ++ tg/pbot/vendor/golang.org/x/image/vp8/decode.go | 403 ++ tg/pbot/vendor/golang.org/x/image/vp8/filter.go | 273 + tg/pbot/vendor/golang.org/x/image/vp8/idct.go | 98 + tg/pbot/vendor/golang.org/x/image/vp8/partition.go | 129 + tg/pbot/vendor/golang.org/x/image/vp8/pred.go | 201 + tg/pbot/vendor/golang.org/x/image/vp8/predfunc.go | 553 ++ tg/pbot/vendor/golang.org/x/image/vp8/quant.go | 98 + .../vendor/golang.org/x/image/vp8/reconstruct.go | 442 ++ tg/pbot/vendor/golang.org/x/image/vp8/token.go | 381 ++ tg/pbot/vendor/golang.org/x/image/vp8l/decode.go | 603 ++ tg/pbot/vendor/golang.org/x/image/vp8l/huffman.go | 245 + .../vendor/golang.org/x/image/vp8l/transform.go | 299 + tg/pbot/vendor/golang.org/x/image/webp/decode.go | 272 + tg/pbot/vendor/golang.org/x/image/webp/webp.go | 30 + tg/pbot/vendor/gopkg.in/telegram-bot-api.v4/bot.go | 695 ++ .../vendor/gopkg.in/telegram-bot-api.v4/configs.go | 789 +++ .../vendor/gopkg.in/telegram-bot-api.v4/helpers.go | 611 ++ .../vendor/gopkg.in/telegram-bot-api.v4/types.go | 627 ++ 91 files changed, 30340 insertions(+) create mode 100644 tg/pbot/main.go create mode 100644 tg/pbot/puush.go create mode 100644 tg/pbot/vendor-log create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/dce.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/doc.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/hash.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/node.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/time.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/util.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/uuid.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/version1.go create mode 100644 tg/pbot/vendor/github.com/Xe/uuid/version4.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/bezier.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/context.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/gradient.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/matrix.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/path.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/pattern.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/point.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/util.go create mode 100644 tg/pbot/vendor/github.com/fogleman/gg/wrap.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/color.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/core.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/ellipse.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/heatmap.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/log.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/model.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/optimize.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/polygon.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/quadratic.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/raster.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/rectangle.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/scanline.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/shape.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/state.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/triangle.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/util.go create mode 100644 tg/pbot/vendor/github.com/fogleman/primitive/primitive/worker.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/raster/geom.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/raster/paint.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/raster/raster.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/raster/stroke.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/truetype/face.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/truetype/glyph.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/truetype/hint.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/truetype/opcodes.go create mode 100644 tg/pbot/vendor/github.com/golang/freetype/truetype/truetype.go create mode 100644 tg/pbot/vendor/github.com/hullerob/go.farbfeld/farbfeld.go create mode 100644 tg/pbot/vendor/github.com/joho/godotenv/autoload/autoload.go create mode 100644 tg/pbot/vendor/github.com/joho/godotenv/godotenv.go create mode 100644 tg/pbot/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go create mode 100644 tg/pbot/vendor/golang.org/x/image/bmp/reader.go create mode 100644 tg/pbot/vendor/golang.org/x/image/bmp/writer.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/draw.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/gen.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/go1_8.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/go1_9.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/impl.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/scale.go create mode 100644 tg/pbot/vendor/golang.org/x/image/draw/stdlib_test.go create mode 100644 tg/pbot/vendor/golang.org/x/image/font/basicfont/basicfont.go create mode 100644 tg/pbot/vendor/golang.org/x/image/font/basicfont/data.go create mode 100644 tg/pbot/vendor/golang.org/x/image/font/basicfont/gen.go create mode 100644 tg/pbot/vendor/golang.org/x/image/font/font.go create mode 100644 tg/pbot/vendor/golang.org/x/image/math/f64/f64.go create mode 100644 tg/pbot/vendor/golang.org/x/image/math/fixed/fixed.go create mode 100644 tg/pbot/vendor/golang.org/x/image/riff/riff.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/buffer.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/compress.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/consts.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/lzw/reader.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/reader.go create mode 100644 tg/pbot/vendor/golang.org/x/image/tiff/writer.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/decode.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/filter.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/idct.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/partition.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/pred.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/predfunc.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/quant.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/reconstruct.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8/token.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8l/decode.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8l/huffman.go create mode 100644 tg/pbot/vendor/golang.org/x/image/vp8l/transform.go create mode 100644 tg/pbot/vendor/golang.org/x/image/webp/decode.go create mode 100644 tg/pbot/vendor/golang.org/x/image/webp/webp.go create mode 100644 tg/pbot/vendor/gopkg.in/telegram-bot-api.v4/bot.go create mode 100644 tg/pbot/vendor/gopkg.in/telegram-bot-api.v4/configs.go create mode 100644 tg/pbot/vendor/gopkg.in/telegram-bot-api.v4/helpers.go create mode 100644 tg/pbot/vendor/gopkg.in/telegram-bot-api.v4/types.go diff --git a/tg/pbot/main.go b/tg/pbot/main.go new file mode 100644 index 0000000..00a342d --- /dev/null +++ b/tg/pbot/main.go @@ -0,0 +1,139 @@ +package main + +import ( + "fmt" + "image" + "log" + "net/http" + "os" + "runtime" + "time" + + "github.com/Xe/uuid" + "github.com/fogleman/primitive/primitive" + _ "github.com/joho/godotenv/autoload" + "gopkg.in/telegram-bot-api.v4" + + // image formats + _ "image/jpeg" + _ "image/png" + + _ "github.com/hullerob/go.farbfeld" + _ "golang.org/x/image/bmp" + _ "golang.org/x/image/tiff" + _ "golang.org/x/image/webp" +) + +func main() { + bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_TOKEN")) + if err != nil { + log.Panic(err) + } + + ps, ok := puushLogin(os.Getenv("PUUSH_KEY")) + if !ok { + log.Fatal("puush login failed") + } + + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + + updates, err := bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message == nil { + continue + } + + err := renderImg(bot, ps, update) + if err != nil { + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "error: "+err.Error()) + log.Printf("error in processing message from %s: %v", update.Message.From.String(), err) + bot.Send(msg) + } + } +} + +func stepImg(img image.Image, count int) image.Image { + bg := primitive.MakeColor(primitive.AverageImageColor(img)) + model := primitive.NewModel(img, bg, 512, runtime.NumCPU()) + + for range make([]struct{}, count) { + model.Step(primitive.ShapeTypeTriangle, 128, 0) + } + + return model.Context.Image() +} + +func renderImg(bot *tgbotapi.BotAPI, ps string, update tgbotapi.Update) error { + msg := update.Message + + // ignore chats without photos + if len(*msg.Photo) == 0 { + return nil + } + + p := *msg.Photo + pho := p[len(p)-1] + fu, err := bot.GetFileDirectURL(pho.FileID) + if err != nil { + return err + } + + resp, err := http.Get(fu) + if err != nil { + return err + } + defer resp.Body.Close() + + img, ifmt, err := image.Decode(resp.Body) + if err != nil { + return err + } + + log.Printf("%s: image id %s loaded (%s)", msg.From, pho.FileID, ifmt) + umsg := tgbotapi.NewMessage(update.Message.Chat.ID, "rendering... (may take a while)") + bot.Send(umsg) + + before := time.Now() + imgs := []image.Image{} + + for i := range make([]struct{}, 10) { + log.Printf("%s: starting frame render", msg.From) + imgs = append(imgs, stepImg(img, 150)) + log.Printf("%s: frame rendered", msg.From) + + umsg = tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("frame %d/10 rendered", i+1)) + bot.Send(umsg) + } + + gpath := "./var/" + update.Message.From.String() + ".gif" + err = primitive.SaveGIFImageMagick(gpath, imgs, 15, 15) + if err != nil { + return err + } + + after := time.Now().Sub(before) + + buf, err := os.Open(gpath) + if err != nil { + return err + } + defer os.Remove(gpath) + + umsg = tgbotapi.NewMessage(update.Message.Chat.ID, "uploading (took "+after.String()+" to render)") + bot.Send(umsg) + + furl, err := puush(ps, uuid.New()+".gif", buf) + if err != nil { + return err + } + + omsg := tgbotapi.NewMessage(update.Message.Chat.ID, furl.String()) + _, err = bot.Send(omsg) + if err != nil { + return err + } + + return nil +} diff --git a/tg/pbot/puush.go b/tg/pbot/puush.go new file mode 100644 index 0000000..259cb56 --- /dev/null +++ b/tg/pbot/puush.go @@ -0,0 +1,93 @@ +package main + +import ( + "bytes" + "crypto/md5" + "errors" + "fmt" + "io" + "io/ioutil" + "mime/multipart" + "net/http" + "net/url" + "strings" +) + +// Puush constants +const ( + PuushBase = "https://puush.me/api/" + PuushAuthURL = "https://puush.me/api/auth/" + PuushUploadURL = "https://puush.me/api/up/" +) + +func puushLogin(key string) (string, bool) { + r, err := http.PostForm(PuushAuthURL, url.Values{"k": {key}}) + if err != nil { + fmt.Println(err) + return "", false + } + body, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + info := strings.Split(string(body), ",") + if info[0] == "-1" { + return "", false + } + + session := info[1] + return session, true +} + +func puush(session, fname string, fin io.Reader) (*url.URL, error) { + buf := new(bytes.Buffer) + w := multipart.NewWriter(buf) + kwriter, err := w.CreateFormField("k") + if err != nil { + return nil, err + } + + io.WriteString(kwriter, session) + + file, _ := ioutil.ReadAll(fin) + + h := md5.New() + h.Write(file) + + cwriter, err := w.CreateFormField("c") + if err != nil { + return nil, err + } + io.WriteString(cwriter, fmt.Sprintf("%x", h.Sum(nil))) + + zwriter, err := w.CreateFormField("z") + if err != nil { + return nil, err + } + io.WriteString(zwriter, "poop") // They must think their protocol is shit + + fwriter, err := w.CreateFormFile("f", fname) + if err != nil { + return nil, err + } + fwriter.Write(file) + + w.Close() + + req, err := http.NewRequest("POST", "http://puush.me/api/up", buf) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", w.FormDataContentType()) + client := &http.Client{} + res, err := client.Do(req) + if err != nil { + return nil, err + } + body, _ := ioutil.ReadAll(res.Body) + res.Body.Close() + info := strings.Split(string(body), ",") + if info[0] == "0" { + return url.Parse(info[1]) + } + + return nil, errors.New("upload failed") +} diff --git a/tg/pbot/vendor-log b/tg/pbot/vendor-log new file mode 100644 index 0000000..1fe2451 --- /dev/null +++ b/tg/pbot/vendor-log @@ -0,0 +1,22 @@ +62b230097e9c9534ca2074782b25d738c4b68964 (dirty) github.com/Xe/uuid +ee8994ff90057955c428a5a949da5d064bf3ce6b github.com/fogleman/gg +80f39ceaa8f4c66acb28aba6abe6b15128c06113 github.com/fogleman/primitive/primitive +bcfeb16b74e8aea9e2fe043406f2ef74b1cb0759 github.com/golang/freetype/raster +bcfeb16b74e8aea9e2fe043406f2ef74b1cb0759 github.com/golang/freetype/truetype +b572f0728b691aae4256edb2e408279146eafe52 github.com/hullerob/go.farbfeld +325433c502d409f3c3dc820098fb0cfe38d98dc7 github.com/joho/godotenv +325433c502d409f3c3dc820098fb0cfe38d98dc7 github.com/joho/godotenv/autoload +a90a01d73ae432e2611d178c18367fbaa13e0154 github.com/technoweenie/multipartstreamer +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/bmp +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/draw +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/font +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/font/basicfont +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/math/f64 +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/math/fixed +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/riff +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/tiff +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/tiff/lzw +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/vp8 +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/vp8l +426cfd8eeb6e08ab1932954e09e3c2cb2bc6e36d golang.org/x/image/webp +0a57807db79efce7f6719fbb2c0e0f83fda79aec (dirty) gopkg.in/telegram-bot-api.v4 diff --git a/tg/pbot/vendor/github.com/Xe/uuid/dce.go b/tg/pbot/vendor/github.com/Xe/uuid/dce.go new file mode 100644 index 0000000..50a0f2d --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/dce.go @@ -0,0 +1,84 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "fmt" + "os" +) + +// A Domain represents a Version 2 domain +type Domain byte + +// Domain constants for DCE Security (Version 2) UUIDs. +const ( + Person = Domain(0) + Group = Domain(1) + Org = Domain(2) +) + +// NewDCESecurity returns a DCE Security (Version 2) UUID. +// +// The domain should be one of Person, Group or Org. +// On a POSIX system the id should be the users UID for the Person +// domain and the users GID for the Group. The meaning of id for +// the domain Org or on non-POSIX systems is site defined. +// +// For a given domain/id pair the same token may be returned for up to +// 7 minutes and 10 seconds. +func NewDCESecurity(domain Domain, id uint32) UUID { + uuid := NewUUID() + if uuid != nil { + uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 + uuid[9] = byte(domain) + binary.BigEndian.PutUint32(uuid[0:], id) + } + return uuid +} + +// NewDCEPerson returns a DCE Security (Version 2) UUID in the person +// domain with the id returned by os.Getuid. +// +// NewDCEPerson(Person, uint32(os.Getuid())) +func NewDCEPerson() UUID { + return NewDCESecurity(Person, uint32(os.Getuid())) +} + +// NewDCEGroup returns a DCE Security (Version 2) UUID in the group +// domain with the id returned by os.Getgid. +// +// NewDCEGroup(Group, uint32(os.Getgid())) +func NewDCEGroup() UUID { + return NewDCESecurity(Group, uint32(os.Getgid())) +} + +// Domain returns the domain for a Version 2 UUID or false. +func (uuid UUID) Domain() (Domain, bool) { + if v, _ := uuid.Version(); v != 2 { + return 0, false + } + return Domain(uuid[9]), true +} + +// Id returns the id for a Version 2 UUID or false. +func (uuid UUID) Id() (uint32, bool) { + if v, _ := uuid.Version(); v != 2 { + return 0, false + } + return binary.BigEndian.Uint32(uuid[0:4]), true +} + +func (d Domain) String() string { + switch d { + case Person: + return "Person" + case Group: + return "Group" + case Org: + return "Org" + } + return fmt.Sprintf("Domain%d", int(d)) +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/doc.go b/tg/pbot/vendor/github.com/Xe/uuid/doc.go new file mode 100644 index 0000000..d8bd013 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/doc.go @@ -0,0 +1,8 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The uuid package generates and inspects UUIDs. +// +// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services. +package uuid diff --git a/tg/pbot/vendor/github.com/Xe/uuid/hash.go b/tg/pbot/vendor/github.com/Xe/uuid/hash.go new file mode 100644 index 0000000..cdd4192 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/hash.go @@ -0,0 +1,53 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "crypto/md5" + "crypto/sha1" + "hash" +) + +// Well known Name Space IDs and UUIDs +var ( + NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") + NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8") + NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8") + NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8") + NIL = Parse("00000000-0000-0000-0000-000000000000") +) + +// NewHash returns a new UUID dervied from the hash of space concatenated with +// data generated by h. The hash should be at least 16 byte in length. The +// first 16 bytes of the hash are used to form the UUID. The version of the +// UUID will be the lower 4 bits of version. NewHash is used to implement +// NewMD5 and NewSHA1. +func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { + h.Reset() + h.Write(space) + h.Write([]byte(data)) + s := h.Sum(nil) + uuid := make([]byte, 16) + copy(uuid, s) + uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) + uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant + return uuid +} + +// NewMD5 returns a new MD5 (Version 3) UUID based on the +// supplied name space and data. +// +// NewHash(md5.New(), space, data, 3) +func NewMD5(space UUID, data []byte) UUID { + return NewHash(md5.New(), space, data, 3) +} + +// NewSHA1 returns a new SHA1 (Version 5) UUID based on the +// supplied name space and data. +// +// NewHash(sha1.New(), space, data, 5) +func NewSHA1(space UUID, data []byte) UUID { + return NewHash(sha1.New(), space, data, 5) +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/node.go b/tg/pbot/vendor/github.com/Xe/uuid/node.go new file mode 100644 index 0000000..dd0a8ac --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/node.go @@ -0,0 +1,101 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "net" + +var ( + interfaces []net.Interface // cached list of interfaces + ifname string // name of interface being used + nodeID []byte // hardware for version 1 UUIDs +) + +// NodeInterface returns the name of the interface from which the NodeID was +// derived. The interface "user" is returned if the NodeID was set by +// SetNodeID. +func NodeInterface() string { + return ifname +} + +// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. +// If name is "" then the first usable interface found will be used or a random +// Node ID will be generated. If a named interface cannot be found then false +// is returned. +// +// SetNodeInterface never fails when name is "". +func SetNodeInterface(name string) bool { + if interfaces == nil { + var err error + interfaces, err = net.Interfaces() + if err != nil && name != "" { + return false + } + } + + for _, ifs := range interfaces { + if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { + if setNodeID(ifs.HardwareAddr) { + ifname = ifs.Name + return true + } + } + } + + // We found no interfaces with a valid hardware address. If name + // does not specify a specific interface generate a random Node ID + // (section 4.1.6) + if name == "" { + if nodeID == nil { + nodeID = make([]byte, 6) + } + randomBits(nodeID) + return true + } + return false +} + +// NodeID returns a slice of a copy of the current Node ID, setting the Node ID +// if not already set. +func NodeID() []byte { + if nodeID == nil { + SetNodeInterface("") + } + nid := make([]byte, 6) + copy(nid, nodeID) + return nid +} + +// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes +// of id are used. If id is less than 6 bytes then false is returned and the +// Node ID is not set. +func SetNodeID(id []byte) bool { + if setNodeID(id) { + ifname = "user" + return true + } + return false +} + +func setNodeID(id []byte) bool { + if len(id) < 6 { + return false + } + if nodeID == nil { + nodeID = make([]byte, 6) + } + copy(nodeID, id) + return true +} + +// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is +// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) NodeID() []byte { + if len(uuid) != 16 { + return nil + } + node := make([]byte, 6) + copy(node, uuid[10:]) + return node +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/time.go b/tg/pbot/vendor/github.com/Xe/uuid/time.go new file mode 100644 index 0000000..b9369c2 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/time.go @@ -0,0 +1,132 @@ +// Copyright 2014 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "sync" + "time" +) + +// A Time represents a time as the number of 100's of nanoseconds since 15 Oct +// 1582. +type Time int64 + +const ( + lillian = 2299160 // Julian day of 15 Oct 1582 + unix = 2440587 // Julian day of 1 Jan 1970 + epoch = unix - lillian // Days between epochs + g1582 = epoch * 86400 // seconds between epochs + g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs +) + +var ( + mu sync.Mutex + lasttime uint64 // last time we returned + clock_seq uint16 // clock sequence for this run + + timeNow = time.Now // for testing +) + +// UnixTime converts t the number of seconds and nanoseconds using the Unix +// epoch of 1 Jan 1970. +func (t Time) UnixTime() (sec, nsec int64) { + sec = int64(t - g1582ns100) + nsec = (sec % 10000000) * 100 + sec /= 10000000 + return sec, nsec +} + +// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and +// adjusts the clock sequence as needed. An error is returned if the current +// time cannot be determined. +func GetTime() (Time, error) { + defer mu.Unlock() + mu.Lock() + return getTime() +} + +func getTime() (Time, error) { + t := timeNow() + + // If we don't have a clock sequence already, set one. + if clock_seq == 0 { + setClockSequence(-1) + } + now := uint64(t.UnixNano()/100) + g1582ns100 + + // If time has gone backwards with this clock sequence then we + // increment the clock sequence + if now <= lasttime { + clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000 + } + lasttime = now + return Time(now), nil +} + +// ClockSequence returns the current clock sequence, generating one if not +// already set. The clock sequence is only used for Version 1 UUIDs. +// +// The uuid package does not use global static storage for the clock sequence or +// the last time a UUID was generated. Unless SetClockSequence a new random +// clock sequence is generated the first time a clock sequence is requested by +// ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated +// for +func ClockSequence() int { + defer mu.Unlock() + mu.Lock() + return clockSequence() +} + +func clockSequence() int { + if clock_seq == 0 { + setClockSequence(-1) + } + return int(clock_seq & 0x3fff) +} + +// SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to +// -1 causes a new sequence to be generated. +func SetClockSequence(seq int) { + defer mu.Unlock() + mu.Lock() + setClockSequence(seq) +} + +func setClockSequence(seq int) { + if seq == -1 { + var b [2]byte + randomBits(b[:]) // clock sequence + seq = int(b[0])<<8 | int(b[1]) + } + old_seq := clock_seq + clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant + if old_seq != clock_seq { + lasttime = 0 + } +} + +// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in +// uuid. It returns false if uuid is not valid. The time is only well defined +// for version 1 and 2 UUIDs. +func (uuid UUID) Time() (Time, bool) { + if len(uuid) != 16 { + return 0, false + } + time := int64(binary.BigEndian.Uint32(uuid[0:4])) + time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 + time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 + return Time(time), true +} + +// ClockSequence returns the clock sequence encoded in uuid. It returns false +// if uuid is not valid. The clock sequence is only well defined for version 1 +// and 2 UUIDs. +func (uuid UUID) ClockSequence() (int, bool) { + if len(uuid) != 16 { + return 0, false + } + return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/util.go b/tg/pbot/vendor/github.com/Xe/uuid/util.go new file mode 100644 index 0000000..de40b10 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/util.go @@ -0,0 +1,43 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// randomBits completely fills slice b with random data. +func randomBits(b []byte) { + if _, err := io.ReadFull(rander, b); err != nil { + panic(err.Error()) // rand should never fail + } +} + +// xvalues returns the value of a byte as a hexadecimal digit or 255. +var xvalues = []byte{ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} + +// xtob converts the the first two hex bytes of x into a byte. +func xtob(x string) (byte, bool) { + b1 := xvalues[x[0]] + b2 := xvalues[x[1]] + return (b1 << 4) | b2, b1 != 255 && b2 != 255 +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/uuid.go b/tg/pbot/vendor/github.com/Xe/uuid/uuid.go new file mode 100644 index 0000000..2920fae --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/uuid.go @@ -0,0 +1,163 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "bytes" + "crypto/rand" + "fmt" + "io" + "strings" +) + +// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC +// 4122. +type UUID []byte + +// A Version represents a UUIDs version. +type Version byte + +// A Variant represents a UUIDs variant. +type Variant byte + +// Constants returned by Variant. +const ( + Invalid = Variant(iota) // Invalid UUID + RFC4122 // The variant specified in RFC4122 + Reserved // Reserved, NCS backward compatibility. + Microsoft // Reserved, Microsoft Corporation backward compatibility. + Future // Reserved for future definition. +) + +var rander = rand.Reader // random function + +// New returns a new random (version 4) UUID as a string. It is a convenience +// function for NewRandom().String(). +func New() string { + return NewRandom().String() +} + +// Parse decodes s into a UUID or returns nil. Both the UUID form of +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded. +func Parse(s string) UUID { + if len(s) == 36+9 { + if strings.ToLower(s[:9]) != "urn:uuid:" { + return nil + } + s = s[9:] + } else if len(s) != 36 { + return nil + } + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return nil + } + uuid := make([]byte, 16) + for i, x := range []int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34} { + if v, ok := xtob(s[x:]); !ok { + return nil + } else { + uuid[i] = v + } + } + return uuid +} + +// Equal returns true if uuid1 and uuid2 are equal. +func Equal(uuid1, uuid2 UUID) bool { + return bytes.Equal(uuid1, uuid2) +} + +// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// , or "" if uuid is invalid. +func (uuid UUID) String() string { + if uuid == nil || len(uuid) != 16 { + return "" + } + b := []byte(uuid) + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", + b[:4], b[4:6], b[6:8], b[8:10], b[10:]) +} + +// URN returns the RFC 2141 URN form of uuid, +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. +func (uuid UUID) URN() string { + if uuid == nil || len(uuid) != 16 { + return "" + } + b := []byte(uuid) + return fmt.Sprintf("urn:uuid:%08x-%04x-%04x-%04x-%012x", + b[:4], b[4:6], b[6:8], b[8:10], b[10:]) +} + +// Variant returns the variant encoded in uuid. It returns Invalid if +// uuid is invalid. +func (uuid UUID) Variant() Variant { + if len(uuid) != 16 { + return Invalid + } + switch { + case (uuid[8] & 0xc0) == 0x80: + return RFC4122 + case (uuid[8] & 0xe0) == 0xc0: + return Microsoft + case (uuid[8] & 0xe0) == 0xe0: + return Future + default: + return Reserved + } + panic("unreachable") +} + +// Version returns the verison of uuid. It returns false if uuid is not +// valid. +func (uuid UUID) Version() (Version, bool) { + if len(uuid) != 16 { + return 0, false + } + return Version(uuid[6] >> 4), true +} + +func (v Version) String() string { + if v > 15 { + return fmt.Sprintf("BAD_VERSION_%d", v) + } + return fmt.Sprintf("VERSION_%d", v) +} + +func (v Variant) String() string { + switch v { + case RFC4122: + return "RFC4122" + case Reserved: + return "Reserved" + case Microsoft: + return "Microsoft" + case Future: + return "Future" + case Invalid: + return "Invalid" + } + return fmt.Sprintf("BadVariant%d", int(v)) +} + +// SetRand sets the random number generator to r, which implents io.Reader. +// If r.Read returns an error when the package requests random data then +// a panic will be issued. +// +// Calling SetRand with nil sets the random number generator to the default +// generator. +func SetRand(r io.Reader) { + if r == nil { + rander = rand.Reader + return + } + rander = r +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/version1.go b/tg/pbot/vendor/github.com/Xe/uuid/version1.go new file mode 100644 index 0000000..6358004 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/version1.go @@ -0,0 +1,41 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" +) + +// NewUUID returns a Version 1 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewUUID returns nil. If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewUUID returns nil. +func NewUUID() UUID { + if nodeID == nil { + SetNodeInterface("") + } + + now, err := GetTime() + if err != nil { + return nil + } + + uuid := make([]byte, 16) + + time_low := uint32(now & 0xffffffff) + time_mid := uint16((now >> 32) & 0xffff) + time_hi := uint16((now >> 48) & 0x0fff) + time_hi |= 0x1000 // Version 1 + + binary.BigEndian.PutUint32(uuid[0:], time_low) + binary.BigEndian.PutUint16(uuid[4:], time_mid) + binary.BigEndian.PutUint16(uuid[6:], time_hi) + binary.BigEndian.PutUint16(uuid[8:], clock_seq) + copy(uuid[10:], nodeID) + + return uuid +} diff --git a/tg/pbot/vendor/github.com/Xe/uuid/version4.go b/tg/pbot/vendor/github.com/Xe/uuid/version4.go new file mode 100644 index 0000000..b3d4a36 --- /dev/null +++ b/tg/pbot/vendor/github.com/Xe/uuid/version4.go @@ -0,0 +1,25 @@ +// Copyright 2011 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +// Random returns a Random (Version 4) UUID or panics. +// +// The strength of the UUIDs is based on the strength of the crypto/rand +// package. +// +// A note about uniqueness derived from from the UUID Wikipedia entry: +// +// Randomly generated UUIDs have 122 random bits. One's annual risk of being +// hit by a meteorite is estimated to be one chance in 17 billion, that +// means the probability is about 0.00000000006 (6 × 10−11), +// equivalent to the odds of creating a few tens of trillions of UUIDs in a +// year and having one duplicate. +func NewRandom() UUID { + uuid := make([]byte, 16) + randomBits([]byte(uuid)) + uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 + uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 + return uuid +} diff --git a/tg/pbot/vendor/github.com/fogleman/gg/bezier.go b/tg/pbot/vendor/github.com/fogleman/gg/bezier.go new file mode 100644 index 0000000..f2cd7ab --- /dev/null +++ b/tg/pbot/vendor/github.com/fogleman/gg/bezier.go @@ -0,0 +1,59 @@ +package gg + +import "math" + +func quadratic(x0, y0, x1, y1, x2, y2, t float64) (x, y float64) { + u := 1 - t + a := u * u + b := 2 * u * t + c := t * t + x = a*x0 + b*x1 + c*x2 + y = a*y0 + b*y1 + c*y2 + return +} + +func QuadraticBezier(x0, y0, x1, y1, x2, y2 float64) []Point { + l := (math.Hypot(x1-x0, y1-y0) + + math.Hypot(x2-x1, y2-y1)) + n := int(l + 0.5) + if n < 4 { + n = 4 + } + d := float64(n) - 1 + result := make([]Point, n) + for i := 0; i < n; i++ { + t := float64(i) / d + x, y := quadratic(x0, y0, x1, y1, x2, y2, t) + result[i] = Point{x, y} + } + return result +} + +func cubic(x0, y0, x1, y1, x2, y2, x3, y3, t float64) (x, y float64) { + u := 1 - t + a := u * u * u + b := 3 * u * u * t + c := 3 * u * t * t + d := t * t * t + x = a*x0 + b*x1 + c*x2 + d*x3 + y = a*y0 + b*y1 + c*y2 + d*y3 + return +} + +func CubicBezier(x0, y0, x1, y1, x2, y2, x3, y3 float64) []Point { + l := (math.Hypot(x1-x0, y1-y0) + + math.Hypot(x2-x1, y2-y1) + + math.Hypot(x3-x2, y3-y2)) + n := int(l + 0.5) + if n < 4 { + n = 4 + } + d := float64(n) - 1 + result := make([]Point, n) + for i := 0; i < n; i++ { + t := float64(i) / d + x, y := cubic(x0, y0, x1, y1, x2, y2, x3, y3, t) + result[i] = Point{x, y} + } + return result +} diff --git a/tg/pbot/vendor/github.com/fogleman/gg/context.go b/tg/pbot/vendor/github.com/fogleman/gg/context.go new file mode 100644 index 0000000..e828af8 --- /dev/null +++ b/tg/pbot/vendor/github.com/fogleman/gg/context.go @@ -0,0 +1,795 @@ +// Package gg provides a simple API for rendering 2D graphics in pure Go. +package gg + +import ( + "image" + "image/color" + "image/png" + "io" + "math" + + "github.com/golang/freetype/raster" + "golang.org/x/image/draw" + "golang.org/x/image/font" + "golang.org/x/image/font/basicfont" + "golang.org/x/image/math/f64" +) + +type LineCap int + +const ( + LineCapRound LineCap = iota + LineCapButt + LineCapSquare +) + +type LineJoin int + +const ( + LineJoinRound LineJoin = iota + LineJoinBevel +) + +type FillRule int + +const ( + FillRuleWinding FillRule = iota + FillRuleEvenOdd +) + +type Align int + +const ( + AlignLeft Align = iota + AlignCenter + AlignRight +) + +var ( + defaultFillStyle = NewSolidPattern(color.White) + defaultStrokeStyle = NewSolidPattern(color.Black) +) + +type Context struct { + width int + height int + im *image.RGBA + mask *image.Alpha + color color.Color + fillPattern Pattern + strokePattern Pattern + strokePath raster.Path + fillPath raster.Path + start Point + current Point + hasCurrent bool + dashes []float64 + lineWidth float64 + lineCap LineCap + lineJoin LineJoin + fillRule FillRule + fontFace font.Face + fontHeight float64 + matrix Matrix + stack []*Context +} + +// NewContext creates a new image.RGBA with the specified width and height +// and prepares a context for rendering onto that image. +func NewContext(width, height int) *Context { + return NewContextForRGBA(image.NewRGBA(image.Rect(0, 0, width, height))) +} + +// NewContextForImage copies the specified image into a new image.RGBA +// and prepares a context for rendering onto that image. +func NewContextForImage(im image.Image) *Context { + return NewContextForRGBA(imageToRGBA(im)) +} + +// NewContextForRGBA prepares a context for rendering onto the specified image. +// No copy is made. +func NewContextForRGBA(im *image.RGBA) *Context { + return &Context{ + width: im.Bounds().Size().X, + height: im.Bounds().Size().Y, + im: im, + color: color.Transparent, + fillPattern: defaultFillStyle, + strokePattern: defaultStrokeStyle, + lineWidth: 1, + fillRule: FillRuleWinding, + fontFace: basicfont.Face7x13, + fontHeight: 13, + matrix: Identity(), + } +} + +// Image returns the image that has been drawn by this context. +func (dc *Context) Image() image.Image { + return dc.im +} + +// Width returns the width of the image in pixels. +func (dc *Context) Width() int { + return dc.width +} + +// Height returns the height of the image in pixels. +func (dc *Context) Height() int { + return dc.height +} + +// SavePNG encodes the image as a PNG and writes it to disk. +func (dc *Context) SavePNG(path string) error { + return SavePNG(path, dc.im) +} + +// EncodePNG encodes the image as a PNG and writes it to the provided io.Writer. +func (dc *Context) EncodePNG(w io.Writer) error { + return png.Encode(w, dc.im) +} + +// SetDash sets the current dash pattern to use. Call with zero arguments to +// disable dashes. The values specify the lengths of each dash, with +// alternating on and off lengths. +func (dc *Context) SetDash(dashes ...float64) { + dc.dashes = dashes +} + +func (dc *Context) SetLineWidth(lineWidth float64) { + dc.lineWidth = lineWidth +} + +func (dc *Context) SetLineCap(lineCap LineCap) { + dc.lineCap = lineCap +} + +func (dc *Context) SetLineCapRound() { + dc.lineCap = LineCapRound +} + +func (dc *Context) SetLineCapButt() { + dc.lineCap = LineCapButt +} + +func (dc *Context) SetLineCapSquare() { + dc.lineCap = LineCapSquare +} + +func (dc *Context) SetLineJoin(lineJoin LineJoin) { + dc.lineJoin = lineJoin +} + +func (dc *Context) SetLineJoinRound() { + dc.lineJoin = LineJoinRound +} + +func (dc *Context) SetLineJoinBevel() { + dc.lineJoin = LineJoinBevel +} + +func (dc *Context) SetFillRule(fillRule FillRule) { + dc.fillRule = fillRule +} + +func (dc *Context) SetFillRuleWinding() { + dc.fillRule = FillRuleWinding +} + +func (dc *Context) SetFillRuleEvenOdd() { + dc.fillRule = FillRuleEvenOdd +} + +// Color Setters + +func (dc *Context) setFillAndStrokeColor(c color.Color) { + dc.color = c + dc.fillPattern = NewSolidPattern(c) + dc.strokePattern = NewSolidPattern(c) +} + +// SetFillStyle sets current fill style +func (dc *Context) SetFillStyle(pattern Pattern) { + // if pattern is SolidPattern, also change dc.color(for dc.Clear, dc.drawString) + if fillStyle, ok := pattern.(*solidPattern); ok { + dc.color = fillStyle.color + } + dc.fillPattern = pattern +} + +// SetStrokeStyle sets current stroke style +func (dc *Context) SetStrokeStyle(pattern Pattern) { + dc.strokePattern = pattern +} + +// SetColor sets the current color(for both fill and stroke). +func (dc *Context) SetColor(c color.Color) { + dc.setFillAndStrokeColor(c) +} + +// SetHexColor sets the current color using a hex string. The leading pound +// sign (#) is optional. Both 3- and 6-digit variations are supported. 8 digits +// may be provided to set the alpha value as well. +func (dc *Context) SetHexColor(x string) { + r, g, b, a := parseHexColor(x) + dc.SetRGBA255(r, g, b, a) +} + +// SetRGBA255 sets the current color. r, g, b, a values should be between 0 and +// 255, inclusive. +func (dc *Context) SetRGBA255(r, g, b, a int) { + dc.color = color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)} + dc.setFillAndStrokeColor(dc.color) +} + +// SetRGB255 sets the current color. r, g, b values should be between 0 and 255, +// inclusive. Alpha will be set to 255 (fully opaque). +func (dc *Context) SetRGB255(r, g, b int) { + dc.SetRGBA255(r, g, b, 255) +} + +// SetRGBA sets the current color. r, g, b, a values should be between 0 and 1, +// inclusive. +func (dc *Context) SetRGBA(r, g, b, a float64) { + dc.color = color.NRGBA{ + uint8(r * 255), + uint8(g * 255), + uint8(b * 255), + uint8(a * 255), + } + dc.setFillAndStrokeColor(dc.color) +} + +// SetRGB sets the current color. r, g, b values should be between 0 and 1, +// inclusive. Alpha will be set to 1 (fully opaque). +func (dc *Context) SetRGB(r, g, b float64) { + dc.SetRGBA(r, g, b, 1) +} + +// Path Manipulation + +// MoveTo starts a new subpath within the current path starting at the +// specified point. +func (dc *Context) MoveTo(x, y float64) { + if dc.hasCurrent { + dc.fillPath.Add1(dc.start.Fixed()) + } + x, y = dc.TransformPoint(x, y) + p := Point{x, y} + dc.strokePath.Start(p.Fixed()) + dc.fillPath.Start(p.Fixed()) + dc.start = p + dc.current = p + dc.hasCurrent = true +} + +// LineTo adds a line segment to the current path starting at the current +// point. If there is no current point, it is equivalent to MoveTo(x, y) +func (dc *Context) LineTo(x, y float64) { + if !dc.hasCurrent { + dc.MoveTo(x, y) + } else { + x, y = dc.TransformPoint(x, y) + p := Point{x, y} + dc.strokePath.Add1(p.Fixed()) + dc.fillPath.Add1(p.Fixed()) + dc.current = p + } +} + +// QuadraticTo adds a quadratic bezier curve to the current path starting at +// the current point. If there is no current point, it first performs +// MoveTo(x1, y1) +func (dc *Context) QuadraticTo(x1, y1, x2, y2 float64) { + if !dc.hasCurrent { + dc.MoveTo(x1, y1) + } + x1, y1 = dc.TransformPoint(x1, y1) + x2, y2 = dc.TransformPoint(x2, y2) + p1 := Point{x1, y1} + p2 := Point{x2, y2} + dc.strokePath.Add2(p1.Fixed(), p2.Fixed()) + dc.fillPath.Add2(p1.Fixed(), p2.Fixed()) + dc.current = p2 +} + +// CubicTo adds a cubic bezier curve to the current path starting at the +// current point. If there is no current point, it first performs +// MoveTo(x1, y1). Because freetype/raster does not support cubic beziers, +// this is emulated with many small line segments. +func (dc *Context) CubicTo(x1, y1, x2, y2, x3, y3 float64) { + if !dc.hasCurrent { + dc.MoveTo(x1, y1) + } + x0, y0 := dc.current.X, dc.current.Y + x1, y1 = dc.TransformPoint(x1, y1) + x2, y2 = dc.TransformPoint(x2, y2) + x3, y3 = dc.TransformPoint(x3, y3) + points := CubicBezier(x0, y0, x1, y1, x2, y2, x3, y3) + previous := dc.current.Fixed() + for _, p := range points[1:] { + f := p.Fixed() + if f == previous { + // TODO: this fixes some rendering issues but not all + continue + } + previous = f + dc.strokePath.Add1(f) + dc.fillPath.Add1(f) + dc.current = p + } +} + +// ClosePath adds a line segment from the current point to the beginning +// of the current subpath. If there is no current point, this is a no-op. +func (dc *Context) ClosePath() { + if dc.hasCurrent { + dc.strokePath.Add1(dc.start.Fixed()) + dc.fillPath.Add1(dc.start.Fixed()) + dc.current = dc.start + } +} + +// ClearPath clears the current path. There is no current point after this +// operation. +func (dc *Context) ClearPath() { + dc.strokePath.Clear() + dc.fillPath.Clear() + dc.hasCurrent = false +} + +// NewSubPath starts a new subpath within the current path. There is no current +// point after this operation. +func (dc *Context) NewSubPath() { + if dc.hasCurrent { + dc.fillPath.Add1(dc.start.Fixed()) + } + dc.hasCurrent = false +} + +// Path Drawing + +func (dc *Context) capper() raster.Capper { + switch dc.lineCap { + case LineCapButt: + return raster.ButtCapper + case LineCapRound: + return raster.RoundCapper + case LineCapSquare: + return raster.SquareCapper + } + return nil +} + +func (dc *Context) joiner() raster.Joiner { + switch dc.lineJoin { + case LineJoinBevel: + return raster.BevelJoiner + case LineJoinRound: + return raster.RoundJoiner + } + return nil +} + +func (dc *Context) stroke(painter raster.Painter) { + path := dc.strokePath + if len(dc.dashes) > 0 { + path = dashed(path, dc.dashes) + } else { + // TODO: this is a temporary workaround to remove tiny segments + // that result in rendering issues + path = rasterPath(flattenPath(path)) + } + r := raster.NewRasterizer(dc.width, dc.height) + r.UseNonZeroWinding = true + r.AddStroke(path, fix(dc.lineWidth), dc.capper(), dc.joiner()) + r.Rasterize(painter) +} + +func (dc *Context) fill(painter raster.Painter) { + path := dc.fillPath + if dc.hasCurrent { + path = make(raster.Path, len(dc.fillPath)) + copy(path, dc.fillPath) + path.Add1(dc.start.Fixed()) + } + r := raster.NewRasterizer(dc.width, dc.height) + r.UseNonZeroWinding = dc.fillRule == FillRuleWinding + r.AddPath(path) + r.Rasterize(painter) +} + +// StrokePreserve strokes the current path with the current color, line width, +// line cap, line join and dash settings. The path is preserved after this +// operation. +func (dc *Context) StrokePreserve() { + painter := newPatternPainter(dc.im, dc.mask, dc.strokePattern) + dc.stroke(painter) +} + +// Stroke strokes the current path with the current color, line width, +// line cap, line join and dash settings. The path is cleared after this +// operation. +func (dc *Context) Stroke() { + dc.StrokePreserve() + dc.ClearPath() +} + +// FillPreserve fills the current path with the current color. Open subpaths +// are implicity closed. The path is preserved after this operation. +func (dc *Context) FillPreserve() { + painter := newPatternPainter(dc.im, dc.mask, dc.fillPattern) + dc.fill(painter) +} + +// Fill fills the current path with the current color. Open subpaths +// are implicity closed. The path is cleared after this operation. +func (dc *Context) Fill() { + dc.FillPreserve() + dc.ClearPath() +} + +// ClipPreserve updates the clipping region by intersecting the current +// clipping region with the current path as it would be filled by dc.Fill(). +// The path is preserved after this operation. +func (dc *Context) ClipPreserve() { + clip := image.NewAlpha(image.Rect(0, 0, dc.width, dc.height)) + painter := raster.NewAlphaOverPainter(clip) + dc.fill(painter) + if dc.mask == nil { + dc.mask = clip + } else { + mask := image.NewAlpha(image.Rect(0, 0, dc.width, dc.height)) + draw.DrawMask(mask, mask.Bounds(), clip, image.ZP, dc.mask, image.ZP, draw.Over) + dc.mask = mask + } +} + +// Clip updates the clipping region by intersecting the current +// clipping region with the current path as it would be filled by dc.Fill(). +// The path is cleared after this operation. +func (dc *Context) Clip() { + dc.ClipPreserve() + dc.ClearPath() +} + +// ResetClip clears the clipping region. +func (dc *Context) ResetClip() { + dc.mask = nil +} + +// Convenient Drawing Functions + +// Clear fills the entire image with the current color. +func (dc *Context) Clear() { + src := image.NewUniform(dc.color) + draw.Draw(dc.im, dc.im.Bounds(), src, image.ZP, draw.Src) +} + +// SetPixel sets the color of the specified pixel using the current color. +func (dc *Context) SetPixel(x, y int) { + dc.im.Set(x, y, dc.color) +} + +// DrawPoint is like DrawCircle but ensures that a circle of the specified +// size is drawn regardless of the current transformation matrix. The position +// is still transformed, but not the shape of the point. +func (dc *Context) DrawPoint(x, y, r float64) { + dc.Push() + tx, ty := dc.TransformPoint(x, y) + dc.Identity() + dc.DrawCircle(tx, ty, r) + dc.Pop() +} + +func (dc *Context) DrawLine(x1, y1, x2, y2 float64) { + dc.MoveTo(x1, y1) + dc.LineTo(x2, y2) +} + +func (dc *Context) DrawRectangle(x, y, w, h float64) { + dc.NewSubPath() + dc.MoveTo(x, y) + dc.LineTo(x+w, y) + dc.LineTo(x+w, y+h) + dc.LineTo(x, y+h) + dc.ClosePath() +} + +func (dc *Context) DrawRoundedRectangle(x, y, w, h, r float64) { + x0, x1, x2, x3 := x, x+r, x+w-r, x+w + y0, y1, y2, y3 := y, y+r, y+h-r, y+h + dc.NewSubPath() + dc.MoveTo(x1, y0) + dc.LineTo(x2, y0) + dc.DrawArc(x2, y1, r, Radians(270), Radians(360)) + dc.LineTo(x3, y2) + dc.DrawArc(x2, y2, r, Radians(0), Radians(90)) + dc.LineTo(x1, y3) + dc.DrawArc(x1, y2, r, Radians(90), Radians(180)) + dc.LineTo(x0, y1) + dc.DrawArc(x1, y1, r, Radians(180), Radians(270)) + dc.ClosePath() +} + +func (dc *Context) DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64) { + const n = 16 + for i := 0; i < n; i++ { + p1 := float64(i+0) / n + p2 := float64(i+1) / n + a1 := angle1 + (angle2-angle1)*p1 + a2 := angle1 + (angle2-angle1)*p2 + x0 := x + rx*math.Cos(a1) + y0 := y + ry*math.Sin(a1) + x1 := x + rx*math.Cos(a1+(a2-a1)/2) + y1 := y + ry*math.Sin(a1+(a2-a1)/2) + x2 := x + rx*math.Cos(a2) + y2 := y + ry*math.Sin(a2) + cx := 2*x1 - x0/2 - x2/2 + cy := 2*y1 - y0/2 - y2/2 + if i == 0 && !dc.hasCurrent { + dc.MoveTo(x0, y0) + } + dc.QuadraticTo(cx, cy, x2, y2) + } +} + +func (dc *Context) DrawEllipse(x, y, rx, ry float64) { + dc.NewSubPath() + dc.DrawEllipticalArc(x, y, rx, ry, 0, 2*math.Pi) + dc.ClosePath() +} + +func (dc *Context) DrawArc(x, y, r, angle1, angle2 float64) { + dc.DrawEllipticalArc(x, y, r, r, angle1, angle2) +} + +func (dc *Context) DrawCircle(x, y, r float64) { + dc.NewSubPath() + dc.DrawEllipticalArc(x, y, r, r, 0, 2*math.Pi) + dc.ClosePath() +} + +func (dc *Context) DrawRegularPolygon(n int, x, y, r, rotation float64) { + angle := 2 * math.Pi / float64(n) + rotation -= math.Pi / 2 + if n%2 == 0 { + rotation += angle / 2 + } + dc.NewSubPath() + for i := 0; i < n; i++ { + a := rotation + angle*float64(i) + dc.LineTo(x+r*math.Cos(a), y+r*math.Sin(a)) + } + dc.ClosePath() +} + +// DrawImage draws the specified image at the specified point. +func (dc *Context) DrawImage(im image.Image, x, y int) { + dc.DrawImageAnchored(im, x, y, 0, 0) +} + +// DrawImageAnchored draws the specified image at the specified anchor point. +// The anchor point is x - w * ax, y - h * ay, where w, h is the size of the +// image. Use ax=0.5, ay=0.5 to center the image at the specified point. +func (dc *Context) DrawImageAnchored(im image.Image, x, y int, ax, ay float64) { + s := im.Bounds().Size() + x -= int(ax * float64(s.X)) + y -= int(ay * float64(s.Y)) + transformer := draw.BiLinear + fx, fy := float64(x), float64(y) + m := dc.matrix.Translate(fx, fy) + s2d := f64.Aff3{m.XX, m.XY, m.X0, m.YX, m.YY, m.Y0} + if dc.mask == nil { + transformer.Transform(dc.im, s2d, im, im.Bounds(), draw.Over, nil) + } else { + transformer.Transform(dc.im, s2d, im, im.Bounds(), draw.Over, &draw.Options{ + DstMask: dc.mask, + DstMaskP: image.ZP, + }) + } +} + +// Text Functions + +func (dc *Context) SetFontFace(fontFace font.Face) { + dc.fontFace = fontFace + dc.fontHeight = float64(fontFace.Metrics().Height) / 64 +} + +func (dc *Context) LoadFontFace(path string, points float64) error { + face, err := LoadFontFace(path, points) + if err == nil { + dc.fontFace = face + dc.fontHeight = points * 72 / 96 + } + return err +} + +func (dc *Context) drawString(im *image.RGBA, s string, x, y float64) { + d := &font.Drawer{ + Dst: im, + Src: image.NewUniform(dc.color), + Face: dc.fontFace, + Dot: fixp(x, y), + } + // based on Drawer.DrawString() in golang.org/x/image/font/font.go + prevC := rune(-1) + for _, c := range s { + if prevC >= 0 { + d.Dot.X += d.Face.Kern(prevC, c) + } + dr, mask, maskp, advance, ok := d.Face.Glyph(d.Dot, c) + if !ok { + // TODO: is falling back on the U+FFFD glyph the responsibility of + // the Drawer or the Face? + // TODO: set prevC = '\ufffd'? + continue + } + sr := dr.Sub(dr.Min) + transformer := draw.BiLinear + fx, fy := float64(dr.Min.X), float64(dr.Min.Y) + m := dc.matrix.Translate(fx, fy) + s2d := f64.Aff3{m.XX, m.XY, m.X0, m.YX, m.YY, m.Y0} + transformer.Transform(d.Dst, s2d, d.Src, sr, draw.Over, &draw.Options{ + SrcMask: mask, + SrcMaskP: maskp, + }) + d.Dot.X += advance + prevC = c + } +} + +// DrawString draws the specified text at the specified point. +func (dc *Context) DrawString(s string, x, y float64) { + dc.DrawStringAnchored(s, x, y, 0, 0) +} + +// DrawStringAnchored draws the specified text at the specified anchor point. +// The anchor point is x - w * ax, y - h * ay, where w, h is the size of the +// text. Use ax=0.5, ay=0.5 to center the text at the specified point. +func (dc *Context) DrawStringAnchored(s string, x, y, ax, ay float64) { + w, h := dc.MeasureString(s) + x -= ax * w + y += ay * h + if dc.mask == nil { + dc.drawString(dc.im, s, x, y) + } else { + im := image.NewRGBA(image.Rect(0, 0, dc.width, dc.height)) + dc.drawString(im, s, x, y) + draw.DrawMask(dc.im, dc.im.Bounds(), im, image.ZP, dc.mask, image.ZP, draw.Over) + } +} + +// DrawStringWrapped word-wraps the specified string to the given max width +// and then draws it at the specified anchor point using the given line +// spacing and text alignment. +func (dc *Context) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align) { + lines := dc.WordWrap(s, width) + h := float64(len(lines)) * dc.fontHeight * lineSpacing + h -= (lineSpacing - 1) * dc.fontHeight + x -= ax * width + y -= ay * h + switch align { + case AlignLeft: + ax = 0 + case AlignCenter: + ax = 0.5 + x += width / 2 + case AlignRight: + ax = 1 + x += width + } + ay = 1 + for _, line := range lines { + dc.DrawStringAnchored(line, x, y, ax, ay) + y += dc.fontHeight * lineSpacing + } +} + +// MeasureString returns the rendered width and height of the specified text +// given the current font face. +func (dc *Context) MeasureString(s string) (w, h float64) { + d := &font.Drawer{ + Face: dc.fontFace, + } + a := d.MeasureString(s) + return float64(a >> 6), dc.fontHeight +} + +// WordWrap wraps the specified string to the given max width and current +// font face. +func (dc *Context) WordWrap(s string, w float64) []string { + return wordWrap(dc, s, w) +} + +// Transformation Matrix Operations + +// Identity resets the current transformation matrix to the identity matrix. +// This results in no translating, scaling, rotating, or shearing. +func (dc *Context) Identity() { + dc.matrix = Identity() +} + +// Translate updates the current matrix with a translation. +func (dc *Context) Translate(x, y float64) { + dc.matrix = dc.matrix.Translate(x, y) +} + +// Scale updates the current matrix with a scaling factor. +// Scaling occurs about the origin. +func (dc *Context) Scale(x, y float64) { + dc.matrix = dc.matrix.Scale(x, y) +} + +// ScaleAbout updates the current matrix with a scaling factor. +// Scaling occurs about the specified point. +func (dc *Context) ScaleAbout(sx, sy, x, y float64) { + dc.Translate(x, y) + dc.Scale(sx, sy) + dc.Translate(-x, -y) +} + +// Rotate updates the current matrix with a clockwise rotation. +// Rotation occurs about the origin. Angle is specified in radians. +func (dc *Context) Rotate(angle float64) { + dc.matrix = dc.matrix.Rotate(angle) +} + +// RotateAbout updates the current matrix with a clockwise rotation. +// Rotation occurs about the specified point. Angle is specified in radians. +func (dc *Context) RotateAbout(angle, x, y float64) { + dc.Translate(x, y) + dc.Rotate(angle) + dc.Translate(-x, -y) +} + +// Shear updates the current matrix with a shearing angle. +// Shearing occurs about the origin. +func (dc *Context) Shear(x, y float64) { + dc.matrix = dc.matrix.Shear(x, y) +} + +// ShearAbout updates the current matrix with a shearing angle. +// Shearing occurs about the specified point. +func (dc *Context) ShearAbout(sx, sy, x, y float64) { + dc.Translate(x, y) + dc.Shear(sx, sy) + dc.Translate(-x, -y) +} + +// TransformPoint multiplies the specified point by the current matrix, +// returning a transformed position. +func (dc *Context) TransformPoint(x, y float64) (tx, ty float64) { + return dc.matrix.TransformPoint(x, y) +} + +// InvertY flips the Y axis so that Y grows from bottom to top and Y=0 is at +// the bottom of the image. +func (dc *Context) InvertY() { + dc.Translate(0, float64(dc.height)) + dc.Scale(1, -1) +} + +// Stack + +// Push saves the current state of the context for later retrieval. These +// can be nested. +func (dc *Context) Push() { + x := *dc + dc.stack = append(dc.stack, &x) +} + +// Pop restores the last saved context state from the stack. +func (dc *Context) Pop() { + before := *dc + s := dc.stack + x, s := s[len(s)-1], s[:len(s)-1] + *dc = *x + dc.mask = before.mask + dc.strokePath = before.strokePath + dc.fillPath = before.fillPath + dc.start = before.start + dc.current = before.current + dc.hasCurrent = before.hasCurrent +} diff --git a/tg/pbot/vendor/github.com/fogleman/gg/gradient.go b/tg/pbot/vendor/github.com/fogleman/gg/gradient.go new file mode 100644 index 0000000..1625520 --- /dev/null +++ b/tg/pbot/vendor/github.com/fogleman/gg/gradient.go @@ -0,0 +1,202 @@ +package gg + +import ( + "image/color" + "math" + "sort" +) + +type stop struct { + pos float64 + color color.Color +} + +type stops []stop + +// Len satisfies the Sort interface. +func (s stops) Len() int { + return len(s) +} + +// Less satisfies the Sort interface. +func (s stops) Less(i, j int) bool { + return s[i].pos < s[j].pos +} + +// Swap satisfies the Sort interface. +func (s stops) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +type Gradient interface { + Pattern + AddColorStop(offset float64, color color.Color) +} + +// Linear Gradient +type linearGradient struct { + x0, y0, x1, y1 float64 + stops stops +} + +func (g *linearGradient) ColorAt(x, y int) color.Color { + if len(g.stops) == 0 { + return color.Transparent + } + + fx, fy := float64(x), float64(y) + x0, y0, x1, y1 := g.x0, g.y0, g.x1, g.y1 + dx, dy := x1-x0, y1-y0 + + // Horizontal + if dy == 0 && dx != 0 { + return getColor((fx-x0)/dx, g.stops) + } + + // Vertical + if dx == 0 && dy != 0 { + return getColor((fy-y0