diff --git a/config.yaml b/config.yaml index 2189c9c3..a64d88a1 100644 --- a/config.yaml +++ b/config.yaml @@ -3,37 +3,31 @@ log: level: info db: - url: postgres://postgres:password@localhost:5432/certificate?sslmode=disable + url: listener: addr: :8000 signature: - key: "5HtbQzoofDVmEvzAMd89iq5nRpFUm8xudgkSNZ4rPN9z5AWcGEJ" + key: "" networks: - rpc_eth: "https://goerli.infura.io/v3/45efc27205e746adb3a1d6c3da69a7ba" + rpc_eth: "" ipfs: "https://ipfs.infura.io:5001" - ipfs_pr_id: "2LgGs3QZ5Ndz065ZVu4xoSTWzcU" - ipfs_pr_key: "4afcd5182cb6e849fa72726d44f77186" + ipfs_pr_id: "" + ipfs_pr_key: "" + +sbt: + external_url: "https://dlt-academy.com/certificates" google: secret_path: "./client.json" qr_path: "qr" pdf_path: "pdf" api_key: "" - # api_key: "AIzaSyB5JPdmDD-BCyOs7WpQaXqz_wiZJ-VMQ" code: "" enable: true -# -#google: -# secret_path: "./client.json" -# qr_path: "qr" -# pdf_path: "pdf" -# api_key: "" -## api_key: "AIzaSyB5JPdmDD-BCyOs7WpQaXqz_wiZJ-VMQ" -# code: "4/0AVHEtk6nkskIwm0pcZEhcrOpoXZG14GYeuoeQ4akl5HOHJLcuwpDRryMZydgBekmjzgElg" -# enable: true + tables: result: "test.xlsx" @@ -76,6 +70,8 @@ exams: "graduated with honors": "Exam passed with honors" "Listener only": "Listener only. Exam not passed" + + cop: disabled: true endpoint: "http://..." diff --git a/docs/spec/components/schemas/Container.yaml b/docs/spec/components/schemas/Container.yaml new file mode 100644 index 00000000..e6cfc2cb --- /dev/null +++ b/docs/spec/components/schemas/Container.yaml @@ -0,0 +1,30 @@ +allOf: + - $ref: '#/components/schemas/ContainerKey' + - type: object + required: + - attributes + properties: + attributes: + type: object + required: + - container_id + - certificates + - status + properties: + container_id: + type: string + format: string + example: "1" + certificates: + type: array + items: + type: object + $ref: '#/components/schemas/User' + status: + type: string + enum: + - "is_processing" + - "ready" + - "not_found" + + diff --git a/docs/spec/components/schemas/ContainerKey.yaml b/docs/spec/components/schemas/ContainerKey.yaml new file mode 100644 index 00000000..69252ba9 --- /dev/null +++ b/docs/spec/components/schemas/ContainerKey.yaml @@ -0,0 +1,9 @@ +type: object +required: + - type + - id +properties: + type: + type: string + enum: + - container \ No newline at end of file diff --git a/docs/spec/components/schemas/IpfsFile.yaml b/docs/spec/components/schemas/IpfsFile.yaml index a8a5fdf9..cdccda21 100644 --- a/docs/spec/components/schemas/IpfsFile.yaml +++ b/docs/spec/components/schemas/IpfsFile.yaml @@ -1,5 +1,5 @@ allOf: - - $ref: '#/components/schemas/IpfsFile' + - $ref: '#/components/schemas/IpfsFileUploadKey' - type: object required: - attributes @@ -11,5 +11,4 @@ allOf: properties: url: type: string - format: string example: "ipfs://..." diff --git a/docs/spec/components/schemas/IpfsFileKey.yaml b/docs/spec/components/schemas/IpfsFileKey.yaml new file mode 100644 index 00000000..58e4c696 --- /dev/null +++ b/docs/spec/components/schemas/IpfsFileKey.yaml @@ -0,0 +1,9 @@ +type: object +required: + - type + - id +properties: + type: + type: string + enum: + - ipfs_file \ No newline at end of file diff --git a/docs/spec/components/schemas/IpfsFileUpload.yaml b/docs/spec/components/schemas/IpfsFileUpload.yaml new file mode 100644 index 00000000..c6fd1714 --- /dev/null +++ b/docs/spec/components/schemas/IpfsFileUpload.yaml @@ -0,0 +1,27 @@ +allOf: + - $ref: '#/components/schemas/IpfsFileUploadKey' + - type: object + required: + - attributes + - relationships + properties: + attributes: + type: object + required: + - img + - description + - name + properties: + name: + type: string + format: string + example: "Name" + img: + type: array + items: + type: byte + description: + type: string + format: string + example: "Some description" + diff --git a/docs/spec/components/schemas/IpfsFileUploadKey.yaml b/docs/spec/components/schemas/IpfsFileUploadKey.yaml new file mode 100644 index 00000000..2ad90d50 --- /dev/null +++ b/docs/spec/components/schemas/IpfsFileUploadKey.yaml @@ -0,0 +1,9 @@ +type: object +required: + - type + - id +properties: + type: + type: string + enum: + - ipfs_file_upload \ No newline at end of file diff --git a/docs/spec/components/schemas/IpfsFileUploadRequest.yaml b/docs/spec/components/schemas/IpfsFileUploadRequest.yaml deleted file mode 100644 index 46e262d1..00000000 --- a/docs/spec/components/schemas/IpfsFileUploadRequest.yaml +++ /dev/null @@ -1,19 +0,0 @@ -type: object -required: - - img - - description - - name -properties: - name: - type: string - format: string - example: "Name" - img: - type: array - items: - type: byte - description: - type: string - format: string - example: "Some description" - diff --git a/docs/spec/components/schemas/Link.yaml b/docs/spec/components/schemas/Link.yaml index c805a176..6399fd56 100644 --- a/docs/spec/components/schemas/Link.yaml +++ b/docs/spec/components/schemas/Link.yaml @@ -11,4 +11,4 @@ allOf: properties: link: type: string - example: "httpL//localhost/*" \ No newline at end of file + example: "http://localhost/*" \ No newline at end of file diff --git a/docs/spec/components/schemas/ParseUsers.yaml b/docs/spec/components/schemas/ParseUsers.yaml new file mode 100644 index 00000000..d3564b82 --- /dev/null +++ b/docs/spec/components/schemas/ParseUsers.yaml @@ -0,0 +1,20 @@ +allOf: + - $ref: '#/components/schemas/ParseUsersKey' + - type: object + required: + - attributes + - relationships + properties: + attributes: + type: object + required: + - name + - url + properties: + name: + type: string + example: "DL" + url: + type: string + example: "https://google.sheet....." + diff --git a/docs/spec/components/schemas/ParseUsersKey.yaml b/docs/spec/components/schemas/ParseUsersKey.yaml new file mode 100644 index 00000000..507c6819 --- /dev/null +++ b/docs/spec/components/schemas/ParseUsersKey.yaml @@ -0,0 +1,9 @@ +type: object +required: + - type + - id +properties: + type: + type: string + enum: + - parse_users \ No newline at end of file diff --git a/docs/spec/components/schemas/PdfsCreateRequest.yaml b/docs/spec/components/schemas/PdfsCreateRequest.yaml deleted file mode 100644 index 231114f6..00000000 --- a/docs/spec/components/schemas/PdfsCreateRequest.yaml +++ /dev/null @@ -1,25 +0,0 @@ -type: object -required: - - data - - url - - address - - name -properties: - data: - type: array - items: - anyOf: - - $ref: '#/components/schemas/User' - description: "user" - url: - type: string - format: string - example: "url" - address: - type: string - format: string - example: "bc3241dhf..." - name: - type: string - format: string - example: "DL" \ No newline at end of file diff --git a/docs/spec/components/schemas/PrepareCertificates.yaml b/docs/spec/components/schemas/PrepareCertificates.yaml new file mode 100644 index 00000000..ede52316 --- /dev/null +++ b/docs/spec/components/schemas/PrepareCertificates.yaml @@ -0,0 +1,32 @@ +allOf: + - $ref: '#/components/schemas/PrepareCertificatesKey' + - type: object + required: + - attributes + properties: + attributes: + type: object + required: + - url + - name + - address + - certificates_data + properties: + name: + type: string + example: "DL" + url: + type: string + example: "ipfs://..." + address: + type: string + example: "0xa0f254..." + certificates_data: + type: array + items: + anyOf: + - $ref: '#/components/schemas/UserBlob' + description: "user" + + + diff --git a/docs/spec/components/schemas/PrepareCertificatesKey.yaml b/docs/spec/components/schemas/PrepareCertificatesKey.yaml new file mode 100644 index 00000000..1b77eda6 --- /dev/null +++ b/docs/spec/components/schemas/PrepareCertificatesKey.yaml @@ -0,0 +1,9 @@ +type: object +required: + - type + - id +properties: + type: + type: string + enum: + - prepare_certificate \ No newline at end of file diff --git a/docs/spec/components/schemas/Settings.yaml b/docs/spec/components/schemas/Settings.yaml index 0f7d3365..8b43afd0 100644 --- a/docs/spec/components/schemas/Settings.yaml +++ b/docs/spec/components/schemas/Settings.yaml @@ -1,12 +1,20 @@ -type: object -required: - - name - - code -properties: - name: - type: string - example: "" - code: - type: string - example: "" +allOf: + - $ref: '#/components/schemas/SettingsKey' + - type: object + required: + - attributes + - relationships + properties: + attributes: + type: object + required: + - name + - code + properties: + name: + type: string + example: "" + code: + type: string + example: "" diff --git a/docs/spec/components/schemas/IpfsKey.yaml b/docs/spec/components/schemas/SettingsKey.yaml similarity index 84% rename from docs/spec/components/schemas/IpfsKey.yaml rename to docs/spec/components/schemas/SettingsKey.yaml index 68043585..37c87b28 100644 --- a/docs/spec/components/schemas/IpfsKey.yaml +++ b/docs/spec/components/schemas/SettingsKey.yaml @@ -6,4 +6,4 @@ properties: type: type: string enum: - - ipfs \ No newline at end of file + - settings \ No newline at end of file diff --git a/docs/spec/components/schemas/User.yaml b/docs/spec/components/schemas/User.yaml index e9842569..74e40905 100644 --- a/docs/spec/components/schemas/User.yaml +++ b/docs/spec/components/schemas/User.yaml @@ -6,78 +6,4 @@ allOf: properties: attributes: type: object - required: - - date - - courseTitle - - points - - participant - - serialNumber - - note - - certificate - - dataHash - - txHash - - signature - - digitalCertificate - - id - - msg - - certificateImg - - shortCourse - properties: - date: - type: string - format: string - example: "02.12.2022" - courseTitle: - type: string - format: string - example: "Title of course" - points: - type: string - format: string - example: "99" - participant: - type: string - format: string - example: "99" - serialNumber: - type: string - format: string - example: "0xhhhhhhhhhhhhhhhhhhhhhhh" - note: - type: string - format: string - example: string - certificate: - type: string - format: string - example: string - dataHash: - type: string - format: string - example: string - txHash: - type: string - format: string - example: string - signature: - type: string - format: string - example: string - digitalCertificate: - type: string - format: string - example: string - id: - type: number - format: int64 - example: 1 - msg: - type: string - format: string - shortCourse: - type: string - format: string - certificateImg: - type: array - items: - type: byte \ No newline at end of file + $ref: '#/components/schemas/UserBlob' \ No newline at end of file diff --git a/docs/spec/components/schemas/UserBlob.yaml b/docs/spec/components/schemas/UserBlob.yaml new file mode 100644 index 00000000..48ac6ec9 --- /dev/null +++ b/docs/spec/components/schemas/UserBlob.yaml @@ -0,0 +1,78 @@ +type: object +required: + - date + - courseTitle + - points + - participant + - serialNumber + - note + - certificate + - dataHash + - txHash + - signature + - digitalCertificate + - id + - msg + - certificateImg + - shortCourse +properties: + date: + type: string + format: string + example: "02.12.2022" + courseTitle: + type: string + format: string + example: "Title of course" + points: + type: string + format: string + example: "99" + participant: + type: string + format: string + example: "99" + serialNumber: + type: string + format: string + example: "17e1da2fa97f8196b4d8" + note: + type: string + format: string + example: "12sffacd4....." + certificate: + type: string + format: string + example: "drive.google.com/file/d/1QXRYX9OeT_TTFm0ya1RaXTVTxaMC7YnL/view" + dataHash: + type: string + format: string + example: "f4f3a35acd60078b21382bd0899ce076587247eb26ba29da8c30902f292189ba" + txHash: + type: string + format: string + example: "17e1da2fa97f8196b4d8fb39a26ff4d61537688ac03a53e3807a9652b5e6535e" + signature: + type: string + format: string + example: "HK9olLqTss5lGvQX2CoqjTIs+zqLJciCvxH3rqrAPh9FSY0uNz/z1h4LInqtQ+EDYmhvBx4+IjhbvY7BMf2ODNI=" + digitalCertificate: + type: string + format: string + example: "drive.google.com/file/d/1QXRYX9OeT_TTFm0ya1RaXTVTxaMC7YnL/view" + id: + type: number + format: int64 + example: 1 + msg: + type: string + format: string + example: "11.04.2023 Ruslan Ovsiienko Basic theory about decentralized finance" + shortCourse: + type: string + format: string + example: "blockchain" + certificateImg: + type: array + items: + type: byte \ No newline at end of file diff --git a/docs/spec/components/schemas/UsersGetRequest.yaml b/docs/spec/components/schemas/UsersGetRequest.yaml deleted file mode 100644 index 3069fcf7..00000000 --- a/docs/spec/components/schemas/UsersGetRequest.yaml +++ /dev/null @@ -1,12 +0,0 @@ -type: object -required: - - name - - url -properties: - name: - type: string - example: "" - url: - type: string - example: "" - diff --git a/docs/spec/paths/integrations@ccp-svc@certificate.yaml b/docs/spec/paths/integrations@ccp-svc@certificate.yaml new file mode 100644 index 00000000..2c1e6b73 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@certificate.yaml @@ -0,0 +1,58 @@ +post: + tags: + - Pdf + summary: pdf + operationId: pdf + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/PrepareCertificates' + responses: + '201': + description: Success + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/User" + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '404': + description: Not Found + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/NotFound" + '500': + $ref: "#/components/responses/InternalError" diff --git a/docs/spec/paths/integrations@ccp-svc@certificate@bitcoin.yaml b/docs/spec/paths/integrations@ccp-svc@certificate@bitcoin.yaml new file mode 100644 index 00000000..1c1b6a97 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@certificate@bitcoin.yaml @@ -0,0 +1,58 @@ +post: + tags: + - Update pdf + summary: update + operationId: update_pdf + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/PrepareCertificates' + responses: + '201': + description: Success + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/User" + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '404': + description: Not Found + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/NotFound" + '500': + $ref: "#/components/responses/InternalError" diff --git a/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}.yaml b/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}.yaml new file mode 100644 index 00000000..4e925097 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}.yaml @@ -0,0 +1,35 @@ +get: + tags: + - Get template by user + summary: template + operationId: get_users_template + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/Template' + responses: + '201': + description: Success + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '500': + $ref: "#/components/responses/InternalError" + diff --git a/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}@{name}.yaml b/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}@{name}.yaml new file mode 100644 index 00000000..30cd8a0b --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@certificate@template@{user}@{name}.yaml @@ -0,0 +1,35 @@ +get: + tags: + - Get current template + summary: template + operationId: get_current_template + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/Template' + responses: + '201': + description: Success + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '500': + $ref: "#/components/responses/InternalError" + diff --git a/docs/spec/paths/integrations@ccp-svc@certificate@{container_id}.yaml b/docs/spec/paths/integrations@ccp-svc@certificate@{container_id}.yaml new file mode 100644 index 00000000..18112eb6 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@certificate@{container_id}.yaml @@ -0,0 +1,47 @@ +get: + tags: + - Get Container State + summary: container + operationId: container + responses: + '201': + description: Success + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/schema/User" + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '404': + description: Not Found + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/NotFound" + '500': + $ref: "#/components/responses/InternalError" diff --git a/docs/spec/paths/integrations@ccp-svc@ipfs.yaml b/docs/spec/paths/integrations@ccp-svc@ipfs.yaml index 7b3393bd..95dcc14d 100644 --- a/docs/spec/paths/integrations@ccp-svc@ipfs.yaml +++ b/docs/spec/paths/integrations@ccp-svc@ipfs.yaml @@ -13,7 +13,7 @@ post: properties: data: type: object - $ref: '#/components/schemas/IpfsFileUploadRequest' + $ref: '#/components/schemas/IpfsFileUpload' responses: '201': description: Success diff --git a/docs/spec/paths/integrations@ccp-svc@pdf.yaml b/docs/spec/paths/integrations@ccp-svc@pdf.yaml deleted file mode 100644 index a965c4ba..00000000 --- a/docs/spec/paths/integrations@ccp-svc@pdf.yaml +++ /dev/null @@ -1,45 +0,0 @@ -post: - tags: - - Pdf - summary: pdf - operationId: pdf - requestBody: - content: - application/json: - schema: - type: object - required: - - data - properties: - data: - type: object - $ref: '#/components/schemas/PdfsCreateRequest' - responses: - '400': - description: Bad Request - content: - application/json: - schema: - type: object - required: - - errors - properties: - errors: - type: array - items: - $ref: "#/components/responses/BadRequest" - '404': - description: Not Found - content: - application/json: - schema: - type: object - required: - - errors - properties: - errors: - type: array - items: - $ref: "#/components/responses/NotFound" - '500': - $ref: "#/components/responses/InternalError" diff --git a/docs/spec/paths/integrations@ccp-svc.yaml b/docs/spec/paths/integrations@ccp-svc@users.yaml similarity index 93% rename from docs/spec/paths/integrations@ccp-svc.yaml rename to docs/spec/paths/integrations@ccp-svc@users.yaml index 51129dff..7fc73758 100644 --- a/docs/spec/paths/integrations@ccp-svc.yaml +++ b/docs/spec/paths/integrations@ccp-svc@users.yaml @@ -13,7 +13,7 @@ post: properties: data: type: object - $ref: '#/components/schemas/UsersGetRequest' + $ref: '#/components/schemas/ParseUsers' responses: '201': description: Success diff --git a/docs/spec/paths/integrations@ccp-svc@users@empty.yaml b/docs/spec/paths/integrations@ccp-svc@users@empty.yaml new file mode 100644 index 00000000..0f097b92 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@users@empty.yaml @@ -0,0 +1,43 @@ +post: + tags: + - Empty users + summary: empty_user + operationId: empty_user + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/ParseUsers' + responses: + '201': + description: Success +# content: +# application/json: +# schema: +# type: object +# properties: +# data: +# type: object +# $ref: '#/components/schemas/User' + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '500': + $ref: "#/components/responses/InternalError" + diff --git a/docs/spec/paths/integrations@ccp-svc@users@settings.yaml b/docs/spec/paths/integrations@ccp-svc@users@settings.yaml new file mode 100644 index 00000000..1efebeb4 --- /dev/null +++ b/docs/spec/paths/integrations@ccp-svc@users@settings.yaml @@ -0,0 +1,35 @@ +post: + tags: + - Set user's setting + summary: users_setting + operationId: setting + requestBody: + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + type: object + $ref: '#/components/schemas/Settings' + responses: + '204': + description: Success + '400': + description: Bad Request + content: + application/json: + schema: + type: object + required: + - errors + properties: + errors: + type: array + items: + $ref: "#/components/responses/BadRequest" + '500': + $ref: "#/components/responses/InternalError" + diff --git a/go.mod b/go.mod index 86c2a717..d15baa88 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/fatih/structs v1.1.0 github.com/go-chi/chi v4.1.2+incompatible github.com/go-chi/cors v1.2.1 + github.com/go-ozzo/ozzo-validation/v4 v4.2.1 github.com/google/jsonapi v0.0.0-20200226002910-c8283f632fb7 github.com/ipfs/go-ipfs-api v0.4.0 github.com/pkg/errors v0.9.1 @@ -28,7 +29,6 @@ require ( gitlab.com/distributed_lab/urlval v3.0.0+incompatible golang.org/x/oauth2 v0.6.0 google.golang.org/api v0.44.0 - gopkg.in/gographics/imagick.v3 v3.4.2 ) require ( @@ -47,7 +47,6 @@ require ( github.com/getsentry/sentry-go v0.18.0 // indirect github.com/go-gorp/gorp/v3 v3.1.0 // indirect github.com/go-ole/go-ole v1.2.1 // indirect - github.com/go-ozzo/ozzo-validation/v4 v4.2.1 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect diff --git a/go.sum b/go.sum index 254c8193..11b3e1a7 100644 --- a/go.sum +++ b/go.sum @@ -1107,8 +1107,6 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= -gopkg.in/gographics/imagick.v3 v3.4.2 h1:vk6oildvhRBVSBfQ4X3raJstApYSeK6CZsyzoSOZk58= -gopkg.in/gographics/imagick.v3 v3.4.2/go.mod h1:+Q9nyA2xRZXrDyTtJ/eko+8V/5E7bWYs08ndkZp8UmA= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/internal/assets/migrations/001_initial.sql b/internal/assets/migrations/001_initial.sql index b2e15238..9b4bb962 100644 --- a/internal/assets/migrations/001_initial.sql +++ b/internal/assets/migrations/001_initial.sql @@ -1,17 +1,17 @@ -- +migrate Up CREATE TABLE users ( - id SERIAL PRIMARY KEY, - name VARCHAR(50), - token TEXT, - code TEXT + id SERIAL PRIMARY KEY, + name VARCHAR(50), + token TEXT, + code TEXT ); CREATE TABLE template ( - id SERIAL PRIMARY KEY, - user_id INTEGER REFERENCES users(id), - template TEXT, - img_bytes text, - name TEXT + id SERIAL PRIMARY KEY, + user_id INTEGER REFERENCES users(id), + template TEXT, + img_bytes text, + name TEXT ); -- +migrate Down diff --git a/internal/cli/main.go b/internal/cli/main.go index 3ffd500a..a16854a5 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -1,12 +1,11 @@ package cli import ( - "fmt" "github.com/alecthomas/kingpin" "gitlab.com/distributed_lab/kit/kv" "gitlab.com/distributed_lab/logan/v3" "gitlab.com/tokend/course-certificates/ccp/internal/config" - "gitlab.com/tokend/course-certificates/ccp/internal/service" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api" ) func Run(args []string) bool { @@ -38,11 +37,9 @@ func Run(args []string) bool { return false } - fmt.Println(serviceCmd.FullCommand()) - switch cmd { case serviceCmd.FullCommand(): - service.Run(cfg) + api.Run(cfg) case migrateUpCmd.FullCommand(): err = MigrateUp(cfg) case migrateDownCmd.FullCommand(): diff --git a/internal/config/main.go b/internal/config/main.go index 653902e6..bb2e99d1 100644 --- a/internal/config/main.go +++ b/internal/config/main.go @@ -21,6 +21,8 @@ type Config interface { NetworksConfiger ExamsConfiger pgdb.Databaser + SbtConfiger + StaticConfiger } type config struct { @@ -37,11 +39,14 @@ type config struct { NetworksConfiger getter kv.Getter comfig.Listenerer + SbtConfiger + StaticConfiger } func New(getter kv.Getter) Config { return &config{ getter: getter, + StaticConfiger: NewStaticConfiger(getter), ExamsConfiger: NewExamsConfiger(getter), TitlesConfiger: NewTitlesConfiger(getter), Listenerer: comfig.NewListenerer(getter), @@ -54,5 +59,6 @@ func New(getter kv.Getter) Config { NetworksConfiger: NewEthRPCConfiger(getter), Databaser: pgdb.NewDatabaser(getter), Logger: comfig.NewLogger(getter, comfig.LoggerOpts{}), + SbtConfiger: NewSbtConfiger(getter), } } diff --git a/internal/config/networks.go b/internal/config/networks.go index 121e39a8..01747176 100644 --- a/internal/config/networks.go +++ b/internal/config/networks.go @@ -15,10 +15,11 @@ type NetworksConfiger interface { } type NetworksConfig struct { - RPCEthEndpoint *ethclient.Client `fig:"rpc_eth"` - IPFSEndpoint string `fig:"ipfs"` - IpfsPrId string `fig:"ipfs_pr_id"` - IpfsPrKey string `fig:"ipfs_pr_key"` + RPCEthEndpoint *ethclient.Client `fig:"rpc_eth"` + IpfsEndpoint string `fig:"ipfs"` + IpfsPrId string `fig:"ipfs_pr_id"` + IpfsPrKey string `fig:"ipfs_pr_key"` + IpfsDisplayFileDomen string `fig:"ipfs_file_display_domen"` } func NewEthRPCConfiger(getter kv.Getter) NetworksConfiger { diff --git a/internal/config/sbt.go b/internal/config/sbt.go new file mode 100644 index 00000000..0160c2b5 --- /dev/null +++ b/internal/config/sbt.go @@ -0,0 +1,39 @@ +package config + +import ( + "gitlab.com/distributed_lab/figure/v3" + "gitlab.com/distributed_lab/kit/comfig" + "gitlab.com/distributed_lab/kit/kv" + "gitlab.com/distributed_lab/logan/v3/errors" +) + +type SbtConfiger interface { + SbtConfig() *SbtConfig +} + +type SbtConfig struct { + ExternalURL string `fig:"external_url" ` +} + +func NewSbtConfiger(getter kv.Getter) SbtConfiger { + return &sbtConfiger{ + getter: getter, + } +} + +type sbtConfiger struct { + getter kv.Getter + once comfig.Once +} + +func (c *sbtConfiger) SbtConfig() *SbtConfig { + return c.once.Do(func() interface{} { + raw := kv.MustGetStringMap(c.getter, "sbt") + config := SbtConfig{} + err := figure.Out(&config).From(raw).Please() + if err != nil { + panic(errors.Wrap(err, "failed to figure out")) + } + return &config + }).(*SbtConfig) +} diff --git a/internal/config/static.go b/internal/config/static.go new file mode 100644 index 00000000..7dc2b348 --- /dev/null +++ b/internal/config/static.go @@ -0,0 +1,39 @@ +package config + +import ( + "github.com/pkg/errors" + "gitlab.com/distributed_lab/figure/v3" + "gitlab.com/distributed_lab/kit/comfig" + "gitlab.com/distributed_lab/kit/kv" +) + +type StaticConfiger interface { + StaticConfig() *StaticConfig +} + +type StaticConfig struct { + Location string `fig:"location"` +} + +func NewStaticConfiger(getter kv.Getter) StaticConfiger { + return &staticConfig{ + getter: getter, + } +} + +type staticConfig struct { + getter kv.Getter + once comfig.Once +} + +func (c *staticConfig) StaticConfig() *StaticConfig { + return c.once.Do(func() interface{} { + raw := kv.MustGetStringMap(c.getter, "static") + config := StaticConfig{} + err := figure.Out(&config).From(raw).Please() + if err != nil { + panic(errors.Wrap(err, "failed to figure out")) + } + return &config + }).(*StaticConfig) +} diff --git a/internal/data/client.go b/internal/data/client.go index 224e0e97..4bf8486f 100644 --- a/internal/data/client.go +++ b/internal/data/client.go @@ -3,10 +3,10 @@ package data type ClientQ interface { New() ClientQ Get() (*Client, error) - Insert(data *Client) (int64, error) - GetByID(hash string) (*Client, error) - GetByName(name string) (*Client, error) + Insert(data *Client) error Update(data *Client) error + FilterByName(name string) ClientQ + FilterByID(id int64) ClientQ } type Client struct { diff --git a/internal/data/master.go b/internal/data/master.go new file mode 100644 index 00000000..dde7417b --- /dev/null +++ b/internal/data/master.go @@ -0,0 +1,8 @@ +package data + +type MasterQ interface { + New() MasterQ + ClientQ() ClientQ + TemplateQ() TemplateQ + Transaction(func(data interface{}) error, interface{}) error +} diff --git a/internal/data/pg/client.go b/internal/data/pg/client.go index 21ebf84b..9b47c0d0 100644 --- a/internal/data/pg/client.go +++ b/internal/data/pg/client.go @@ -5,83 +5,87 @@ import ( "fmt" sq "github.com/Masterminds/squirrel" "github.com/fatih/structs" + "github.com/pkg/errors" "gitlab.com/distributed_lab/kit/pgdb" "gitlab.com/tokend/course-certificates/ccp/internal/data" - "sync" ) const clientTableName = "users" +const ( + idField = "id" + nameField = "name" + tokenField = "token" + codeField = "code" +) + func NewClientQ(db *pgdb.DB) data.ClientQ { return &ClientQ{ - db: db.Clone(), + db: db, sql: sq.Select("b.*").From(fmt.Sprintf("%s as b", clientTableName)), + upd: sq.Update(clientTableName), } } type ClientQ struct { - mx sync.Mutex db *pgdb.DB sql sq.SelectBuilder + upd sq.UpdateBuilder } func (q *ClientQ) New() data.ClientQ { - q.mx.Lock() - defer q.mx.Unlock() - return NewClientQ(q.db) + return NewClientQ(q.db.Clone()) } func (q *ClientQ) Get() (*data.Client, error) { - q.mx.Lock() - defer q.mx.Unlock() var result data.Client err := q.db.Get(&result, q.sql) if err == sql.ErrNoRows { return nil, nil } - return &result, err + if err != nil { + return nil, errors.Wrap(err, "failed to get client") + } + + return &result, nil } func (q *ClientQ) Update(client *data.Client) error { clauses := structs.Map(client) - stmt := sq.Update(clientTableName).SetMap(clauses).Where(sq.Eq{"id": client.ID}) - err := q.db.Exec(stmt) + if err := q.db.Exec(q.upd.SetMap(clauses)); err != nil { + return errors.Wrap(err, "failed to update client") + } - return err + return nil } -func (q *ClientQ) Insert(value *data.Client) (int64, error) { +func (q *ClientQ) Insert(value *data.Client) error { clauses := structs.Map(value) var id int64 - stmt := sq.Insert(clientTableName).SetMap(clauses).Suffix("returning id") - err := q.db.Get(&id, stmt) + if err := q.db.Get(&id, sq.Insert(clientTableName).SetMap(clauses).Suffix("returning id")); err != nil { + return errors.Wrap(err, "failed to insert client") + } - return id, err + return nil } -func (q *ClientQ) GetByID(id string) (*data.Client, error) { +func (q *ClientQ) FilterByID(id int64) data.ClientQ { + q.sql = q.sql.Where(sq.Eq{idField: id}) + q.upd = q.upd.Where(sq.Eq{idField: id}) - var result data.Client - err := q.db.Get(&result, sq.Select("*").From(clientTableName).Where(sq.Eq{"id": id})) - if err == sql.ErrNoRows { - return nil, nil - } - return &result, err + return q } -func (q *ClientQ) GetByName(name string) (*data.Client, error) { - var result data.Client - err := q.db.Get(&result, sq.Select("*").From(clientTableName).Where(sq.Eq{"name": name})) - if err == sql.ErrNoRows { - return nil, nil - } - return &result, err +func (q *ClientQ) FilterByName(name string) data.ClientQ { + q.sql = q.sql.Where(sq.Eq{nameField: name}) + q.upd = q.upd.Where(sq.Eq{nameField: name}) + + return q } func (q *ClientQ) Page(pageParams pgdb.OffsetPageParams) data.ClientQ { - q.mx.Lock() - defer q.mx.Unlock() - q.sql = pageParams.ApplyTo(q.sql, "id") + q.sql = pageParams.ApplyTo(q.sql, idField) + return q } diff --git a/internal/data/pg/master.go b/internal/data/pg/master.go new file mode 100644 index 00000000..f541b9fb --- /dev/null +++ b/internal/data/pg/master.go @@ -0,0 +1,38 @@ +package pg + +import ( + "database/sql" + "gitlab.com/distributed_lab/kit/pgdb" + "gitlab.com/tokend/course-certificates/ccp/internal/data" +) + +type masterQ struct { + db *pgdb.DB +} + +func NewMasterQ(db *pgdb.DB) data.MasterQ { + return &masterQ{ + db: db, + } +} + +func (q *masterQ) New() data.MasterQ { + return NewMasterQ(q.db) + //return NewMasterQ(q.db).New() +} + +func (q *masterQ) ClientQ() data.ClientQ { + return NewClientQ(q.db) +} + +func (q *masterQ) TemplateQ() data.TemplateQ { + return NewTemplateQ(q.db) +} + +func (q *masterQ) Transaction(fn func(data interface{}) error, data interface{}) error { + return q.db.TransactionWithOptions(&sql.TxOptions{ + Isolation: sql.LevelSerializable, + }, func() error { + return fn(data) + }) +} diff --git a/internal/data/pg/template.go b/internal/data/pg/template.go index bf48412e..0bd3c4a2 100644 --- a/internal/data/pg/template.go +++ b/internal/data/pg/template.go @@ -5,96 +5,102 @@ import ( "fmt" sq "github.com/Masterminds/squirrel" "github.com/fatih/structs" + "github.com/pkg/errors" "gitlab.com/distributed_lab/kit/pgdb" "gitlab.com/tokend/course-certificates/ccp/internal/data" - "sync" ) -const tempalteTableName = "template" +const templateTableName = "template" + +const ( + userIDField = "user_id" +) func NewTemplateQ(db *pgdb.DB) data.TemplateQ { return &TemplateQ{ - db: db.Clone(), - sql: sq.Select("b.*").From(fmt.Sprintf("%s as b", clientTableName)), + db: db, + sql: sq.Select("b.*").From(fmt.Sprintf("%s as b", templateTableName)), + upd: sq.Update(templateTableName), } } type TemplateQ struct { - mx sync.Mutex db *pgdb.DB sql sq.SelectBuilder + upd sq.UpdateBuilder } func (q *TemplateQ) New() data.TemplateQ { - q.mx.Lock() - defer q.mx.Unlock() - return NewTemplateQ(q.db) + return NewTemplateQ(q.db.Clone()) } func (q *TemplateQ) Get() (*data.Template, error) { - q.mx.Lock() - defer q.mx.Unlock() var result data.Template err := q.db.Get(&result, q.sql) if err == sql.ErrNoRows { return nil, nil } - return &result, err + + if err != nil { + return nil, errors.Wrap(err, "failed to get template") + } + + return &result, nil } func (q *TemplateQ) Update(client *data.Template) error { clauses := structs.Map(client) - stmt := sq.Update(tempalteTableName).SetMap(clauses).Where(sq.Eq{"id": client.ID}) - err := q.db.Exec(stmt) - - return err -} + if err := q.db.Exec(q.upd.SetMap(clauses)); err != nil { + return errors.Wrap(err, "failed to update template") + } -func (q *TemplateQ) FilterByUser(id int64) data.TemplateQ { - q.sql = q.sql.Where(sq.Eq{"user_id": id}) - return q + return nil } -func (q *TemplateQ) Select(id int64) ([]data.Template, error) { +func (q *TemplateQ) Select() ([]data.Template, error) { var result []data.Template - stmt := sq.Select("*").From(tempalteTableName).Where(sq.Eq{"user_id": id}) - err := q.db.Select(&result, stmt) + err := q.db.Select(&result, q.sql) + if err != nil { + return nil, errors.Wrap(err, "failed to select templates") + } - return result, err + return result, nil } -func (q *TemplateQ) Insert(value *data.Template) (int64, error) { +func (q *TemplateQ) Insert(value *data.Template) error { clauses := structs.Map(value) var id int64 - stmt := sq.Insert(tempalteTableName).SetMap(clauses).Suffix("returning id") - err := q.db.Get(&id, stmt) + if err := q.db.Get(&id, sq.Insert(templateTableName).SetMap(clauses).Suffix("returning id")); err != nil { + return errors.Wrap(err, "failed to insert template ") + } - return id, err + return nil } -func (q *TemplateQ) GetByUserID(id string) (*data.Template, error) { - var result data.Template - err := q.db.Get(&result, sq.Select("*").From(tempalteTableName).Where(sq.Eq{"user_id": id})) - if err == sql.ErrNoRows { - return nil, nil - } - return &result, err +func (q *TemplateQ) Page(pageParams pgdb.OffsetPageParams) data.TemplateQ { + q.sql = pageParams.ApplyTo(q.sql, idField) + + return q } -func (q *TemplateQ) GetByName(name string, clientID int64) (*data.Template, error) { - var result data.Template - err := q.db.Get(&result, sq.Select("*").From(tempalteTableName).Where(sq.Eq{"name": name, "user_id": clientID})) - if err == sql.ErrNoRows { - return nil, nil - } - return &result, err +func (q *TemplateQ) FilterByUser(id int64) data.TemplateQ { + q.sql = q.sql.Where(sq.Eq{userIDField: id}) + + return q } -func (q *TemplateQ) Page(pageParams pgdb.OffsetPageParams) data.TemplateQ { - q.mx.Lock() - defer q.mx.Unlock() - q.sql = pageParams.ApplyTo(q.sql, "id") +func (q *TemplateQ) FilterByID(id int64) data.TemplateQ { + q.sql = q.sql.Where(sq.Eq{idField: id}) + q.upd = q.upd.Where(sq.Eq{idField: id}) + + return q +} + +func (q *TemplateQ) FilterByName(name string) data.TemplateQ { + q.sql = q.sql.Where(sq.Eq{nameField: name}) + q.upd = q.upd.Where(sq.Eq{nameField: name}) + return q } diff --git a/internal/data/template.go b/internal/data/template.go index 17f1932f..2b12a8d1 100644 --- a/internal/data/template.go +++ b/internal/data/template.go @@ -3,12 +3,12 @@ package data type TemplateQ interface { New() TemplateQ Get() (*Template, error) - Insert(data *Template) (int64, error) - GetByUserID(hash string) (*Template, error) - GetByName(name string, userID int64) (*Template, error) + Insert(data *Template) error Update(data *Template) error - Select(id int64) ([]Template, error) + Select() ([]Template, error) FilterByUser(ids int64) TemplateQ + FilterByName(name string) TemplateQ + FilterByID(ids int64) TemplateQ } type Template struct { diff --git a/internal/service/api/handlers/check_container_state.go b/internal/service/api/handlers/check_container_state.go new file mode 100644 index 00000000..403821af --- /dev/null +++ b/internal/service/api/handlers/check_container_state.go @@ -0,0 +1,77 @@ +package handlers + +import ( + "fmt" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" +) + +func CheckContainerState(w http.ResponseWriter, r *http.Request) { + containerID, err := requests.NewCheckContainerState(r) + if err != nil { + Log(r).WithError(err).Error("failed to generate template") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + + container := PdfCreator(r).CheckContainerState(containerID) + if container == nil { + Log(r).WithError(err).Error("user not found") + w.WriteHeader(http.StatusProcessing) + return + } + Log(r).Debug("container on handler: ", container) + + ape.Render(w, newUserWithImgResponse(container.Certificates, container.ID, container.Status)) +} + +func newUserWithImgResponse(users []*helpers.Certificate, id int, status string) resources.ContainerResponse { + usersData := make([]resources.User, 0) + for _, user := range users { + resp := resources.User{ + Key: resources.Key{ + ID: fmt.Sprintf("%x", user.ID), + Type: resources.PARSE_USERS, + }, + Attributes: resources.UserBlob{ //todo make better + Participant: user.Participant, + Date: user.Date, + CourseTitle: user.CourseTitle, + CertificateImg: user.ImageCertificate, + DigitalCertificate: user.DigitalCertificate, + Certificate: user.Certificate, + Points: user.Points, + Note: user.Note, + Signature: user.Signature, + Msg: user.Msg, + }, + } + usersData = append(usersData, resp) + } + + return resources.ContainerResponse{ + Data: resources.Container{ + Attributes: resources.ContainerAttributes{ + ContainerId: fmt.Sprintf("%d", id), + Certificates: usersData, + Status: status, + }, + }, + } + +} + +func newLinkResponse(link string) resources.LinkResponse { + data := resources.LinkResponse{ + Data: resources.Link{ + Attributes: resources.LinkAttributes{ + Link: link, + }, + }, + } + return data +} diff --git a/internal/service/api/handlers/create_template.go b/internal/service/api/handlers/create_template.go new file mode 100644 index 00000000..d3a62b8f --- /dev/null +++ b/internal/service/api/handlers/create_template.go @@ -0,0 +1,96 @@ +package handlers + +import ( + "encoding/base64" + "encoding/json" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/data" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" +) + +func CreateTemplate(w http.ResponseWriter, r *http.Request) { + template, backgroundImg, req, err := requests.NewGenerateTemplate(r) + if err != nil { + Log(r).WithError(err).Error("failed to generate template") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + defaultData := pdf.DefaultData + client, err := MasterQ(r).ClientQ().FilterByName(req.Data.Relationships.User).Get() + if err != nil { + Log(r).WithError(err).Error("failed to get client") + ape.RenderErr(w, problems.InternalError()) + return + } + if client == nil { + Log(r).WithError(err).Error("client is not found") + ape.RenderErr(w, problems.NotFound()) + return + } + + if template.Width == 0 || template.High == 0 { + tp := pdf.DefaultTemplateTall + _, _, imgBytes, err := tp.Prepare(defaultData, pdf.NewPDFConfig(Config(r)), MasterQ(r), backgroundImg, client.ID, StaticConfiger(r).Location) + if err != nil { + Log(r).WithError(err).Error("failed to prepare pdf") + ape.RenderErr(w, problems.InternalError()) + return + } + ape.Render(w, newTemplateImageResp(imgBytes)) + return + } + + file := pdf.NewPDF(template.High, template.Width) + + file.SetName(template.Name.X, template.Name.Y, template.Name.FontSize, template.Name.Font) + file.SetDate(template.Date.X, template.Date.Y, template.Date.FontSize, template.Date.Font) + file.SetCourse(template.Course.X, template.Course.Y, template.Course.FontSize, template.Course.Font) + file.SetCredits(template.Credits.X, template.Credits.Y, template.Credits.FontSize, template.Credits.Font) + file.SetExam(template.Exam.X, template.Exam.Y, template.Exam.FontSize, template.Exam.Font) + file.SetLevel(template.Level.X, template.Level.Y, template.Level.FontSize, template.Level.Font) + file.SetSerialNumber(template.SerialNumber.X, template.SerialNumber.Y, template.SerialNumber.FontSize, template.SerialNumber.Font) + file.SetPoints(template.Points.X, template.Points.Y, template.Points.FontSize, template.Points.Font) + file.SetQR(template.QR.X, template.QR.Y, template.QR.FontSize, template.QR.High, template.Width) + _, _, imgBytes, err := template.Prepare(defaultData, pdf.NewPDFConfig(Config(r)), MasterQ(r), backgroundImg, client.ID, StaticConfiger(r).Location) + if err != nil { + Log(r).WithError(err).Error("failed to prepare pdf") + ape.RenderErr(w, problems.InternalError()) + return + } + if req.Data.Attributes.IsCompleted { + templateBytes, err := json.Marshal(template) + if err != nil { + Log(r).WithError(err).Error("failed to marshal") + ape.RenderErr(w, problems.InternalError()) + return + } + + err = MasterQ(r).TemplateQ().Insert(&data.Template{ + Template: templateBytes, + //ImgBytes: backgroundImg, + Name: req.Data.Attributes.TemplateName, + UserID: client.ID, + }) + if err != nil { + Log(r).WithError(err).Error("failed to insert template") + ape.RenderErr(w, problems.InternalError()) + return + } + } + ape.Render(w, newTemplateImageResp(imgBytes)) + return +} + +func newTemplateImageResp(img []byte) resources.TemplateResponse { + return resources.TemplateResponse{ + Data: resources.Template{ + Attributes: resources.TemplateAttributes{ + BackgroundImg: base64.StdEncoding.EncodeToString(img), + }, + }, + } +} diff --git a/internal/service/helpers/ctx.go b/internal/service/api/handlers/ctx.go similarity index 50% rename from internal/service/helpers/ctx.go rename to internal/service/api/handlers/ctx.go index f284f460..06503f7c 100644 --- a/internal/service/helpers/ctx.go +++ b/internal/service/api/handlers/ctx.go @@ -1,10 +1,11 @@ -package helpers +package handlers import ( "context" "gitlab.com/distributed_lab/logan/v3" "gitlab.com/tokend/course-certificates/ccp/internal/config" "gitlab.com/tokend/course-certificates/ccp/internal/data" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" "net/http" ) @@ -13,8 +14,9 @@ type ctxKey int const ( logCtxKey ctxKey = iota configCtxKey - clientCtxKey - templateCtxKey + masterqCtxKey + pdfCreatorCtxKey + staticConfigerCtxKey ) func CtxLog(entry *logan.Entry) func(context.Context) context.Context { @@ -37,22 +39,32 @@ func Config(r *http.Request) config.Config { return r.Context().Value(configCtxKey).(config.Config) } -func CtxClientQ(entry data.ClientQ) func(context.Context) context.Context { +func CtxMasterQ(entry data.MasterQ) func(context.Context) context.Context { return func(ctx context.Context) context.Context { - return context.WithValue(ctx, clientCtxKey, entry) + return context.WithValue(ctx, masterqCtxKey, entry) } } -func ClientQ(r *http.Request) data.ClientQ { - return r.Context().Value(clientCtxKey).(data.ClientQ).New() +func MasterQ(r *http.Request) data.MasterQ { + return r.Context().Value(masterqCtxKey).(data.MasterQ).New() } -func CtxTemplateQ(entry data.TemplateQ) func(context.Context) context.Context { +func CtxPdfCreator(entry pdf.CreatorPDF) func(context.Context) context.Context { return func(ctx context.Context) context.Context { - return context.WithValue(ctx, templateCtxKey, entry) + return context.WithValue(ctx, pdfCreatorCtxKey, entry) } } -func TemplateQ(r *http.Request) data.TemplateQ { - return r.Context().Value(templateCtxKey).(data.TemplateQ).New() +func PdfCreator(r *http.Request) pdf.CreatorPDF { + return r.Context().Value(pdfCreatorCtxKey).(pdf.CreatorPDF) +} + +func CtxStaticConfiger(entry *config.StaticConfig) func(context.Context) context.Context { + return func(ctx context.Context) context.Context { + return context.WithValue(ctx, staticConfigerCtxKey, entry) + } +} + +func StaticConfiger(r *http.Request) *config.StaticConfig { + return r.Context().Value(staticConfigerCtxKey).(*config.StaticConfig) } diff --git a/internal/service/api/handlers/get_empty_users.go b/internal/service/api/handlers/get_empty_users.go new file mode 100644 index 00000000..8d7625c1 --- /dev/null +++ b/internal/service/api/handlers/get_empty_users.go @@ -0,0 +1,98 @@ +package handlers + +import ( + "fmt" + "github.com/google/jsonapi" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" +) + +func GetUsersEmpty(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewGetUsers(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse request") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + + client := google.NewGoogleClient(Config(r)) + + link, err := client.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) + if len(link) != 0 { + Log(r).WithError(err).Error("failed to authorize") + + ape.RenderErr(w, []*jsonapi.ErrorObject{{ + Title: "Forbidden", + Detail: "Invalid token", + Status: "403", + Meta: &map[string]interface{}{"auth_link": link}}, + }...) + + return + } + + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.InternalError()) + return + } + + users, errs := client.ParseFromWeb(req.Data.Attributes.Url, "A1:K") + if errs != nil { + Log(r).WithError(err).Error("failed to parse table: Errors:", errs) + ape.RenderErr(w, problems.InternalError()) + return + } + emptyUsers := make([]*helpers.Certificate, 0) + for id, user := range users { + user.ID = id + user.ShortCourseName = Config(r).TemplatesConfig()[user.CourseTitle] + if user.Certificate != "" { + Log(r).Debug("has already") + continue + } + user.Msg = fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle) + emptyUsers = append(emptyUsers, user) + } + + ape.Render(w, newUserResponse(emptyUsers)) +} + +func newUserResponse(users []*helpers.Certificate) resources.UserListResponse { + usersData := make([]resources.User, 0) + for _, user := range users { + resp := resources.User{ + Key: resources.Key{ + ID: fmt.Sprintf("%x", user.ID), + Type: resources.PARSE_USERS, + }, + Attributes: resources.UserBlob{ + Certificate: user.Certificate, + Id: int64(user.ID), + Points: user.Points, + Participant: user.Participant, + Msg: user.Msg, + SerialNumber: user.SerialNumber, + Note: user.Note, + DataHash: user.DataHash, + Signature: user.Signature, + TxHash: user.TxHash, + Date: user.Date, + CertificateImg: user.ImageCertificate, + CourseTitle: user.CourseTitle, + ShortCourse: user.ShortCourseName, + }, + } + usersData = append(usersData, resp) + } + + return resources.UserListResponse{ + Data: usersData, + } + +} diff --git a/internal/service/api/handlers/get_image.go b/internal/service/api/handlers/get_image.go new file mode 100644 index 00000000..02ea797c --- /dev/null +++ b/internal/service/api/handlers/get_image.go @@ -0,0 +1,64 @@ +package handlers + +import ( + "github.com/google/jsonapi" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" + "net/http" +) + +func GetImages(w http.ResponseWriter, r *http.Request) { + request, err := requests.NewPrepareCertificates(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse request ") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + + certificates := request.PrepareCertificates() + googleClient := google.NewGoogleClient(Config(r)) + + link, err := googleClient.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), request.Data.Attributes.Name) + if len(link) != 0 { + Log(r).WithError(err).Error("failed to authorize") + ape.RenderErr(w, []*jsonapi.ErrorObject{{ + Title: "Forbidden", + Detail: "Invalid token", + Status: "403", + Meta: &map[string]interface{}{"auth_link": link}}, + }...) + + return + } + + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.InternalError()) + return + } + + for _, certificate := range certificates { + if certificate.Certificate != "" { + file, err := googleClient.Download(certificate.Certificate) + if err != nil { + Log(r).WithError(err).Error("failed to download file") + ape.RenderErr(w, problems.InternalError()) + return + } + img, err := pdf.NewImageConverter().Convert(file) + if err != nil { + Log(r).WithError(err).Error("failed to convert") + ape.RenderErr(w, problems.InternalError()) + return + } + + certificate.ImageCertificate = img + } + + } + + ape.Render(w, newUserResponse(certificates)) +} diff --git a/internal/service/handlers/get_template_by_name.go b/internal/service/api/handlers/get_template_by_name.go similarity index 59% rename from internal/service/handlers/get_template_by_name.go rename to internal/service/api/handlers/get_template_by_name.go index 229cae10..6b656ab9 100644 --- a/internal/service/handlers/get_template_by_name.go +++ b/internal/service/api/handlers/get_template_by_name.go @@ -2,13 +2,10 @@ package handlers import ( "encoding/base64" - "fmt" - "github.com/pkg/errors" "gitlab.com/distributed_lab/ape" "gitlab.com/distributed_lab/ape/problems" "gitlab.com/tokend/course-certificates/ccp/internal/data" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" "gitlab.com/tokend/course-certificates/ccp/resources" "net/http" ) @@ -16,38 +13,37 @@ import ( func GetTemplateByName(w http.ResponseWriter, r *http.Request) { request, err := requests.NewGetTemplateByNameRequest(r) if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to parse request ")) + Log(r).WithError(err).Error("failed to parse request ") ape.Render(w, problems.BadRequest(err)) return } - client, err := helpers.ClientQ(r).GetByName(request.User) + client, err := MasterQ(r).ClientQ().FilterByName(request.User).Get() if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to get client")) + Log(r).WithError(err).Error("failed to get client") ape.Render(w, problems.InternalError()) return } if client == nil { - helpers.Log(r).Error(errors.Wrap(err, "client is not found")) + Log(r).WithError(err).Error("client is not found") ape.RenderErr(w, problems.NotFound()) return } - tmp, err := helpers.TemplateQ(r).GetByName(request.TemplateName, client.ID) + tmp, err := MasterQ(r).TemplateQ().FilterByName(request.TemplateName).FilterByUser(client.ID).Get() if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to select templates ")) + Log(r).WithError(err).Error("failed to select templates ") ape.Render(w, problems.InternalError()) return } if tmp != nil { - helpers.Log(r).Error(errors.Wrap(err, "template is not found")) + Log(r).WithError(err).Error("template is not found") ape.Render(w, problems.NotFound()) return } - helpers.Log(r).Debug("template: ", tmp.Template) - fmt.Println("template: ", tmp.Template) + Log(r).Debug("template: ", tmp.Template) ape.Render(w, newTemplateResp(tmp)) } diff --git a/internal/service/handlers/get_templates.go b/internal/service/api/handlers/get_templates.go similarity index 58% rename from internal/service/handlers/get_templates.go rename to internal/service/api/handlers/get_templates.go index b366bef8..b79c6301 100644 --- a/internal/service/handlers/get_templates.go +++ b/internal/service/api/handlers/get_templates.go @@ -1,12 +1,10 @@ package handlers import ( - "github.com/pkg/errors" "gitlab.com/distributed_lab/ape" "gitlab.com/distributed_lab/ape/problems" "gitlab.com/tokend/course-certificates/ccp/internal/data" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" "gitlab.com/tokend/course-certificates/ccp/resources" "net/http" ) @@ -14,28 +12,28 @@ import ( func GetTemplates(w http.ResponseWriter, r *http.Request) { userName, err := requests.NewGetTemplateRequest(r) if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to parse request ")) - ape.Render(w, problems.BadRequest(err)) + Log(r).WithError(err).Error("failed to parse request ") + ape.RenderErr(w, problems.BadRequest(err)...) return } - client, err := helpers.ClientQ(r).GetByName(userName.User) + client, err := MasterQ(r).ClientQ().FilterByName(userName.User).Get() if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to get client")) - ape.Render(w, problems.InternalError()) + Log(r).WithError(err).Error("failed to get client") + ape.RenderErr(w, problems.InternalError()) return } if client == nil { - helpers.Log(r).Error(errors.Wrap(err, "client is not found")) + Log(r).WithError(err).Error("client is not found") ape.RenderErr(w, problems.NotFound()) return } - tmps, err := helpers.TemplateQ(r).Select(client.ID) + tmps, err := MasterQ(r).TemplateQ().FilterByUser(client.ID).Select() if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to select templates ")) - ape.Render(w, problems.InternalError()) + Log(r).WithError(err).Error("failed to select templates ") + ape.RenderErr(w, problems.InternalError()) return } ape.Render(w, newTemlateListResp(tmps)) diff --git a/internal/service/handlers/get_users.go b/internal/service/api/handlers/get_users.go similarity index 51% rename from internal/service/handlers/get_users.go rename to internal/service/api/handlers/get_users.go index 795925dd..66b45a36 100644 --- a/internal/service/handlers/get_users.go +++ b/internal/service/api/handlers/get_users.go @@ -5,9 +5,9 @@ import ( "github.com/google/jsonapi" "gitlab.com/distributed_lab/ape" "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" "net/http" "strings" ) @@ -15,16 +15,16 @@ import ( func GetUsers(w http.ResponseWriter, r *http.Request) { req, err := requests.NewGetUsers(r) if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse request") + Log(r).WithError(err).Error("failed to parse request") ape.RenderErr(w, problems.BadRequest(err)...) return } - client := google.NewGoogleClient(helpers.Config(r)) - link, err := client.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) + client := google.NewGoogleClient(Config(r)) + link, err := client.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) if len(link) != 0 { - helpers.Log(r).WithError(err).Error("failed to authorize") + Log(r).WithError(err).Error("failed to authorize") ape.RenderErr(w, []*jsonapi.ErrorObject{{ Title: "Forbidden", @@ -35,53 +35,40 @@ func GetUsers(w http.ResponseWriter, r *http.Request) { return } - if err != nil { - helpers.Log(r).WithError(err).Error("failed to authorize") + Log(r).WithError(err).Error("failed to authorize") if strings.Contains(err.Error(), "unable to get client") { + Log(r).WithError(err).Error("failed to get client") ape.RenderErr(w, problems.NotFound()) return } if strings.Contains(err.Error(), "Token has been expired or revoked") { + Log(r).WithError(err).Error("failed to get client ") ape.RenderErr(w, problems.Unauthorized()) return } - helpers.Log(r).WithError(err).Error("failed to authorize") + Log(r).WithError(err).Error("failed to authorize") ape.RenderErr(w, problems.InternalError()) return } - users, errs := client.ParseFromWeb(req.Data.Url, "A1:K", helpers.Config(r).Log()) + users, errs := client.ParseFromWeb(req.Data.Attributes.Url, "A1:K") if errs != nil { - fmt.Println(errs[0].Error()) - if strings.Contains(errs[0].Error(), "400") { - helpers.Log(r).Error("token expired") + Log(r).WithError(err).Error("token expired or revoked") ape.RenderErr(w, problems.Unauthorized()) return } - helpers.Log(r).Error("failed to parse table: Errors:", errs) + + Log(r).Error("failed to parse table: Errors:", errs) ape.RenderErr(w, problems.BadRequest(err)...) return } - readyUsers := make([]*helpers.User, 0) + + readyUsers := make([]*helpers.Certificate, 0) for id, user := range users { user.ID = id - user.ShortCourseName = helpers.Config(r).TemplatesConfig()[user.CourseTitle] - - //file, err := client.Download(user.Certificate) - //if err != nil { - // helpers.Log(r).Error("failed to ", err) - // ape.Render(w, problems.BadRequest(err)) - // return - //} - //img, err := pdf.Convert("png", file) - //if err != nil { - // helpers.Log(r).Error("failed to convert", err) - // ape.Render(w, problems.BadRequest(err)) - // return - //} - //user.ImageCertificate = img + user.ShortCourseName = Config(r).TemplatesConfig()[user.CourseTitle] user.Msg = fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle) readyUsers = append(readyUsers, user) } diff --git a/internal/service/api/handlers/ipfs_upload.go b/internal/service/api/handlers/ipfs_upload.go new file mode 100644 index 00000000..7c6edd56 --- /dev/null +++ b/internal/service/api/handlers/ipfs_upload.go @@ -0,0 +1,54 @@ +package handlers + +import ( + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/ipfs" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" +) + +func UploadFileToIpfs(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewUploadFileToIPFS(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse data") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + connector := ipfs.NewConnector(Config(r).NetworksConfig()) + imgHash, err := connector.Upload(req.Data.Attributes.Img) + if err != nil { + Log(r).WithError(err).Error("failed to upload ") + ape.RenderErr(w, problems.InternalError()) + return + } + jsonHash, err := connector.PrepareJSON(req.Data.Attributes.Name, req.Data.Attributes.Description, Config(r).SbtConfig().ExternalURL, imgHash) + if err != nil { + Log(r).WithError(err).Error("failed to prepare json") + ape.RenderErr(w, problems.InternalError()) + return + } + + preparedURI, err := connector.Upload(jsonHash) + if err != nil { + Log(r).WithError(err).Error("failed to upload") + ape.RenderErr(w, problems.InternalError()) + return + } + + ape.Render(w, newIpfsUploadResponse(preparedURI)) +} + +func newIpfsUploadResponse(uri string) resources.IpfsFileResponse { + return resources.IpfsFileResponse{ + Data: resources.IpfsFile{ + Key: resources.Key{ + Type: resources.IPFS_FILE_UPLOAD, + }, + Attributes: resources.IpfsFileAttributes{ + Url: uri, + }, + }, + } +} diff --git a/internal/service/api/handlers/prepare_certificate.go b/internal/service/api/handlers/prepare_certificate.go new file mode 100644 index 00000000..31f7b5cf --- /dev/null +++ b/internal/service/api/handlers/prepare_certificate.go @@ -0,0 +1,57 @@ +package handlers + +import ( + "github.com/google/jsonapi" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" + "net/http" +) + +func PrepareCertificate(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewPrepareCertificates(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse data") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + certificates := req.PrepareCertificates() + + googleClient := google.NewGoogleClient(Config(r)) + link, err := googleClient.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.InternalError()) + return + } + + if len(link) != 0 { + Log(r).WithError(err).Error("failed to authorize") + ape.RenderErr(w, []*jsonapi.ErrorObject{{ + Title: "Forbidden", + Detail: "Invalid token", + Status: "403", + Meta: &map[string]interface{}{"auth_link": link}}, + }...) + + return + } + + client, err := MasterQ(r).ClientQ().FilterByName(req.Data.Attributes.Name).Get() + if err != nil { + Log(r).WithError(err).Error("failed to get client") + ape.RenderErr(w, problems.InternalError()) + return + } + if client == nil { + Log(r).WithError(err).Error("client is not found") + ape.RenderErr(w, problems.NotFound()) + return + } + + id := PdfCreator(r).NewContainer(certificates, googleClient, req.Data.Attributes.Address, req.Data.Attributes.Url, client, MasterQ(r), pdf.Generate) + + ape.Render(w, NewContainerResponse(id)) +} diff --git a/internal/service/api/handlers/set_settings.go b/internal/service/api/handlers/set_settings.go new file mode 100644 index 00000000..e6bd74d0 --- /dev/null +++ b/internal/service/api/handlers/set_settings.go @@ -0,0 +1,57 @@ +package handlers + +import ( + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/data" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "net/http" +) + +func SetSettings(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewSetSettings(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse request") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + + settings, err := MasterQ(r).ClientQ().FilterByName(req.Data.Attributes.Name).Get() + if err != nil { + Log(r).WithError(err).Error("failed to get settings") + ape.RenderErr(w, problems.InternalError()) + return + } + if settings == nil { + user := data.Client{ + Name: req.Data.Attributes.Name, + Code: req.Data.Attributes.Code, + } + if err = MasterQ(r).ClientQ().Insert(&user); err != nil { + Log(r).WithError(err).Error("failed to get settings") + ape.RenderErr(w, problems.InternalError()) + return + } + w.WriteHeader(204) + return + } + settings.Code = req.Data.Attributes.Code + err = MasterQ(r).ClientQ().FilterByID(settings.ID).Update(settings) + if err != nil { + Log(r).WithError(err).Error("failed to update settings") + ape.RenderErr(w, problems.InternalError()) + return + } + if req.Data.Attributes.Code != "" { + client := google.NewGoogleClient(Config(r)) + _, err = client.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.InternalError()) + return + } + } + w.WriteHeader(204) + return +} diff --git a/internal/service/api/handlers/updare_token.go b/internal/service/api/handlers/updare_token.go new file mode 100644 index 00000000..37b2ac2c --- /dev/null +++ b/internal/service/api/handlers/updare_token.go @@ -0,0 +1,59 @@ +package handlers + +import ( + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "net/http" +) + +func UpdateToken(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewUpdateTokenRequest(r) + if err != nil { + Log(r).WithError(err).Error("failed to parse request") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + + userInfo, err := MasterQ(r).ClientQ().FilterByName(req.Data.Attributes.Name).Get() + if err != nil { + Log(r).WithError(err).Error("failed to get user") + ape.RenderErr(w, problems.InternalError()) + return + } + + if userInfo == nil { + Log(r).WithError(err).Error("user is not found") + ape.RenderErr(w, problems.NotFound()) + return + } + + userInfo.Token = nil + userInfo.Code = req.Data.Attributes.Code + + err = MasterQ(r).ClientQ().FilterByID(userInfo.ID).Update(userInfo) + if err != nil { + Log(r).WithError(err).Error("failed to update user") + ape.RenderErr(w, problems.InternalError()) + return + } + + client := google.NewGoogleClient(Config(r)) + link, err := client.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) + + if len(link) != 0 { + ape.Render(w, newLinkResponse(link)) + w.WriteHeader(http.StatusNoContent) + return + } + + if err != nil { + Log(r).WithError(err).Error("failed to connect to google") + ape.RenderErr(w, problems.InternalError()) + return + } + + ape.RenderErr(w, problems.InternalError()) + +} diff --git a/internal/service/api/handlers/update_certificate.go b/internal/service/api/handlers/update_certificate.go new file mode 100644 index 00000000..e8edc9ba --- /dev/null +++ b/internal/service/api/handlers/update_certificate.go @@ -0,0 +1,89 @@ +package handlers + +import ( + "fmt" + "github.com/google/jsonapi" + "gitlab.com/distributed_lab/ape" + "gitlab.com/distributed_lab/ape/problems" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/requests" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" +) + +func UpdateCertificate(w http.ResponseWriter, r *http.Request) { + req, err := requests.NewPrepareCertificates(r) + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.BadRequest(err)...) + return + } + certificates := req.PrepareCertificates() + + googleClient := google.NewGoogleClient(Config(r)) + link, err := googleClient.Connect(Config(r).Google().SecretPath, MasterQ(r).ClientQ(), req.Data.Attributes.Name) + if err != nil { + Log(r).WithError(err).Error("failed to connect") + ape.RenderErr(w, problems.InternalError()) + return + } + + if len(link) != 0 { + Log(r).WithError(err).Error("failed to authorize") + ape.RenderErr(w, []*jsonapi.ErrorObject{{ + Title: "Forbidden", + Detail: "Invalid token", + Status: "403", + Meta: &map[string]interface{}{"auth_link": link}}, + }...) + + return + } + + client, err := MasterQ(r).ClientQ().FilterByName(req.Data.Attributes.Name).Get() + Log(r).Debug("user ", client) + if err != nil { + Log(r).WithError(err).Error("failed to get user") + ape.Render(w, problems.InternalError()) + return + } + if client == nil { + Log(r).WithError(err).Error("user is not found") + ape.Render(w, problems.NotFound()) + return + } + + for _, certificate := range certificates { + if certificate.Certificate != "" { + file, err := googleClient.Download(certificate.Certificate) + if err != nil { + Log(r).WithError(err).Error("failed to download file ") + ape.Render(w, problems.BadRequest(err)) + return + } + img, err := pdf.NewImageConverter().Convert(file) + if err != nil { + Log(r).WithError(err).Error("failed to convert") + ape.Render(w, problems.BadRequest(err)) + return + } + + certificate.ImageCertificate = img + } + } + + id := PdfCreator(r).NewContainer(certificates, googleClient, req.Data.Attributes.Address, req.Data.Attributes.Url, client, MasterQ(r), pdf.Update) + + ape.Render(w, NewContainerResponse(id)) +} + +func NewContainerResponse(id int) resources.ContainerResponse { + return resources.ContainerResponse{ + Data: resources.Container{ + Attributes: resources.ContainerAttributes{ + ContainerId: fmt.Sprintf("%d", id), + }, + }, + } +} diff --git a/internal/service/main.go b/internal/service/api/main.go similarity index 58% rename from internal/service/main.go rename to internal/service/api/main.go index 2c7f26c6..592bf69d 100644 --- a/internal/service/main.go +++ b/internal/service/api/main.go @@ -1,19 +1,22 @@ -package service +package api import ( + "context" "gitlab.com/distributed_lab/kit/copus/types" "gitlab.com/distributed_lab/logan/v3" "gitlab.com/distributed_lab/logan/v3/errors" "gitlab.com/tokend/course-certificates/ccp/internal/config" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" "net" "net/http" ) type service struct { - cfg config.Config - log *logan.Entry - listener net.Listener - copus types.Copus + cfg config.Config + log *logan.Entry + listener net.Listener + copus types.Copus + pdfCreator *pdf.CreatorPDFType } func (s *service) run(cfg config.Config) error { @@ -26,11 +29,15 @@ func (s *service) run(cfg config.Config) error { } func newService(cfg config.Config) *service { + + pdfCreator := pdf.NewPdfCreator(cfg.Log(), cfg) + go pdfCreator.Run(context.Background()) return &service{ - cfg: cfg, - log: cfg.Log(), - copus: cfg.Copus(), - listener: cfg.Listener(), + cfg: cfg, + log: cfg.Log(), + copus: cfg.Copus(), + listener: cfg.Listener(), + pdfCreator: pdfCreator, } } diff --git a/internal/service/api/requests/check_container_state.go b/internal/service/api/requests/check_container_state.go new file mode 100644 index 00000000..3061f43b --- /dev/null +++ b/internal/service/api/requests/check_container_state.go @@ -0,0 +1,31 @@ +package requests + +import ( + "github.com/go-chi/chi" + "github.com/pkg/errors" + "gitlab.com/distributed_lab/urlval" + "net/http" + "strconv" +) + +const ( + containerIDPathParam = "container" +) + +type CheckContainerState struct { + Container string `url:"-"` +} + +func NewCheckContainerState(r *http.Request) (int, error) { + request := CheckContainerState{} + if err := urlval.Decode(r.URL.Query(), &request); err != nil { + return -1, err + } + + request.Container = chi.URLParam(r, containerIDPathParam) + containerID, err := strconv.Atoi(request.Container) + if err != nil { + return -1, errors.Wrap(err, "failed to convert string to int ") + } + return containerID, err +} diff --git a/internal/service/api/requests/create_template.go b/internal/service/api/requests/create_template.go new file mode 100644 index 00000000..864635e9 --- /dev/null +++ b/internal/service/api/requests/create_template.go @@ -0,0 +1,71 @@ +package requests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/pkg/errors" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/pdf" + "gitlab.com/tokend/course-certificates/ccp/resources" + "image" + "image/jpeg" + "net/http" + "strings" +) + +type GenerateTemplate struct { + Data resources.Template +} + +func NewGenerateTemplate(r *http.Request) (pdf.PDF, []byte, GenerateTemplate, error) { + request := GenerateTemplate{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to decode raw request ") + } + + pdfTemplate := pdf.PDF{} + if err := json.Unmarshal(request.Data.Attributes.Template, &pdfTemplate); err != nil { + return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to decode template data") + } + + rawImg := strings.ReplaceAll(request.Data.Attributes.BackgroundImg, "data:image/jpeg;base64,", "") + rawImg = strings.ReplaceAll(rawImg, "data:image/png;base64,", "") + + imgBytes, err := base64toJpg(rawImg) + if err != nil { + return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to convert image") + } + + if err = validateTemplateData(request.Data); err != nil { + return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to validate data") + + } + return pdfTemplate, imgBytes, request, err +} + +func base64toJpg(data string) ([]byte, error) { + reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) + m, _, err := image.Decode(reader) + if err != nil { + return nil, err + } + + buf := new(bytes.Buffer) + if err = jpeg.Encode(buf, m, &jpeg.Options{Quality: 75}); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +func validateTemplateData(template resources.Template) error { + return MergeErrors(validation.Errors{ + "/attributes/is_completed": validation.Validate(template.Attributes.IsCompleted, + validation.Required), + "/attributes/template_name": validation.Validate(template.Attributes.TemplateName, + validation.Required), + "/attributes/background_img": validation.Validate(template.Attributes.BackgroundImg, + validation.Required), + }).Filter() +} diff --git a/internal/service/requests/get_template_by_name.go b/internal/service/api/requests/get_template_by_name.go similarity index 71% rename from internal/service/requests/get_template_by_name.go rename to internal/service/api/requests/get_template_by_name.go index 6a511b8b..578450c0 100644 --- a/internal/service/requests/get_template_by_name.go +++ b/internal/service/api/requests/get_template_by_name.go @@ -2,6 +2,7 @@ package requests import ( "github.com/go-chi/chi" + "gitlab.com/distributed_lab/logan/v3/errors" "gitlab.com/distributed_lab/urlval" "net/http" ) @@ -17,11 +18,11 @@ type GetTemplateByNameRequest struct { func NewGetTemplateByNameRequest(r *http.Request) (GetTemplateByNameRequest, error) { request := GetTemplateByNameRequest{} - err := urlval.Decode(r.URL.Query(), &request) - if err != nil { - return request, err + if err := urlval.Decode(r.URL.Query(), &request); err != nil { + return request, errors.Wrap(err, "failed to decode data") } request.User = chi.URLParam(r, UserPathParam) request.TemplateName = chi.URLParam(r, NamePathParam) - return request, err + + return request, nil } diff --git a/internal/service/requests/get_templates.go b/internal/service/api/requests/get_templates.go similarity index 67% rename from internal/service/requests/get_templates.go rename to internal/service/api/requests/get_templates.go index fefed9b0..3aba7106 100644 --- a/internal/service/requests/get_templates.go +++ b/internal/service/api/requests/get_templates.go @@ -2,6 +2,7 @@ package requests import ( "github.com/go-chi/chi" + "github.com/pkg/errors" "gitlab.com/distributed_lab/urlval" "net/http" ) @@ -16,10 +17,10 @@ type GetTemplateRequest struct { func NewGetTemplateRequest(r *http.Request) (GetTemplateRequest, error) { request := GetTemplateRequest{} - err := urlval.Decode(r.URL.Query(), &request) - if err != nil { - return request, err + if err := urlval.Decode(r.URL.Query(), &request); err != nil { + return request, errors.Wrap(err, "failed to decode query") } request.User = chi.URLParam(r, UserPathParam) - return request, err + + return request, nil } diff --git a/internal/service/api/requests/ipfs_upload.go b/internal/service/api/requests/ipfs_upload.go new file mode 100644 index 00000000..dbaf6796 --- /dev/null +++ b/internal/service/api/requests/ipfs_upload.go @@ -0,0 +1,38 @@ +package requests + +import ( + "encoding/json" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/pkg/errors" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" + "regexp" +) + +type IpfsFileUpload struct { + Data resources.IpfsFileUpload //todo replace string to []byte +} + +func NewUploadFileToIPFS(r *http.Request) (IpfsFileUpload, error) { + request := IpfsFileUpload{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return IpfsFileUpload{}, errors.Wrap(err, "failed to decode data") + } + + if err := validateIpfsData(request.Data); err != nil { + return IpfsFileUpload{}, errors.Wrap(err, "failed to validate data") + } + + return request, nil +} + +func validateIpfsData(request resources.IpfsFileUpload) error { + return MergeErrors(validation.Errors{ + "/attributes/description": validation.Validate(request.Attributes.Description, + validation.Required), + "/attributes/img": validation.Validate(request.Attributes.Img, + validation.Required), + "/attributes/name": validation.Validate(request.Attributes.Name, + validation.Required, validation.Match(regexp.MustCompile("^([A-Za-z])[A-Za-z\\s]+$"))), + }).Filter() +} diff --git a/internal/service/api/requests/parse_users.go b/internal/service/api/requests/parse_users.go new file mode 100644 index 00000000..9f67de15 --- /dev/null +++ b/internal/service/api/requests/parse_users.go @@ -0,0 +1,50 @@ +package requests + +import ( + "encoding/json" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/pkg/errors" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" + "regexp" + "strings" +) + +type ParseUsers struct { + Data resources.ParseUsers +} + +func NewGetUsers(r *http.Request) (ParseUsers, error) { + request := ParseUsers{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return ParseUsers{}, errors.Wrap(err, "failed to decode data") + } + + if err := validateParseData(request.Data); err != nil { + return ParseUsers{}, errors.Wrap(err, "failed to validate data") + } + + request.Data.Attributes.Url = request.parse() + + return request, nil +} + +func (g *ParseUsers) parse() string { + id := strings.Replace(g.Data.Attributes.Url, "https://docs.google.com/spreadsheets/d/", "", 1) + + index := strings.Index(id, "/") + if index != -1 { + id = id[:index] + } + + return id +} + +func validateParseData(request resources.ParseUsers) error { + return MergeErrors(validation.Errors{ + "/attributes/url": validation.Validate(request.Attributes.Url, + validation.Required), + "/attributes/name": validation.Validate(request.Attributes.Name, + validation.Required, validation.Match(regexp.MustCompile("^([A-Za-z])[A-Za-z\\s]+$"))), + }).Filter() +} diff --git a/internal/service/api/requests/prepare_certificates.go b/internal/service/api/requests/prepare_certificates.go new file mode 100644 index 00000000..1c721384 --- /dev/null +++ b/internal/service/api/requests/prepare_certificates.go @@ -0,0 +1,64 @@ +package requests + +import ( + "bytes" + "encoding/json" + "github.com/pkg/errors" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" + "strings" +) + +type PrepareCertificates struct { + Data resources.PrepareCertificates +} + +func NewPrepareCertificates(r *http.Request) (PrepareCertificates, error) { + request := PrepareCertificates{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return PrepareCertificates{}, errors.Wrap(err, "failed to decode data") + } + + request.Data.Attributes.Url = request.parse() + return request, nil +} + +func (p *PrepareCertificates) PrepareCertificates() []*helpers.Certificate { + result := make([]*helpers.Certificate, 0) + for _, user := range p.Data.Attributes.CertificatesData { + img, err := base64toJpg(bytes.NewBuffer(user.CertificateImg).String()) + if err != nil { + img = nil + } + resUser := helpers.Certificate{ + ID: int(user.Id), + Date: user.Date, + CourseTitle: user.CourseTitle, + TxHash: user.TxHash, + Signature: user.Signature, + DataHash: user.DataHash, + SerialNumber: user.SerialNumber, + Note: user.Note, + Msg: user.Msg, + Participant: user.Participant, + Points: user.Points, + Certificate: user.Certificate, + DigitalCertificate: user.DigitalCertificate, + ImageCertificate: img, + } + result = append(result, &resUser) + } + return result +} + +func (p *PrepareCertificates) parse() string { + id := strings.Replace(p.Data.Attributes.Url, "https://docs.google.com/spreadsheets/d/", "", 1) + + index := strings.Index(id, "/") + if index != -1 { + id = id[:index] + } + + return id +} diff --git a/internal/service/api/requests/set_settings.go b/internal/service/api/requests/set_settings.go new file mode 100644 index 00000000..5fd8800e --- /dev/null +++ b/internal/service/api/requests/set_settings.go @@ -0,0 +1,34 @@ +package requests + +import ( + "encoding/json" + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/pkg/errors" + "gitlab.com/tokend/course-certificates/ccp/resources" + "net/http" + "regexp" +) + +type SetSettings struct { + Data resources.Settings +} + +func NewSetSettings(r *http.Request) (SetSettings, error) { + request := SetSettings{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return SetSettings{}, errors.Wrap(err, "failed to decode data") + } + + if err := validateSettingsData(request.Data); err != nil { + return SetSettings{}, errors.Wrap(err, "failed to validate data") + } + + return request, nil +} + +func validateSettingsData(request resources.Settings) error { + return MergeErrors(validation.Errors{ + "/attributes/name": validation.Validate(request.Attributes.Name, + validation.Required, validation.Match(regexp.MustCompile("^([A-Za-z])[A-Za-z\\s]+$"))), + }).Filter() +} diff --git a/internal/service/requests/update_token_request.go b/internal/service/api/requests/update_token.go similarity index 57% rename from internal/service/requests/update_token_request.go rename to internal/service/api/requests/update_token.go index 29d0279a..27ceeec8 100644 --- a/internal/service/requests/update_token_request.go +++ b/internal/service/api/requests/update_token.go @@ -12,10 +12,14 @@ type UpdateTokenRequest struct { } func NewUpdateTokenRequest(r *http.Request) (UpdateTokenRequest, error) { - res := UpdateTokenRequest{} - err := json.NewDecoder(r.Body).Decode(&res) - if err != nil { + request := UpdateTokenRequest{} + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { return UpdateTokenRequest{}, errors.Wrap(err, "failed to decode data") } - return res, nil + + if err := validateSettingsData(request.Data); err != nil { + return UpdateTokenRequest{}, errors.Wrap(err, "failed to decode data") + } + + return request, nil } diff --git a/internal/service/api/requests/validation.go b/internal/service/api/requests/validation.go new file mode 100644 index 00000000..0cfc52a9 --- /dev/null +++ b/internal/service/api/requests/validation.go @@ -0,0 +1,13 @@ +package requests + +import validation "github.com/go-ozzo/ozzo-validation/v4" + +func MergeErrors(validationErrors ...validation.Errors) validation.Errors { + result := make(validation.Errors) + for _, errs := range validationErrors { + for key, err := range errs { + result[key] = err + } + } + return result +} diff --git a/internal/service/router.go b/internal/service/api/router.go similarity index 72% rename from internal/service/router.go rename to internal/service/api/router.go index 62a1b438..a43b7717 100644 --- a/internal/service/router.go +++ b/internal/service/api/router.go @@ -1,4 +1,4 @@ -package service +package api import ( "github.com/go-chi/chi" @@ -6,8 +6,7 @@ import ( "gitlab.com/distributed_lab/ape" "gitlab.com/tokend/course-certificates/ccp/internal/config" "gitlab.com/tokend/course-certificates/ccp/internal/data/pg" - "gitlab.com/tokend/course-certificates/ccp/internal/service/handlers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" + "gitlab.com/tokend/course-certificates/ccp/internal/service/api/handlers" ) func (s *service) router(cfg config.Config) chi.Router { @@ -18,10 +17,11 @@ func (s *service) router(cfg config.Config) chi.Router { ape.RecoverMiddleware(s.log), ape.LoganMiddleware(s.log), ape.CtxMiddleware( - helpers.CtxClientQ(pg.NewClientQ(s.cfg.DB())), - helpers.CtxTemplateQ(pg.NewTemplateQ(s.cfg.DB())), - helpers.CtxLog(s.log), - helpers.CtxConfig(cfg), + handlers.CtxMasterQ(pg.NewMasterQ(s.cfg.DB())), + handlers.CtxLog(s.log), + handlers.CtxPdfCreator(s.pdfCreator), + handlers.CtxConfig(cfg), + handlers.CtxStaticConfiger(cfg.StaticConfig()), ), ) @@ -37,6 +37,11 @@ func (s *service) router(cfg config.Config) chi.Router { r.Post("/", handlers.PrepareCertificate) r.Post("/bitcoin", handlers.UpdateCertificate) r.Post("/ipfs", handlers.UploadFileToIpfs) + r.Get("/{container}", handlers.CheckContainerState) + + r.Route("/image", func(r chi.Router) { + r.Post("/", handlers.GetImages) + }) r.Route("/template", func(r chi.Router) { r.Post("/", handlers.CreateTemplate) diff --git a/internal/service/google/google_connect.go b/internal/service/core/google/google_connect.go similarity index 67% rename from internal/service/google/google_connect.go rename to internal/service/core/google/google_connect.go index e7942c55..f0bc6a19 100644 --- a/internal/service/google/google_connect.go +++ b/internal/service/core/google/google_connect.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "gitlab.com/distributed_lab/logan/v3" "gitlab.com/distributed_lab/logan/v3/errors" "gitlab.com/tokend/course-certificates/ccp/internal/config" "gitlab.com/tokend/course-certificates/ccp/internal/data" @@ -12,7 +13,6 @@ import ( "google.golang.org/api/drive/v3" "google.golang.org/api/option" "google.golang.org/api/sheets/v4" - "log" "net/http" "os" ) @@ -23,8 +23,8 @@ type Google struct { cfg config.Config prefixPath string - sheetID string - + sheetID string + log *logan.Entry driveSrv *drive.Service sheetSrv *sheets.Service } @@ -32,6 +32,7 @@ type Google struct { func NewGoogleClient(cfg config.Config) *Google { g := Google{ cfg: cfg, + log: cfg.Log(), } return &g } @@ -43,13 +44,14 @@ func NewGoogleClientTest(prefixPath string) *Google { } func (g *Google) getClient(config *oauth2.Config, clientQ data.ClientQ, name string) (*http.Client, string, error) { - client, err := clientQ.GetByName(name) + client, err := clientQ.FilterByName(name).Get() if err != nil { return nil, "", errors.Wrap(err, "failed to get client") } if client == nil { return nil, "", errors.New("user not found") } + tok := &oauth2.Token{} if len(client.Token) == 0 { tok, link, err := g.getTokenFromWeb(config, client.Code) @@ -59,20 +61,19 @@ func (g *Google) getClient(config *oauth2.Config, clientQ data.ClientQ, name str if tok == nil { return nil, link, nil } + bf := new(bytes.Buffer) - err = json.NewEncoder(bf).Encode(tok) - if err != nil { + if err = json.NewEncoder(bf).Encode(tok); err != nil { return nil, "", errors.Wrap(err, "failed to decode token") } + client.Token = bf.Bytes() - err = clientQ.Update(client) - if err != nil { + if err = clientQ.FilterByID(client.ID).Update(client); err != nil { return nil, "", errors.Wrap(err, "failed to update") } } else { - log.Println("token already exist") - err = json.Unmarshal(client.Token, tok) - if err != nil { + g.log.Debug("token already exist") + if err = json.Unmarshal(client.Token, tok); err != nil { return nil, "", errors.Wrap(err, "failed to encode token") } } @@ -86,7 +87,8 @@ func (g *Google) getTokenFromWeb(config *oauth2.Config, code string) (*oauth2.To if code == "" { return nil, authURL, nil } - log.Println(code) + + g.log.Debug(code) tok, err := config.Exchange(context.TODO(), code) if err != nil { return nil, "", errors.New("failed to generate token") @@ -94,43 +96,18 @@ func (g *Google) getTokenFromWeb(config *oauth2.Config, code string) (*oauth2.To return tok, "", nil } -// Retrieves a token from a local file. -func (g *Google) tokenFromFile(file string) (*oauth2.Token, error) { - f, err := os.Open("token.json") - if err != nil { - return nil, errors.Wrap(err, "Failed to open token's file") - } - defer f.Close() - tok := &oauth2.Token{} - err = json.NewDecoder(f).Decode(tok) - if err != nil { - return nil, errors.Wrap(err, "Failed to parse file") - } - return tok, nil - -} - -func (g *Google) saveToken(path string, token *oauth2.Token) error { - f, err := os.OpenFile("token.json", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - return errors.Wrap(err, "Unable to cache oauth token") - } - defer f.Close() - json.NewEncoder(f).Encode(token) - return nil -} - func (g *Google) Connect(path string, clientQ data.ClientQ, name string) (string, error) { b, err := os.ReadFile(path) if err != nil { return "", errors.Wrap(err, "unable to read client secret file") } link := "" - config, err := google.ConfigFromJSON(b, drive.DriveScope, sheets.SpreadsheetsScope) + googleConfig, err := google.ConfigFromJSON(b, drive.DriveScope, sheets.SpreadsheetsScope) if err != nil { return "", errors.Wrap(err, "unable to parse client secret file to config") } - g.client, link, err = g.getClient(config, clientQ, name) + + g.client, link, err = g.getClient(googleConfig, clientQ, name) if err != nil { return link, errors.Wrap(err, "unable to get client") } @@ -140,21 +117,16 @@ func (g *Google) Connect(path string, clientQ data.ClientQ, name string) (string if len(link) != 0 { return link, nil } + g.driveSrv, err = drive.NewService(context.Background(), option.WithHTTPClient(g.client)) if err != nil { return "", errors.Wrap(err, "failed to create new drive service") } + g.sheetSrv, err = sheets.NewService(context.Background(), option.WithHTTPClient(g.client)) if err != nil { return "", errors.Wrap(err, "failed to create new sheet service") } - return "", nil -} -func (g *Google) ConnectSheetByKey(apiKey string) (*sheets.Service, error) { - sheetsService, err := sheets.NewService(context.Background(), option.WithAPIKey(apiKey)) - if err != nil { - return nil, errors.Wrap(err, "failed to connect") - } - return sheetsService, nil + return "", nil } diff --git a/internal/service/google/google_drive.go b/internal/service/core/google/google_drive.go similarity index 71% rename from internal/service/google/google_drive.go rename to internal/service/core/google/google_drive.go index a7a14bd1..e14e1fe9 100644 --- a/internal/service/google/google_drive.go +++ b/internal/service/core/google/google_drive.go @@ -6,7 +6,6 @@ import ( "github.com/pkg/errors" "google.golang.org/api/drive/v3" "io" - "net/http" "strings" "time" ) @@ -39,7 +38,6 @@ func (g *Google) CreateFolder(folderPath string) error { } func (g *Google) GetFiles() ([]*drive.File, error) { - r, err := g.driveSrv.Files.List().PageSize(10). Fields("nextPageToken, files(id, name)").Do() if err != nil { @@ -68,40 +66,24 @@ func (g *Google) GetFile(url string) (*drive.File, error) { } func (g *Google) Download(url string) ([]byte, error) { - //f, err := g.driveSrv.Files.Export(g.googleParseURl(url), "application/pdf").Download() - - // Get the file metadata to retrieve the file name and download URL - file, err := g.driveSrv.Files.Get(g.googleParseURl(url)).Fields("name, webContentLink").Do() + file, err := g.driveSrv.Files.Get(g.googleParseURl(url)).Download() if err != nil { - fmt.Println("Unable to retrieve file metadata: ", err) - return nil, err + return nil, errors.Wrap(err, "failed to get file data") } - // Download the file content - resp, err := http.Get(file.WebContentLink) - if err != nil { - fmt.Println("Unable to download file: ", err) - return nil, err - } - defer resp.Body.Close() + defer file.Body.Close() out := new(bytes.Buffer) + _, err = io.Copy(out, file.Body) if err != nil { - fmt.Println("Unable to create file: ", err) - return nil, err - } - - _, err = io.Copy(out, resp.Body) - if err != nil { - fmt.Println("Unable to save file: ", err) - return nil, err + return nil, errors.Wrap(err, "Unable to save file") } return out.Bytes(), nil } func (g *Google) googleParseURl(url string) string { - id := strings.Replace(url, "https://drive.google.com/file/d/", "", 1) + id := strings.Replace(url, "drive.google.com/file/d/", "", 1) id = strings.Replace(id, "/view", "", 1) return id } diff --git a/internal/service/google/google_speets.go b/internal/service/core/google/google_speets.go similarity index 56% rename from internal/service/google/google_speets.go rename to internal/service/core/google/google_speets.go index ae5870ea..99f62274 100644 --- a/internal/service/google/google_speets.go +++ b/internal/service/core/google/google_speets.go @@ -3,34 +3,17 @@ package google import ( "fmt" "github.com/pkg/errors" - "gitlab.com/distributed_lab/logan/v3" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" "google.golang.org/api/sheets/v4" - "log" "reflect" "time" ) -func (g *Google) GetTable(readRange, spreadsheetId string) error { - - resp, err := g.sheetSrv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do() - if err != nil { - log.Fatalf("Unable to retrieve data from sheet: %v", err) - } - - if len(resp.Values) == 0 { - - } else { - log.Println(resp.Values) - } - return nil -} - -func (g *Google) ParseFromWeb(spreadsheetId, readRange string, log *logan.Entry) ([]*helpers.User, []error) { +func (g *Google) ParseFromWeb(spreadsheetId, readRange string) ([]*helpers.Certificate, []error) { errs := make([]error, 0) resp, err := g.sheetSrv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do() if err != nil { - log.Info("Unable to retrieve data from sheet: %v", err) + g.log.Info("Unable to retrieve data from sheet: %v", err) errs = append(errs, err) return nil, errs } @@ -38,19 +21,15 @@ func (g *Google) ParseFromWeb(spreadsheetId, readRange string, log *logan.Entry) if len(resp.Values) == 0 { return nil, nil } else { - log.Info(resp.Values) - } - - users := make([]*helpers.User, 0) - if err != nil { - return nil, append(errs, errors.Wrap(err, "failed to open file")) + g.log.Info(resp.Values) } + users := make([]*helpers.Certificate, 0) for id, row := range resp.Values { if id < 1 { continue } - userInfo := new(helpers.User) + userInfo := new(helpers.Certificate) st := reflect.ValueOf(userInfo) st = st.Elem() @@ -65,7 +44,7 @@ func (g *Google) ParseFromWeb(spreadsheetId, readRange string, log *logan.Entry) return users, nil } -func (g *Google) SetRes(users []*helpers.User, sheetID string) []error { +func (g *Google) SetRes(users []*helpers.Certificate, sheetID string) []error { errs := make([]error, 0) for _, user := range users { @@ -74,12 +53,11 @@ func (g *Google) SetRes(users []*helpers.User, sheetID string) []error { dataForSend = append(dataForSend, user.SerialNumber, user.Certificate, user.DataHash, user.TxHash, user.Signature, user.DigitalCertificate) - err := g.UpdateTable(fmt.Sprint("Sheet1!F", user.ID+2), dataForSend, sheetID) - time.Sleep(4 * time.Millisecond) - if err != nil { + if err := g.UpdateTable(fmt.Sprint("Sheet1!F", user.ID+2), dataForSend, sheetID); err != nil { errs = append(errs, err) continue } + time.Sleep(4 * time.Millisecond) } return nil } @@ -88,9 +66,7 @@ func (g *Google) UpdateTable(position string, value []string, spreadsheetId stri values := stringToInterface(value) var vr sheets.ValueRange vr.Values = append(vr.Values, values) - _, err := g.sheetSrv.Spreadsheets.Values.Update(spreadsheetId, position, &vr).ValueInputOption("RAW").Do() - if err != nil { - log.Println(err) + if _, err := g.sheetSrv.Spreadsheets.Values.Update(spreadsheetId, position, &vr).ValueInputOption("RAW").Do(); err != nil { return errors.Wrap(err, "failed to update sheet") } diff --git a/internal/handlers/handlers.go b/internal/service/core/google/handlers.go similarity index 74% rename from internal/handlers/handlers.go rename to internal/service/core/google/handlers.go index 8cbe91a2..91c6d8cf 100644 --- a/internal/handlers/handlers.go +++ b/internal/service/core/google/handlers.go @@ -1,4 +1,4 @@ -package handlers +package google import ( "context" @@ -6,11 +6,8 @@ import ( "github.com/pkg/errors" "gitlab.com/distributed_lab/logan/v3" "gitlab.com/distributed_lab/running" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "log" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" "strings" - "sync" "time" ) @@ -23,7 +20,6 @@ type FilesBytes struct { } type Handler struct { - mu sync.Mutex running int chInput chan FilesBytes chOutput chan FilesBytes @@ -33,11 +29,11 @@ type Handler struct { log *logan.Entry ctx context.Context cancel context.CancelFunc - googleClient *google.Google + googleClient *Google count int32 } -func NewHandler(input chan FilesBytes, output chan FilesBytes, log *logan.Entry, google *google.Google, ran int, ctx context.Context) Handler { +func NewHandler(input chan FilesBytes, output chan FilesBytes, log *logan.Entry, google *Google, ran int, ctx context.Context) Handler { ctxInner, cancel := context.WithCancel(ctx) return Handler{ running: ran, @@ -76,9 +72,7 @@ func (h *Handler) StartDriveRunner() { } func (h *Handler) decrement() { - h.mu.Lock() h.running-- - h.mu.Unlock() if h.running == 0 { close(h.chOutput) h.cancel() @@ -86,7 +80,7 @@ func (h *Handler) decrement() { } } -func (h *Handler) Read(users []*helpers.User, flag string) []*helpers.User { +func (h *Handler) Read(users []*helpers.Certificate, flag string) []*helpers.Certificate { for { select { case path := <-h.chOutput: @@ -94,7 +88,7 @@ func (h *Handler) Read(users []*helpers.User, flag string) []*helpers.User { for id, u := range users { if u.ID == path.ID { users[id] = h.setLink(users[id], path, flag) - log.Println("set external link: ", flag) + h.log.Debug("set external link: ", flag) break } } @@ -105,7 +99,7 @@ func (h *Handler) Read(users []*helpers.User, flag string) []*helpers.User { } } -func (h *Handler) setLink(user *helpers.User, path FilesBytes, flag string) *helpers.User { +func (h *Handler) setLink(user *helpers.Certificate, path FilesBytes, flag string) *helpers.Certificate { switch strings.ToLower(flag) { case "qr": user.DigitalCertificate = strings.ReplaceAll(path.Link, "https://", "") @@ -124,22 +118,20 @@ func (h *Handler) insertData(files []FilesBytes) { close(h.chInput) } -func Drive(googleClient *google.Google, log *logan.Entry, files []FilesBytes, users []*helpers.User, flag string, folderName string) ([]*helpers.User, error) { +func Drive(googleClient *Google, log *logan.Entry, files []FilesBytes, users []*helpers.Certificate, flag string, folderName string) ([]*helpers.Certificate, error) { var err error input := make(chan FilesBytes) output := make(chan FilesBytes) - ctx := context.Background() - - err = googleClient.CreateFolder(folderName) - if err != nil { + if err := googleClient.CreateFolder(folderName); err != nil { return users, errors.Wrap(err, "failed to create folder") } - handler := NewHandler(input, output, log, googleClient, 10, ctx) + + handler := NewHandler(input, output, log, googleClient, 10, context.Background()) handler.StartDriveRunner() go handler.insertData(files) users = handler.Read(users, flag) - log.Info("sent to drive: ", handler.count) + log.Info("Sent to drive: ", handler.count) return users, err } diff --git a/internal/service/helpers/model.go b/internal/service/core/helpers/model.go similarity index 100% rename from internal/service/helpers/model.go rename to internal/service/core/helpers/model.go diff --git a/internal/service/helpers/user.go b/internal/service/core/helpers/user.go similarity index 79% rename from internal/service/helpers/user.go rename to internal/service/core/helpers/user.go index 7f318ce2..4b96b493 100644 --- a/internal/service/helpers/user.go +++ b/internal/service/core/helpers/user.go @@ -5,7 +5,7 @@ import ( "fmt" ) -type User struct { +type Certificate struct { Date string Participant string CourseTitle string @@ -23,11 +23,11 @@ type User struct { ShortCourseName string } -func (u *User) SetSignature(signature string) { +func (u *Certificate) SetSignature(signature string) { u.Signature = signature } -func (u *User) SetDataHash(hash string) { +func (u *Certificate) SetDataHash(hash string) { u.DataHash = hash if len(u.TxHash) > 0 && len(u.TxHash) < 5 { u.SerialNumber = hash[:20] @@ -38,7 +38,7 @@ func (u *User) SetDataHash(hash string) { } } -func (u *User) Hashing(msg string) string { +func (u *Certificate) Hashing(msg string) string { sum := sha256.Sum256([]byte(msg)) return fmt.Sprintf("%x", sum[:]) } diff --git a/internal/service/core/ipfs/client.go b/internal/service/core/ipfs/client.go new file mode 100644 index 00000000..9d725872 --- /dev/null +++ b/internal/service/core/ipfs/client.go @@ -0,0 +1,28 @@ +package ipfs + +import "net/http" + +type AuthHandler interface { + RoundTrip(r *http.Request) (*http.Response, error) +} + +type authTransport struct { + http.RoundTripper + ProjectId string + ProjectSecret string +} + +func NewClient(projectId, projectSecret string) *http.Client { + return &http.Client{ + Transport: authTransport{ + RoundTripper: http.DefaultTransport, + ProjectId: projectId, + ProjectSecret: projectSecret, + }, + } +} + +func (t authTransport) RoundTrip(r *http.Request) (*http.Response, error) { + r.SetBasicAuth(t.ProjectId, t.ProjectSecret) + return t.RoundTripper.RoundTrip(r) +} diff --git a/internal/service/core/ipfs/ipfs.go b/internal/service/core/ipfs/ipfs.go new file mode 100644 index 00000000..79d1738e --- /dev/null +++ b/internal/service/core/ipfs/ipfs.go @@ -0,0 +1,79 @@ +package ipfs + +import ( + "bytes" + "encoding/json" + shell "github.com/ipfs/go-ipfs-api" + "gitlab.com/distributed_lab/logan/v3/errors" + "gitlab.com/tokend/course-certificates/ccp/internal/config" + "image/png" + "os" + "path/filepath" + "strings" +) + +type ConnectorHandler interface { + Upload(data []byte) (string, error) + PrepareJSON(tokenName, tokenDescription, link, imagePath string) ([]byte, error) + PrepareImagePath(imagePath string) ([]byte, error) +} + +type Connector struct { + cfg *config.NetworksConfig +} + +func NewConnector(cfg *config.NetworksConfig) *Connector { + return &Connector{cfg: cfg} +} + +func (i Connector) Upload(data []byte) (string, error) { + ipfs := shell.NewShellWithClient(i.cfg.IpfsEndpoint, NewClient(i.cfg.IpfsPrId, i.cfg.IpfsPrKey)) + + fileHash, err := ipfs.Add(bytes.NewReader(data)) + if err != nil { + return "", errors.Wrap(err, "failed to upload file to ipfs") + } + return fileHash, nil + +} + +func (i Connector) PrepareJSON(tokenName, tokenDescription, link, imagePath string) ([]byte, error) { + erc721 := ERC721json{ + Name: tokenName, + Description: tokenDescription, + Image: i.cfg.IpfsDisplayFileDomen + imagePath, + ExternalUrl: link, + } + + erc721JSON, err := json.Marshal(erc721) + if err != nil { + return nil, errors.Wrap(err, "failed to marshal erc721") + } + + return erc721JSON, nil +} + +func (i Connector) PrepareImagePath(imagePath string) ([]byte, error) { + path, err := filepath.Abs("main.go") + if err != nil { + return nil, errors.Wrap(err, "failed to get absolute path") + } + path = strings.ReplaceAll(path, "main.go", "") + + infile, err := os.Open(path + imagePath) + if err != nil { + return nil, errors.Wrap(err, "failed to open image") + } + + img, err := png.Decode(infile) + if err != nil { + return nil, errors.Wrap(err, "failed to decode image") + } + + buf := new(bytes.Buffer) + + if err = png.Encode(buf, img); err != nil { + return nil, errors.Wrap(err, "failed to decode image to []byte") + } + return buf.Bytes(), nil +} diff --git a/internal/service/core/ipfs/types.go b/internal/service/core/ipfs/types.go new file mode 100644 index 00000000..a46bfdeb --- /dev/null +++ b/internal/service/core/ipfs/types.go @@ -0,0 +1,8 @@ +package ipfs + +type ERC721json struct { + Name string `json:"name"` + Description string `json:"description"` + Image string `json:"image"` + ExternalUrl string `json:"external_url"` +} diff --git a/internal/service/core/pdf/config.go b/internal/service/core/pdf/config.go new file mode 100644 index 00000000..c88a40d1 --- /dev/null +++ b/internal/service/core/pdf/config.go @@ -0,0 +1,17 @@ +package pdf + +import "gitlab.com/tokend/course-certificates/ccp/internal/config" + +type PDFConfig struct { + titles map[string]string + exams map[string]string + templates map[string]string +} + +func NewPDFConfig(cfg config.Config) *PDFConfig { + return &PDFConfig{ + titles: cfg.TitlesConfig(), + exams: cfg.ExamsConfig(), + templates: cfg.TemplatesConfig(), + } +} diff --git a/internal/service/core/pdf/container.go b/internal/service/core/pdf/container.go new file mode 100644 index 00000000..39553f82 --- /dev/null +++ b/internal/service/core/pdf/container.go @@ -0,0 +1,138 @@ +package pdf + +import ( + "fmt" + "github.com/pkg/errors" + "gitlab.com/distributed_lab/logan/v3" + "gitlab.com/tokend/course-certificates/ccp/internal/config" + "gitlab.com/tokend/course-certificates/ccp/internal/data" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/qr" +) + +type ContainerHandler interface { + Generate() error + Update() error +} + +type Container struct { + Certificates []*helpers.Certificate + ID int + Status string + log *logan.Entry + config config.Config + masterQ data.MasterQ + googleClient *google.Google + address string + sheetUrl string + owner *data.Client + process string +} + +const SendQR = "qr" +const sendCertificate = "certificate" + +func (c *Container) Generate() error { + var files []google.FilesBytes + var filesCert []google.FilesBytes + for _, user := range c.Certificates { + qrData := qr.NewQR(user, c.log, c.config.TemplatesConfig(), c.config.QRCode().Template) + hash := user.Hashing(fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle)) + + if hash != "" { + c.log.Debug(user.Participant, " hash = ", hash) + } + + user.SetDataHash(hash) + file, img, name, err := qrData.GenerateQR([]byte(c.address)) + if err != nil { + return errors.Wrap(err, "failed to Generate qrData") + } + + files = append(files, google.FilesBytes{File: file, Name: name, ID: user.ID, Type: "image/svg+xml"}) + + pdf := PDF{} + certificate := pdf.SetTemplateData(DefaultTemplateTall) + + pdfData := NewData(user.Participant, user.CourseTitle, "45 hours / 1.5 ECTS Credit", user.Points, user.SerialNumber, user.Date, img, user.Note, "", "") + fileBytes, name, certificateImg, err := certificate.Prepare(pdfData, NewPDFConfig(c.config), c.masterQ, nil, c.owner.ID, c.config.StaticConfig().Location) + if err != nil { + return errors.Wrap(err, "failed to create pdf") + } + + user.ImageCertificate = certificateImg + filesCert = append(filesCert, google.FilesBytes{File: fileBytes, Name: name, ID: user.ID, Type: "application/pdf"}) + } + + users, err := google.Drive(c.googleClient, c.log, files, c.Certificates, SendQR, c.config.Google().QRPath) + if err != nil { + return errors.Wrap(err, "failed to send date to drive") + } + + users, err = google.Drive(c.googleClient, c.log, filesCert, c.Certificates, sendCertificate, c.config.Google().PdfPath) + if err != nil { + return errors.Wrap(err, "failed to send date to drive") + } + + c.log.Debug("creating table") + errs := c.googleClient.SetRes(users, c.sheetUrl) + if errs != nil { + return errors.Wrap(err, "failed to set result on table") + } + + c.Status = readyStatus + return nil +} + +func (c *Container) Update() error { + var files []google.FilesBytes + var filesCert []google.FilesBytes + for _, user := range c.Certificates { + qrData := qr.NewQR(user, c.log, c.config.TemplatesConfig(), c.config.QRCode().Template) + hash := user.Hashing(fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle)) + + if hash != "" { + c.log.Debug(user.Participant, " hash = ", hash) + } + + user.SetDataHash(hash) + file, img, name, err := qrData.GenerateQR([]byte(c.address)) + if err != nil { + return errors.Wrap(err, "failed to Generate qrData") + } + + files = append(files, google.FilesBytes{File: file, Name: name, ID: user.ID, Type: "image/svg+xml"}) + + pdf := PDF{} + certificate := pdf.SetTemplateData(DefaultTemplateTall) + + pdfData := NewData(user.Participant, user.CourseTitle, "45 hours / 1.5 ECTS Credit", user.Points, user.SerialNumber, user.Date, img, user.Note, "", "") + fileBytes, name, certificateImg, err := certificate.Prepare(pdfData, NewPDFConfig(c.config), c.masterQ, nil, c.owner.ID, c.config.StaticConfig().Location) + if err != nil { + return errors.Wrap(err, "failed to create pdf") + } + + user.ImageCertificate = certificateImg + filesCert = append(filesCert, google.FilesBytes{File: fileBytes, Name: name, ID: user.ID, Type: "application/pdf"}) + } + + users, err := google.Drive(c.googleClient, c.log, files, c.Certificates, SendQR, c.config.Google().QRPath) + if err != nil { + return errors.Wrap(err, "failed to send qrs to drive") + } + + users, err = google.Drive(c.googleClient, c.log, filesCert, c.Certificates, sendCertificate, c.config.Google().PdfPath) + if err != nil { + return errors.Wrap(err, "failed to send certificates to drive") + } + + c.log.Debug("creating table") + errs := c.googleClient.SetRes(users, c.sheetUrl) + if errs != nil { + return errors.Wrap(err, "failed to set result on table") + } + c.Status = readyStatus + + return nil +} diff --git a/internal/service/core/pdf/default_data.go b/internal/service/core/pdf/default_data.go new file mode 100644 index 00000000..6891f23e --- /dev/null +++ b/internal/service/core/pdf/default_data.go @@ -0,0 +1,130 @@ +package pdf + +var DefaultTemplateNormal = PDF{ + High: 595, + Width: 842, + Name: Field{ + X: 200, + Y: 217, + FontSize: 28, + Font: "semibold", + }, + Course: Field{ + X: 61, + Y: 259, + FontSize: 14, + Font: "semibold", + }, + Credits: Field{ + X: 70, + Y: 56, + FontSize: 12, + Font: "regular", + }, + Points: Field{ + X: 70, + Y: 79, + FontSize: 12, + Font: "regular", + }, + SerialNumber: Field{ + X: 641, + Y: 56, + FontSize: 12, + Font: "regular", + }, + Date: Field{ + X: 641, + Y: 79, + FontSize: 12, + Font: "regular", + }, + QR: Field{ + X: 658, + Y: 106, + High: 114, + Width: 114, + }, + Exam: Field{ + X: 300, + Y: 300, + FontSize: 15, + Font: "italic", + }, + Level: Field{ + X: 300, + Y: 277, + FontSize: 14, + Font: "semibold", + }, +} + +var DefaultTemplateTall = PDF{ + High: 1190, + Width: 1684, + Name: Field{ + Y: 434, + FontSize: 56, + Font: "semibold", + }, + Course: Field{ + Y: 518, + FontSize: 28, + Font: "semibold", + }, + Credits: Field{ //todo get from front and save to db + X: 140, + Y: 112, + FontSize: 24, + Font: "regular", + }, + Points: Field{ + X: 140, + Y: 158, + FontSize: 24, + Font: "regular", + }, + SerialNumber: Field{ + X: 1244, + //X: 1270, + Y: 112, + FontSize: 24, + Font: "regular", + }, + Date: Field{ + X: 1244, + //X: 1282, + Y: 158, + FontSize: 24, + Font: "regular", + }, + QR: Field{ + X: 1316, + Y: 212, + High: 228, + Width: 228, + }, + Exam: Field{ + Y: 600, + FontSize: 30, + Font: "italic", + }, + Level: Field{ + Y: 554, + FontSize: 28, + Font: "semibold", + }, +} + +var DefaultData = PDFData{ + Name: "Test Name", + Course: "Blockchain and Distributed Systems", + Credits: " 99", + Points: "100", + SerialNumber: "694d0f5a7afe6fbc99cb", + Date: "30.05.2018", + QR: nil, + Exam: "passed", + Level: "graduated with honors", + Note: "************************************************", +} diff --git a/internal/service/core/pdf/images.go b/internal/service/core/pdf/images.go new file mode 100644 index 00000000..3f2bf5c0 --- /dev/null +++ b/internal/service/core/pdf/images.go @@ -0,0 +1,94 @@ +package pdf + +import ( + "bytes" + "encoding/base64" + "fmt" + "github.com/pkg/errors" + "image" + "image/jpeg" + "os" + "os/exec" + "path/filepath" + "time" +) + +type ImageConvertHandler interface { + Convert(blob []byte) ([]byte, error) + base64toJpg(data []byte) ([]byte, error) +} + +type ImageConvert struct{} + +func NewImageConverter() ImageConvertHandler { + return ImageConvert{} +} + +func (i ImageConvert) Convert(blob []byte) ([]byte, error) { + unixTime := time.Now().Unix() + + fileInput, err := os.Create(fmt.Sprintf("input%d.pdf", unixTime)) + if err != nil { + return nil, errors.Wrap(err, "failed to create file") + } + + defer os.Remove(fileInput.Name()) + + if _, err = fileInput.Write(blob); err != nil { + return nil, errors.Wrap(err, "failed to write data") + } + + fileInputPath, err := filepath.Abs(fileInput.Name()) + if err != nil { + return nil, errors.Wrap(err, "failed to get abs input file") + } + + fileOutput, err := os.Create(fmt.Sprintf("output%d.png", unixTime)) + if err != nil { + return nil, errors.Wrap(err, "failed ot create file") + } + + defer os.Remove(fileOutput.Name()) + + err = fileOutput.Close() + if err != nil { + return nil, errors.Wrap(err, "failed to close file") + } + + fileOutputPath, err := filepath.Abs(fileOutput.Name()) + if err != nil { + return nil, errors.Wrap(err, "failed to get abs output file") + } + + cmd := exec.Command("sh", "-c", "gs -sDEVICE=png16m -dNOPAUSE -dBATCH -dSAFER -sOutputFile="+fileOutputPath+" "+fileInputPath) + _, err = cmd.Output() + if err != nil { + return nil, errors.Wrap(err, "failed to exec convert script") + } + + fileBlob, err := os.ReadFile(fileOutputPath) + if err != nil { + return nil, errors.Wrap(err, "failed to read file ") + } + + return fileBlob, nil +} + +func (i ImageConvert) base64toJpg(data []byte) ([]byte, error) { + + reader := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(data)) + m, _, err := image.Decode(reader) + if err != nil { + return nil, errors.Wrap(err, "failed to decode file") + } + + //Encode from image format to writer + buf := new(bytes.Buffer) + + err = jpeg.Encode(buf, m, &jpeg.Options{Quality: 75}) + if err != nil { + return nil, errors.Wrap(err, "failed to encode data") + + } + return buf.Bytes(), nil +} diff --git a/internal/service/core/pdf/pdf.go b/internal/service/core/pdf/pdf.go new file mode 100644 index 00000000..c145b258 --- /dev/null +++ b/internal/service/core/pdf/pdf.go @@ -0,0 +1,328 @@ +package pdf + +import ( + "bytes" + "fmt" + "github.com/signintech/gopdf" + "gitlab.com/distributed_lab/logan/v3/errors" + "gitlab.com/tokend/course-certificates/ccp/internal/data" + "image" + "io" + "os" + "strings" +) + +func (p *PDF) Prepare(data PDFData, config *PDFConfig, masterQ data.MasterQ, backgroundImg []byte, userID int64, abs string) ([]byte, string, []byte, error) { + pdf := new(gopdf.GoPdf) + pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: p.Width, H: p.High}}) + pdf.AddPage() + pdf.SetTextColor(255, 255, 255) + + if err := p.setFonts(pdf, abs); err != nil { + return nil, "", nil, errors.Wrap(err, "failed to set fonts") + } + + templateImg := config.templates[data.Course] + + if backgroundImg == nil { + if err := p.initBackground(pdf, masterQ.TemplateQ(), templateImg, abs, userID); err != nil { + return nil, "", nil, errors.Wrap(err, "failed to init background") + } + } else { + if err := p.setBackground(pdf, backgroundImg); err != nil { + return nil, "", nil, errors.Wrap(err, "failed to set background") + } + } + + if err := p.CellAllPdfFields(pdf, data, config, templateImg); err != nil { + return nil, "", nil, errors.Wrap(err, "failed to set all pdf's fields") + } + + pdfBlob := pdf.GetBytesPdf() + imgBlob, err := NewImageConverter().Convert(pdfBlob) + if err != nil { + return nil, "", nil, errors.Wrap(err, "failed to convert pdf to png") + } + + return pdfBlob, p.prepareName(data.Name, config.templates[data.Course]), imgBlob, nil + +} + +func (p *PDF) checkLevel(title string) (bool, string, string) { + titles := strings.Split(title, "Level:") + if len(titles) > 1 { + return true, titles[0], fmt.Sprint("Level:", titles[1]) + } + return false, titles[0], "" +} + +func (p *PDF) setBackgroundFromFile(pdf *gopdf.GoPdf, abs, imageName string) error { + file, err := os.Open(fmt.Sprintf("%s/static/templates/%s.png", abs, imageName)) + defer file.Close() + if err != nil { + return errors.Wrap(err, "default template isn't found") + } + + back, err := io.ReadAll(file) + if err != nil { + return errors.Wrap(err, "cant to decode img") + + } + if err := p.setBackground(pdf, back); err != nil { + return errors.Wrap(err, "cant to set img") + } + + return nil +} + +func (p *PDF) setBackgroundFromTemplate(pdf *gopdf.GoPdf, image []byte) error { + back, err := NewImageConverter().base64toJpg(image) + if err != nil { + return errors.Wrap(err, "cant to decode img") + + } + if err := p.setBackground(pdf, back); err != nil { + return errors.Wrap(err, "cant to set img") + } + + return nil +} + +func (p *PDF) setBackground(pdf *gopdf.GoPdf, image []byte) error { + backgroundImgHolder, err := gopdf.ImageHolderByBytes(image) + if err != nil { + return errors.Wrap(err, "failed to prepare background") + } + + err = pdf.ImageByHolder(backgroundImgHolder, 0, 0, &gopdf.Rect{W: p.Width, H: p.High}) + if err != nil { + return errors.Wrap(err, "failed to set background") + } + return nil +} + +func (p *PDF) setFonts(pdf *gopdf.GoPdf, abs string) error { + if err := pdf.AddTTFFont("italic", abs+"/static/font/Inter-Italic.ttf"); err != nil { + return errors.Wrap(err, "failed to add font") + } + if err := pdf.AddTTFFont("regular", abs+"/static/font/Inter-Regular.ttf"); err != nil { + return errors.Wrap(err, "failed to add Inter-Regular") + } + if err := pdf.AddTTFFont("semibold", abs+"/static/font/Inter-SemiBold.ttf"); err != nil { + return errors.Wrap(err, "failed to add Inter-SemiBold.ttf") + } + + return nil +} + +func (p *PDF) setLevel(pdf *gopdf.GoPdf, level string) error { + if err := pdf.SetFont("italic", "", p.Level.FontSize); err != nil { + return errors.Wrap(err, "failed to set font Level") + } + pdf.SetX(0) + pdf.SetY(p.Level.Y) + if err := pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, level, gopdf.CellOption{Align: gopdf.Center}); err != nil { + return errors.Wrap(err, "failed to cell Level") + } + + return nil +} + +func (p *PDF) setExam(pdf *gopdf.GoPdf, exam string) error { + if err := pdf.SetFont("italic", "", p.Exam.FontSize); err != nil { + return errors.Wrap(err, "failed to set font Exam") + } + pdf.SetX(0) + pdf.SetY(p.Exam.Y) + + if err := pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, exam, gopdf.CellOption{Align: gopdf.Center}); err != nil { + return errors.Wrap(err, "failed to cell Exam") + } + + return nil +} + +func (p *PDF) setQR(pdf *gopdf.GoPdf, qr []byte) error { + img, _, err := image.Decode(bytes.NewReader(qr)) + if err != nil { + return errors.Wrap(err, "failed to convert bytes to image QR") + } + + err = pdf.ImageFrom(img, p.QR.X, p.QR.Y, &gopdf.Rect{W: p.QR.High, H: p.QR.High}) + if err != nil { + return errors.Wrap(err, "failed to set image QR") + } + + return nil +} + +func (p *PDF) setCourse(pdf *gopdf.GoPdf, courseTitle string) error { + if err := pdf.SetFont("italic", "", p.Course.FontSize); err != nil { + return errors.Wrap(err, "failed to set font Course") + } + pdf.SetX(0) + pdf.SetY(p.Course.Y) + + if err := pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, courseTitle, gopdf.CellOption{Align: gopdf.Center}); err != nil { + return errors.Wrap(err, "failed to cell Course") + } + + return nil +} + +func (p *PDF) setSerialNumber(pdf *gopdf.GoPdf, serialNumber string) error { + if err := pdf.SetFont("italic", "", p.SerialNumber.FontSize); err != nil { + return errors.Wrap(err, "failed to set font SerialNumber") + } + + pdf.SetX(p.SerialNumber.X) + pdf.SetY(p.SerialNumber.Y) + if err := pdf.CellWithOption(&gopdf.Rect{W: 300, H: 300}, serialNumber, gopdf.CellOption{Align: gopdf.Right}); err != nil { + return errors.Wrap(err, "failed to cell SerialNumber ") + } + + return nil + +} + +func (p *PDF) setPoints(pdf *gopdf.GoPdf, points string) error { + if err := pdf.SetFont("italic", "", p.Points.FontSize); err != nil { + return errors.Wrap(err, "failed to set font points") + + } + pdf.SetX(p.Points.X) + pdf.SetY(p.Points.Y) + if err := pdf.Cell(&gopdf.Rect{W: p.Width, H: p.High}, fmt.Sprintf("Count of points: %s", points)); err != nil { + return errors.Wrap(err, "failed to cell points") + } + + return nil +} + +func (p *PDF) setDate(pdf *gopdf.GoPdf, date string) error { + if err := pdf.SetFont("italic", "", p.Date.FontSize); err != nil { + return errors.Wrap(err, "failed to set font Date") + } + + pdf.SetX(p.Date.X) + pdf.SetY(p.Date.Y) + if err := pdf.CellWithOption(&gopdf.Rect{W: 300, H: 300}, fmt.Sprintf("Issued on: %s", date), gopdf.CellOption{Align: gopdf.Right}); err != nil { + return errors.Wrap(err, "failed to cell Date") + } + return nil +} + +func (p *PDF) setCredits(pdf *gopdf.GoPdf, credits string) error { + if err := pdf.SetFont("italic", "", p.Credits.FontSize); err != nil { + return errors.Wrap(err, "failed to set font credits") + } + pdf.SetX(p.Credits.X) + pdf.SetY(p.Credits.Y) + + if err := pdf.Cell(&gopdf.Rect{W: p.Width, H: p.High}, fmt.Sprintf(credits)); err != nil { + return errors.Wrap(err, "failed to cell credits") + } + + return nil +} + +func (p *PDF) setName(pdf *gopdf.GoPdf, name string) error { + if err := pdf.SetFont("regular", "", p.Name.FontSize); err != nil { + return errors.Wrap(err, "failed to set font name") + } + pdf.SetY(p.Name.Y) + pdf.SetX(0) + if err := pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, name, gopdf.CellOption{Align: gopdf.Center}); err != nil { + return errors.Wrap(err, "failed to cell name") + } + + return nil +} + +func (p *PDF) initBackground(pdf *gopdf.GoPdf, templateQ data.TemplateQ, templateImg, abs string, userID int64) error { + template, err := templateQ.FilterByName(templateImg).FilterByUser(userID).Get() + if err != nil { + return errors.Wrap(err, "failed to get background img") + } + if template == nil { + if err = p.setBackgroundFromFile(pdf, abs, templateImg); err != nil { + return errors.Wrap(err, "failed to set back from file") + } + } else { + if err = p.setBackgroundFromTemplate(pdf, template.ImgBytes); err != nil { + return errors.Wrap(err, "failed to set back from template") + + } + } + + return nil +} + +func (p *PDF) prepareName(name, course string) string { + parsedName := strings.Split(name, " ") + if len(parsedName) < 2 { + return fmt.Sprintf("certificate_%s_%s.pdf", parsedName[0], course) + } + + return fmt.Sprintf("certificate_%s_%s_%s.pdf", parsedName[0], parsedName[1], course) +} + +func (p *PDF) SetTemplateData(template PDF) *PDF { + certificate := NewPDF(template.High, template.Width) + certificate.SetName(template.Name.X, template.Name.Y, template.Name.FontSize, template.Name.Font) + certificate.SetDate(template.Date.X, template.Date.Y, template.Date.FontSize, template.Date.Font) + certificate.SetCourse(template.Course.X, template.Course.Y, template.Course.FontSize, template.Course.Font) + certificate.SetCredits(template.Credits.X, template.Credits.Y, template.Credits.FontSize, template.Credits.Font) + certificate.SetExam(template.Exam.X, template.Exam.Y, template.Exam.FontSize, template.Exam.Font) + certificate.SetLevel(template.Level.X, template.Level.Y, template.Level.FontSize, template.Level.Font) + certificate.SetSerialNumber(template.SerialNumber.X, template.SerialNumber.Y, template.SerialNumber.FontSize, template.SerialNumber.Font) + certificate.SetPoints(template.Points.X, template.Points.Y, template.Points.FontSize, template.Points.Font) + certificate.SetQR(template.QR.X, template.QR.Y, template.QR.FontSize, template.QR.High, template.Width) + + return certificate +} + +func (p *PDF) CellAllPdfFields(pdf *gopdf.GoPdf, data PDFData, config *PDFConfig, templateImg string) error { + if err := p.setName(pdf, data.Name); err != nil { + return errors.Wrap(err, "failed to set name") + } + + if err := p.setCredits(pdf, data.Credits); err != nil { + return errors.Wrap(err, "failed to set credits") + } + + if err := p.setPoints(pdf, data.Points); err != nil { + return errors.Wrap(err, "failed to set points") + } + + if err := p.setSerialNumber(pdf, data.SerialNumber); err != nil { + return errors.Wrap(err, "failed to set serial number") + } + + if err := p.setDate(pdf, data.Date); err != nil { + return errors.Wrap(err, "failed to set data") + } + + isLevel, title, level := p.checkLevel(config.titles[templateImg]) + if err := p.setCourse(pdf, title); err != nil { + return errors.Wrap(err, "failed to set course") + } + + if data.QR != nil { + if err := p.setQR(pdf, data.QR); err != nil { + return errors.Wrap(err, "failed to set qr") + } + } + + if err := p.setExam(pdf, config.exams[data.Exam]); err != nil { + return errors.Wrap(err, "failed to set exam") + } + + if isLevel { + if err := p.setLevel(pdf, level); err != nil { + return errors.Wrap(err, "failed to set level") + } + } + + return nil +} diff --git a/internal/service/core/pdf/runner.go b/internal/service/core/pdf/runner.go new file mode 100644 index 00000000..b05592d4 --- /dev/null +++ b/internal/service/core/pdf/runner.go @@ -0,0 +1,111 @@ +package pdf + +import ( + "context" + "gitlab.com/distributed_lab/logan/v3" + "gitlab.com/tokend/course-certificates/ccp/internal/config" + "gitlab.com/tokend/course-certificates/ccp/internal/data" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/google" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" +) + +const Update = "Update" +const Generate = "generates" + +type CreatorPDF interface { + NewContainer(users []*helpers.Certificate, google *google.Google, address, sheetUrl string, owner *data.Client, masterQ data.MasterQ, process string) int + CheckContainerState(containerID int) *Container + Run(ctx context.Context) + removeIndex(index int) +} + +type CreatorPDFType struct { + handlerChan chan *Container + lastContainerID int + log *logan.Entry + config config.Config + readyContainers []*Container +} + +func NewPdfCreator(log *logan.Entry, config config.Config) *CreatorPDFType { + return &CreatorPDFType{ + handlerChan: make(chan *Container), + log: log, + config: config, + readyContainers: make([]*Container, 0), + } +} + +func (p *CreatorPDFType) NewContainer(certificates []*helpers.Certificate, google *google.Google, address, sheetUrl string, owner *data.Client, masterQ data.MasterQ, process string) int { + p.lastContainerID++ + p.handlerChan <- &Container{ + Certificates: certificates, + ID: p.lastContainerID, + Status: isProcessingStatus, + log: p.log, + config: p.config, + masterQ: masterQ, + googleClient: google, + address: address, + sheetUrl: sheetUrl, + owner: owner, + process: process, + } + return p.lastContainerID +} + +func (p *CreatorPDFType) Run(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + + case container, ok := <-p.handlerChan: + if !ok { + ctx.Done() + return + } + + switch container.process { + case Generate: + err := container.Generate() + if err != nil { + p.log.Error(err, "failed to run container") + } + container.Status = readyStatus + p.log.Debug("Success: ", container) + + p.readyContainers = append(p.readyContainers, container) + break + case Update: + //todo make better + err := container.Update() + if err != nil { + p.log.Error(err, "failed to run container") + } + container.Status = readyStatus + p.readyContainers = append(p.readyContainers, container) + } + break + } + } +} + +func (p *CreatorPDFType) CheckContainerState(containerID int) *Container { + p.log.Debug("readyContainers: ", p.readyContainers) + + for _, container := range p.readyContainers { + if container.ID == containerID { + p.log.Debug("container: ", container) + return container + } + } + + return nil +} + +func (p *CreatorPDFType) removeIndex(index int) { + ret := make([]*Container, 0) + ret = append(ret, p.readyContainers[:index]...) + p.readyContainers = append(ret, p.readyContainers[index+1:]...) +} diff --git a/internal/service/core/pdf/setters.go b/internal/service/core/pdf/setters.go new file mode 100644 index 00000000..2273c4a2 --- /dev/null +++ b/internal/service/core/pdf/setters.go @@ -0,0 +1,121 @@ +package pdf + +func NewPDF(high, width float64) *PDF { + return &PDF{ + High: high, + Width: width, + } +} + +func NewData(name, course, credits, points, serialNumber, date string, qr []byte, exam, level, note string) PDFData { + return PDFData{ + Name: name, + Course: course, + Credits: credits, + Points: points, + SerialNumber: serialNumber, + Date: date, + QR: qr, + Exam: exam, + Level: level, + Note: note, + } +} + +func (p *PDF) SetName(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Name = fl +} + +func (p *PDF) SetCourse(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Course = fl +} +func (p *PDF) SetCredits(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Credits = fl +} + +func (p *PDF) SetLevel(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Level = fl +} + +func (p *PDF) SetPoints(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Points = fl +} + +func (p *PDF) SetSerialNumber(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.SerialNumber = fl +} + +func (p *PDF) SetDate(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Date = fl +} +func (p *PDF) SetQR(x, y float64, size int, high, width float64) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + High: high, + Width: width, + } + + p.QR = fl +} + +func (p *PDF) SetExam(x, y float64, size int, font string) { + fl := Field{ + X: x, + Y: y, + FontSize: size, + Font: font, + } + + p.Exam = fl +} diff --git a/internal/service/core/pdf/types.go b/internal/service/core/pdf/types.go new file mode 100644 index 00000000..1d354333 --- /dev/null +++ b/internal/service/core/pdf/types.go @@ -0,0 +1,46 @@ +package pdf + +const ( + readyStatus = "ready_status" + isProcessingStatus = "processing" +) + +type PDF struct { + High float64 `json:"high"` + Width float64 `json:"width"` + Name Field `json:"name"` + Course Field `json:"course"` + Credits Field `json:"credits"` + Points Field `json:"points"` + SerialNumber Field `json:"serial_number"` + Date Field `json:"date"` + QR Field `json:"qr"` + Exam Field `json:"exam"` + Level Field `json:"level"` + Note Field `json:"note"` +} + +type Field struct { + X float64 `json:"x"` + Y float64 `json:"y"` + XCenter bool `json:"x_center"` + YCenter bool `json:"y_center"` + FontSize int `json:"font_size"` + Color string `json:"color"` + Font string `json:"font"` + High float64 `json:"high"` + Width float64 `json:"width"` +} + +type PDFData struct { + Name string + Course string + Credits string + Points string + SerialNumber string + Date string + QR []byte + Exam string + Level string + Note string +} diff --git a/internal/service/qr/qr.go b/internal/service/core/qr/qr.go similarity index 59% rename from internal/service/qr/qr.go rename to internal/service/core/qr/qr.go index 269635db..0c3c27bc 100644 --- a/internal/service/qr/qr.go +++ b/internal/service/core/qr/qr.go @@ -5,20 +5,18 @@ import ( "fmt" "github.com/aaronarduino/goqrsvg" svg "github.com/ajstarks/svgo" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "image/color" - "github.com/boombuler/barcode/qr" qrcode "github.com/skip2/go-qrcode" + "gitlab.com/distributed_lab/logan/v3" "gitlab.com/distributed_lab/logan/v3/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/config" + "gitlab.com/tokend/course-certificates/ccp/internal/service/core/helpers" + "image/color" "os" + "time" "strings" ) -const sample = "message:\n%s\n\naddress:\n%s\n\nsignature:\n%s\n\ncertificate page:\nhttps://dlt-academy.com/certificates" - var shortTitles = map[string]string{ "Beginner at theoretical aspects blockchain technology": "blockchain", "Theory of database organization and basic SQL": "database", @@ -29,26 +27,36 @@ var shortTitles = map[string]string{ "Blockchain and Distributed Systems": "distributed_system", } +type QRCreator interface { + GenerateQR(address []byte) ([]byte, []byte, string, error) + PrepareMsgForQR(name string, address, signature []byte) string + pngQR(msg string) ([]byte, error) +} + type QR struct { - user *helpers.User - cfg config.Config + user *helpers.Certificate + templates map[string]string + log *logan.Entry + qrMessageTemplate string } -func NewQR(user *helpers.User, cfg config.Config) QR { +func NewQR(user *helpers.Certificate, log *logan.Entry, templates map[string]string, qrMessageTemplate string) QRCreator { return QR{ - user: user, - cfg: cfg, + user: user, + log: log, + templates: templates, + qrMessageTemplate: qrMessageTemplate, } } func (q QR) GenerateQR(address []byte) ([]byte, []byte, string, error) { parsedName := strings.Split(q.user.Participant, " ") path := "" - q.cfg.Log().Debug(parsedName) + q.log.Debug(parsedName) if len(parsedName) < 2 { - path = fmt.Sprintf("certificate_%s_%s_QR_codecreate.svg", parsedName[0], q.cfg.TemplatesConfig()[q.user.CourseTitle]) + path = fmt.Sprintf("certificate_%s_%s_QR_codecreate.svg", parsedName[0], q.templates[q.user.CourseTitle]) } else { - path = fmt.Sprintf("certificate_%s_%s_%s_QR_codecreate.svg", parsedName[0], parsedName[1], q.cfg.TemplatesConfig()[q.user.CourseTitle]) + path = fmt.Sprintf("certificate_%s_%s_%s_QR_codecreate.svg", parsedName[0], parsedName[1], q.templates[q.user.CourseTitle]) } bf := new(bytes.Buffer) @@ -73,11 +81,13 @@ func (q QR) GenerateQR(address []byte) ([]byte, []byte, string, error) { } func (q QR) PrepareMsgForQR(name string, address, signature []byte) string { - msg := fmt.Sprintf(sample, name, fmt.Sprintf("%s", address), fmt.Sprintf("%s", signature)) - return msg + return fmt.Sprintf(q.qrMessageTemplate, name, fmt.Sprintf("%s", address), fmt.Sprintf("%s", signature)) + } func (q QR) pngQR(msg string) ([]byte, error) { + unixTime := time.Now().Unix() + back := color.RGBA{ R: 0, G: 18, @@ -90,13 +100,15 @@ func (q QR) pngQR(msg string) ([]byte, error) { B: 255, A: 255, } - err := qrcode.WriteColorFile(msg, qrcode.Highest, 400, back, front, "testqr.png") - if err != nil { - return nil, err + if err := qrcode.WriteColorFile(msg, qrcode.Highest, 400, back, front, fmt.Sprintf("testqr%d.png", unixTime)); err != nil { + return nil, errors.Wrap(err, "failed to write color file") } - file, err := os.ReadFile("testqr.png") + defer os.Remove(fmt.Sprintf("testqr%d.png", unixTime)) + + file, err := os.ReadFile(fmt.Sprintf("testqr%d.png", unixTime)) if err != nil { - return nil, err + return nil, errors.Wrap(err, "failed to read file") } + return file, nil } diff --git a/internal/service/handlers/create_template.go b/internal/service/handlers/create_template.go deleted file mode 100644 index 83dbe6fa..00000000 --- a/internal/service/handlers/create_template.go +++ /dev/null @@ -1,128 +0,0 @@ -package handlers - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "github.com/pkg/errors" - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/data" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/pdf" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "gitlab.com/tokend/course-certificates/ccp/resources" - "image" - "image/png" - "net/http" -) - -func CreateTemplate(w http.ResponseWriter, r *http.Request) { - template, backgroundImg, resp, err := requests.NewGenerateTemplate(r) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to generate template")) - ape.Render(w, problems.BadRequest(err)) - return - } - d := pdf.DefaultData - client, err := helpers.ClientQ(r).GetByName(resp.Data.Relationships.User) - helpers.Log(r).Debug("client ", client) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to get client")) - ape.Render(w, problems.InternalError()) - return - } - if client == nil { - helpers.Log(r).Error(errors.Wrap(err, "client is not found")) - ape.Render(w, problems.NotFound()) - return - } - - fmt.Println("********") - if template.Width == 0 || template.High == 0 { - tp := pdf.DefaultTemplateTall - _, _, imgBytes, err := tp.Prepare(d, helpers.Config(r), helpers.TemplateQ(r), backgroundImg, client.ID) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to prepare pdf")) - ape.Render(w, problems.InternalError()) - return - } - fmt.Println(template.Width) - ape.Render(w, newTemplateImageResp(imgBytes)) - return - } - - file := pdf.NewPDF(template.High, template.Width) - - file.SetName(template.Name.X, template.Name.Y, template.Name.FontSize, template.Name.Font) - file.SetDate(template.Date.X, template.Date.Y, template.Date.FontSize, template.Date.Font) - file.SetCourse(template.Course.X, template.Course.Y, template.Course.FontSize, template.Course.Font) - file.SetCredits(template.Credits.X, template.Credits.Y, template.Credits.FontSize, template.Credits.Font) - file.SetExam(template.Exam.X, template.Exam.Y, template.Exam.FontSize, template.Exam.Font) - file.SetLevel(template.Level.X, template.Level.Y, template.Level.FontSize, template.Level.Font) - file.SetSerialNumber(template.SerialNumber.X, template.SerialNumber.Y, template.SerialNumber.FontSize, template.SerialNumber.Font) - file.SetPoints(template.Points.X, template.Points.Y, template.Points.FontSize, template.Points.Font) - file.SetQR(template.QR.X, template.QR.Y, template.QR.FontSize, template.QR.High, template.Width) - _, _, imgBytes, err := template.Prepare(d, helpers.Config(r), helpers.TemplateQ(r), backgroundImg, client.ID) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to prepare pdf")) - ape.Render(w, problems.InternalError()) - return - } - fmt.Println("IsCompleted: ", resp.Data.Attributes.IsCompleted) - if resp.Data.Attributes.IsCompleted { - templateBytes, err := json.Marshal(template) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to marshal")) - ape.Render(w, problems.InternalError()) - return - } - helpers.Log(r).Debug("template: ", templateBytes) - fmt.Println("template ", templateBytes) - - helpers.Log(r).Debug("client ", client) - - _, err = helpers.TemplateQ(r).Insert(&data.Template{ - Template: templateBytes, - //ImgBytes: backgroundImg, - Name: resp.Data.Attributes.TemplateName, - UserID: client.ID, - }) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to insert template")) - ape.Render(w, problems.InternalError()) - return - } - } - ape.Render(w, newTemplateImageResp(imgBytes)) - return -} - -func newTemplateImageResp(img []byte) resources.TemplateResponse { - return resources.TemplateResponse{ - Data: resources.Template{ - Attributes: resources.TemplateAttributes{ - BackgroundImg: base64.StdEncoding.EncodeToString(img), - }, - }, - } -} - -func base64BytestoPng(data []byte) (string, error) { - - reader := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(data)) - m, _, err := image.Decode(reader) - if err != nil { - return "", err - } - - //Encode from image format to writer - buf := new(bytes.Buffer) - - err = png.Encode(buf, m) - if err != nil { - return "", err - } - return buf.String(), nil -} diff --git a/internal/service/handlers/get_empty_users.go b/internal/service/handlers/get_empty_users.go deleted file mode 100644 index 8fe015b7..00000000 --- a/internal/service/handlers/get_empty_users.go +++ /dev/null @@ -1,98 +0,0 @@ -package handlers - -import ( - "fmt" - "github.com/google/jsonapi" - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "gitlab.com/tokend/course-certificates/ccp/resources" - "net/http" -) - -func GetUsersEmpty(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewGetUsers(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse request") - ape.Render(w, problems.BadRequest(err)) - return - } - - client := google.NewGoogleClient(helpers.Config(r)) - - link, err := client.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) - if len(link) != 0 { - helpers.Log(r).WithError(err).Error("failed to authorize") - - ape.RenderErr(w, []*jsonapi.ErrorObject{{ - Title: "Forbidden", - Detail: "Invalid token", - Status: "403", - Code: "125", - Meta: &map[string]interface{}{"auth_link": link}}, - }...) - - return - } - - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect") - ape.Render(w, problems.InternalError()) - return - } - - users, errs := client.ParseFromWeb(req.Data.Url, "A1:K", helpers.Config(r).Log()) - if errs != nil { - helpers.Log(r).Error("failed to parse table: Errors:", errs) - ape.Render(w, problems.BadRequest(err)) - return - } - emptyUsers := make([]*helpers.User, 0) - for id, user := range users { - user.ID = id - user.ShortCourseName = helpers.Config(r).TemplatesConfig()[user.CourseTitle] - if user.Certificate != "" { - helpers.Log(r).Debug("has already") - continue - } - user.Msg = fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle) - emptyUsers = append(emptyUsers, user) - } - - ape.Render(w, newUserResponse(emptyUsers)) -} - -func newUserResponse(users []*helpers.User) resources.UserListResponse { - usersData := make([]resources.User, 0) - for _, user := range users { - resp := resources.User{ - Key: resources.Key{ - ID: fmt.Sprintf("%x", user.ID), - Type: resources.USER, - }, - Attributes: resources.UserAttributes{ - Certificate: user.Certificate, - Id: int64(user.ID), - Points: user.Points, - Participant: user.Participant, - Msg: user.Msg, - SerialNumber: user.SerialNumber, - Note: user.Note, - DataHash: user.DataHash, - Signature: user.Signature, - TxHash: user.TxHash, - Date: user.Date, - CourseTitle: user.CourseTitle, - ShortCourse: user.ShortCourseName, - }, - } - usersData = append(usersData, resp) - } - - return resources.UserListResponse{ - Data: usersData, - } - -} diff --git a/internal/service/handlers/ipfs_upload.go b/internal/service/handlers/ipfs_upload.go deleted file mode 100644 index 55bf2ed5..00000000 --- a/internal/service/handlers/ipfs_upload.go +++ /dev/null @@ -1,51 +0,0 @@ -package handlers - -import ( - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/ipfs" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "gitlab.com/tokend/course-certificates/ccp/resources" - "net/http" -) - -func UploadFileToIpfs(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewUploadFileToIPFS(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse data") - ape.Render(w, problems.InternalError()) - return - } - connector := ipfs.NewConnector(helpers.Config(r)) - imgHash, err := connector.Upload(req.Data.Img) - jsonHash, err := connector.PrepareJSON(req.Data.Name, req.Data.Description, imgHash) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to prepare json") - ape.Render(w, problems.InternalError()) - return - } - - preparedURI, err := connector.Upload(jsonHash) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to upload") - ape.Render(w, problems.InternalError()) - return - } - - ape.Render(w, newIpfsUploadResponse(preparedURI)) - helpers.Log(r).Debug(newIpfsUploadResponse(preparedURI)) -} - -func newIpfsUploadResponse(uri string) resources.IpfsFileResponse { - return resources.IpfsFileResponse{ - Data: resources.IpfsFile{ - Key: resources.Key{ - Type: resources.IPFS, - }, - Attributes: resources.IpfsFileAttributes{ - Url: uri, - }, - }, - } -} diff --git a/internal/service/handlers/prepare_certificate.go b/internal/service/handlers/prepare_certificate.go deleted file mode 100644 index 6086ba60..00000000 --- a/internal/service/handlers/prepare_certificate.go +++ /dev/null @@ -1,175 +0,0 @@ -package handlers - -import ( - "fmt" - "github.com/google/jsonapi" - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/distributed_lab/logan/v3/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/handlers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/pdf" - "gitlab.com/tokend/course-certificates/ccp/internal/service/qr" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "gitlab.com/tokend/course-certificates/ccp/resources" - "log" - "net/http" -) - -const SENDQR = "qr" -const SENDCERTIFICATE = "certificate" - -func PrepareCertificate(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewPrepareCertificates(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse data") - ape.Render(w, problems.BadRequest(err)) - return - } - users := req.PrepareUsers() - var files []handlers.FilesBytes - var filesCert []handlers.FilesBytes - - googleClient := google.NewGoogleClient(helpers.Config(r)) - link, err := googleClient.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect") - ape.Render(w, problems.InternalError()) - return - } - - if len(link) != 0 { - helpers.Log(r).WithError(err).Error("failed to authorize") - - ape.RenderErr(w, []*jsonapi.ErrorObject{{ - Title: "Forbidden", - Detail: "Invalid token", - Status: "403", - Meta: &map[string]interface{}{"auth_link": link}}, - }...) - - return - } - - client, err := helpers.ClientQ(r).GetByName(req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to get client") - ape.Render(w, problems.InternalError()) - return - } - if client == nil { - helpers.Log(r).Error(errors.Wrap(err, "client is not found")) - ape.RenderErr(w, problems.NotFound()) - return - } - - for _, user := range users { - qrData := qr.NewQR(user, helpers.Config(r)) - hash := user.Hashing(fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle)) - - if hash != "" { - helpers.Log(r).Info(user.Participant, " hash = ", hash) - } - - user.SetDataHash(hash) - var file []byte - name := "" - file, img, name, err := qrData.GenerateQR([]byte(req.Data.Address)) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to generate qrData") - ape.Render(w, problems.InternalError()) - return - } - - files = append(files, handlers.FilesBytes{File: file, Name: name, ID: user.ID, Type: "image/svg+xml"}) - - req := pdf.DefaultTemplateTall - log.Println(req) - log.Println("user", user) - certificate := pdf.NewPDF(req.High, req.Width) - certificate.SetName(req.Name.X, req.Name.Y, req.Name.FontSize, req.Name.Font) - certificate.SetDate(req.Date.X, req.Date.Y, req.Date.FontSize, req.Date.Font) - certificate.SetCourse(req.Course.X, req.Course.Y, req.Course.FontSize, req.Course.Font) - certificate.SetCredits(req.Credits.X, req.Credits.Y, req.Credits.FontSize, req.Credits.Font) - certificate.SetExam(req.Exam.X, req.Exam.Y, req.Exam.FontSize, req.Exam.Font) - certificate.SetLevel(req.Level.X, req.Level.Y, req.Level.FontSize, req.Level.Font) - certificate.SetSerialNumber(req.SerialNumber.X, req.SerialNumber.Y, req.SerialNumber.FontSize, req.SerialNumber.Font) - certificate.SetPoints(req.Points.X, req.Points.Y, req.Points.FontSize, req.Points.Font) - certificate.SetQR(req.QR.X, req.QR.Y, req.QR.FontSize, req.QR.High, req.Width) - - pdfData := pdf.NewData(user.Participant, user.CourseTitle, "45 hours / 1.5 ECTS Credit", user.Points, user.SerialNumber, user.Date, img, user.Note, "", "") - fileBytes, name, certificateImg, err := certificate.Prepare(pdfData, helpers.Config(r), helpers.TemplateQ(r), nil, client.ID) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to create pdf") - ape.Render(w, problems.BadRequest(err)) - return - } - user.ImageCertificate = certificateImg - filesCert = append(filesCert, handlers.FilesBytes{File: fileBytes, Name: name, ID: user.ID, Type: "application/pdf"}) - } - - users, err = handlers.Drive(googleClient, helpers.Log(r), files, users, SENDQR, helpers.Config(r).Google().QRPath) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to send date to drive") - ape.Render(w, problems.InternalError()) - return - } - - users, err = handlers.Drive(googleClient, helpers.Log(r), filesCert, users, SENDCERTIFICATE, helpers.Config(r).Google().PdfPath) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to send date to drive") - ape.Render(w, problems.InternalError()) - return - } - - helpers.Log(r).Info("creating table") - errs := googleClient.SetRes(users, req.Data.Url) - if errs != nil { - helpers.Log(r).Error("failed to send date to drive: Errors: ", errs) - ape.Render(w, problems.InternalError()) - return - } - - ape.Render(w, newUserWithImgResponse(users)) -} - -func newUserWithImgResponse(users []*helpers.User) resources.UserListResponse { - usersData := make([]resources.User, 0) - for _, user := range users { - resp := resources.User{ - Key: resources.Key{ - ID: fmt.Sprintf("%x", user.ID), - Type: resources.USER, - }, - Attributes: resources.UserAttributes{ - Participant: user.Participant, - Date: user.Date, - CourseTitle: user.CourseTitle, - CertificateImg: user.ImageCertificate, - DigitalCertificate: user.DigitalCertificate, - Certificate: user.Certificate, - Points: user.Points, - Note: user.Note, - Signature: user.Signature, - }, - } - usersData = append(usersData, resp) - } - - return resources.UserListResponse{ - Data: usersData, - } - -} - -func newLinkResponse(link string) resources.LinkResponse { - data := resources.LinkResponse{ - Data: resources.Link{ - Attributes: resources.LinkAttributes{ - Link: link, - }, - }, - } - return data -} diff --git a/internal/service/handlers/set_settings.go b/internal/service/handlers/set_settings.go deleted file mode 100644 index 65d2f1bb..00000000 --- a/internal/service/handlers/set_settings.go +++ /dev/null @@ -1,59 +0,0 @@ -package handlers - -import ( - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/data" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "net/http" -) - -func SetSettings(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewSetSettings(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse request") - ape.Render(w, problems.BadRequest(err)) - return - } - - settings, err := helpers.ClientQ(r).GetByName(req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to get settings") - ape.Render(w, problems.BadRequest(err)) - return - } - if settings == nil { - user := data.Client{ - Name: req.Data.Name, - Code: req.Data.Code, - } - _, err := helpers.ClientQ(r).Insert(&user) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to get settings") - ape.Render(w, problems.InternalError()) - return - } - w.WriteHeader(204) - return - } - settings.Code = req.Data.Code - err = helpers.ClientQ(r).Update(settings) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to update settings") - ape.Render(w, problems.InternalError()) - return - } - if req.Data.Code != "" { - client := google.NewGoogleClient(helpers.Config(r)) - _, err = client.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect") - ape.Render(w, problems.InternalError()) - return - } - } - w.WriteHeader(204) - return -} diff --git a/internal/service/handlers/updare_token.go b/internal/service/handlers/updare_token.go deleted file mode 100644 index e8c1ef64..00000000 --- a/internal/service/handlers/updare_token.go +++ /dev/null @@ -1,60 +0,0 @@ -package handlers - -import ( - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "net/http" -) - -func UpdateToken(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewUpdateTokenRequest(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to parse request") - ape.RenderErr(w, problems.BadRequest(err)...) - return - } - - userInfo, err := helpers.ClientQ(r).GetByName(req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to get user") - ape.RenderErr(w, problems.InternalError()) - return - } - - if userInfo == nil { - helpers.Log(r).WithError(err).Error("user is not found") - ape.RenderErr(w, problems.NotFound()) - return - } - - userInfo.Token = nil - userInfo.Code = req.Data.Code - - err = helpers.ClientQ(r).Update(userInfo) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to update user") - ape.RenderErr(w, problems.InternalError()) - return - } - - client := google.NewGoogleClient(helpers.Config(r)) - link, err := client.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) - - if len(link) != 0 { - ape.Render(w, newLinkResponse(link)) - w.WriteHeader(201) - return - } - - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect to google") - ape.RenderErr(w, problems.InternalError()) - return - } - - ape.RenderErr(w, problems.InternalError()) - -} diff --git a/internal/service/handlers/update_users.go b/internal/service/handlers/update_users.go deleted file mode 100644 index 9c7aee3f..00000000 --- a/internal/service/handlers/update_users.go +++ /dev/null @@ -1,114 +0,0 @@ -package handlers - -import ( - "github.com/google/jsonapi" - "gitlab.com/distributed_lab/ape" - "gitlab.com/distributed_lab/ape/problems" - "gitlab.com/distributed_lab/logan/v3/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/handlers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/google" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "gitlab.com/tokend/course-certificates/ccp/internal/service/pdf" - "gitlab.com/tokend/course-certificates/ccp/internal/service/requests" - "net/http" -) - -func UpdateCertificate(w http.ResponseWriter, r *http.Request) { - req, err := requests.NewPrepareCertificates(r) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect") - ape.Render(w, problems.InternalError()) - return - } - users := req.PrepareUsers() - - var filesCert []handlers.FilesBytes - - googleClient := google.NewGoogleClient(helpers.Config(r)) - link, err := googleClient.Connect(helpers.Config(r).Google().SecretPath, helpers.ClientQ(r), req.Data.Name) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to connect") - ape.Render(w, problems.InternalError()) - return - } - - if len(link) != 0 { - helpers.Log(r).WithError(err).Error("failed to authorize") - ape.RenderErr(w, []*jsonapi.ErrorObject{{ - Title: "Forbidden", - Detail: "Invalid token", - Status: "403", - Meta: &map[string]interface{}{"auth_link": link}}, - }...) - - return - } - - client, err := helpers.ClientQ(r).GetByName(req.Data.Name) //todo use relationship - helpers.Log(r).Debug("user ", client) - if err != nil { - helpers.Log(r).Error(errors.Wrap(err, "failed to get user")) - ape.Render(w, problems.InternalError()) - return - } - if client == nil { - helpers.Log(r).Error(errors.Wrap(err, "user is not found")) - ape.Render(w, problems.NotFound()) - return - } - - for _, user := range users { - //qrData := qr.NewQR(user, helpers.Config(r)) - //_, img, name, err := qrData.GenerateQR([]byte(req.Data.Address)) - //if err != nil { - // helpers.Log(r).WithError(err).Error("failed to generate qrData") - // ape.Render(w, problems.InternalError()) - // return - //} - - //hash := user.Hashing(fmt.Sprintf("%s %s %s", user.Date, user.Participant, user.CourseTitle)) - //if hash != "" { - // helpers.Log(r).Info(user.Participant, " hash = ", hash) - //} - // - //user.SetDataHash(hash) - helpers.Log(r).Info(user.TxHash, " tx") - if user.TxHash != "" { - user.SetDataHash(user.TxHash) - helpers.Log(r).Info(user.DataHash) - helpers.Log(r).Info(user.TxHash) - } - - req := pdf.DefaultTemplateTall - helpers.Log(r).Info("user", user) - certificate := pdf.NewPDF(req.High, req.Width) - certificate.SetSerialNumber(req.SerialNumber.X, req.SerialNumber.Y, req.SerialNumber.FontSize, req.SerialNumber.Font) - - pdfData := pdf.NewData("", user.CourseTitle, "", "", user.SerialNumber, "", nil, "", "", "") - fileBytes, name, certificateImg, err := certificate.Prepare(pdfData, helpers.Config(r), helpers.TemplateQ(r), user.ImageCertificate, client.ID) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to create pdf") - ape.Render(w, problems.BadRequest(err)) - return - } - user.ImageCertificate = certificateImg - filesCert = append(filesCert, handlers.FilesBytes{File: fileBytes, Name: name, ID: user.ID, Type: "application/pdf"}) - } - - users, err = handlers.Drive(googleClient, helpers.Log(r), filesCert, users, SENDCERTIFICATE, helpers.Config(r).Google().PdfPath) - if err != nil { - helpers.Log(r).WithError(err).Error("failed to send date to drive") - ape.Render(w, problems.InternalError()) - return - } - - helpers.Log(r).Info("creating table") - errs := googleClient.SetRes(users, req.Data.Url) - if errs != nil { - helpers.Log(r).Error("failed to send date to drive: Errors: ", errs) - ape.Render(w, problems.InternalError()) - return - } - - ape.Render(w, newUserWithImgResponse(users)) -} diff --git a/internal/service/ipfs/ipfs.go b/internal/service/ipfs/ipfs.go deleted file mode 100644 index 7e66d54d..00000000 --- a/internal/service/ipfs/ipfs.go +++ /dev/null @@ -1,102 +0,0 @@ -package ipfs - -import ( - "bytes" - "encoding/json" - shell "github.com/ipfs/go-ipfs-api" - "gitlab.com/distributed_lab/logan/v3/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/config" - "image/png" - "net/http" - "os" - "path/filepath" - "strings" -) - -type Connector struct { - cfg config.Config -} - -type ERC721json struct { - Name string `json:"name"` - Description string `json:"description"` - Image string `json:"image"` - ExternalUrl string `json:"external_url"` -} - -func NewConnector(cfg config.Config) *Connector { - return &Connector{cfg: cfg} -} - -func (i Connector) Upload(data []byte) (string, error) { - ipfs := shell.NewShellWithClient(i.cfg.NetworksConfig().IPFSEndpoint, NewClient(i.cfg.NetworksConfig().IpfsPrId, i.cfg.NetworksConfig().IpfsPrKey)) - - fileHash, err := ipfs.Add(bytes.NewReader(data)) - if err != nil { - return "", errors.Wrap(err, "failed to upload") - } - return fileHash, nil - -} - -func (i Connector) PrepareJSON(tokenName, tokenDescription, imagePath string) ([]byte, error) { - erc721 := ERC721json{ - Name: tokenName, - Description: tokenDescription, - Image: "https://ipfs.io/ipfs/" + imagePath, - ExternalUrl: "https://dlt-academy.com/certificates", - } - - erc721JSON, err := json.Marshal(erc721) - if err != nil { - return nil, errors.Wrap(err, "failed to marshal erc721") - } - - return erc721JSON, nil -} - -func (i Connector) PrepareImageyPath(imagePath string) ([]byte, error) { - path, err := filepath.Abs("main.go") - if err != nil { - return nil, errors.Wrap(err, "failed to get absolute path") - } - path = strings.ReplaceAll(path, "main.go", "") - - infile, err := os.Open(path + imagePath) - if err != nil { - return nil, errors.Wrap(err, "failed to open image") - } - img, err := png.Decode(infile) - if err != nil { - return nil, errors.Wrap(err, "failed to decode image") - } - - buf := new(bytes.Buffer) - err = png.Encode(buf, img) - if err != nil { - return nil, errors.Wrap(err, "failed to decode image to []byte") - } - return buf.Bytes(), nil -} - -func NewClient(projectId, projectSecret string) *http.Client { - return &http.Client{ - Transport: authTransport{ - RoundTripper: http.DefaultTransport, - ProjectId: projectId, - ProjectSecret: projectSecret, - }, - } -} - -// authTransport decorates each request with a basic auth header. -type authTransport struct { - http.RoundTripper - ProjectId string - ProjectSecret string -} - -func (t authTransport) RoundTrip(r *http.Request) (*http.Response, error) { - r.SetBasicAuth(t.ProjectId, t.ProjectSecret) - return t.RoundTripper.RoundTrip(r) -} diff --git a/internal/service/pdf/images.go b/internal/service/pdf/images.go deleted file mode 100644 index 510dc04b..00000000 --- a/internal/service/pdf/images.go +++ /dev/null @@ -1,123 +0,0 @@ -package pdf - -import ( - "bytes" - "encoding/base64" - "image" - "image/jpeg" - "log" - "os" - "os/exec" - "path/filepath" -) - -//func Convert(imgType string, blob []byte) ([]byte, error) { -// log.Println("init") -// -// imagick.Initialize() -// log.Println("Terminate") -// -// defer imagick.Terminate() -// log.Println("NewMagickWand") -// -// mw := imagick.NewMagickWand() -// -// defer mw.Destroy() -// log.Println("ReadImageBlob") -// -// err := mw.ReadImageBlob(blob) -// if err != nil { -// return nil, errors.Wrap(err, "failed to read img blob") -// } -// log.Println("SetIteratorIndex") -// -// mw.SetIteratorIndex(0) -// log.Println("SetImageFormat") -// -// err = mw.SetImageFormat(imgType) -// if err != nil { -// return nil, errors.Wrap(err, "failed to set format") -// } -// log.Println("GetImageBlob") -// -// return mw.GetImageBlob(), nil -//} - -func Convert(imgType string, blob []byte) ([]byte, error) { - fileInput, err := os.Create("input.pdf") - if err != nil { - return nil, err - } - _, err = fileInput.Write(blob) - if err != nil { - return nil, err - } - - fileInputPath, err := filepath.Abs(fileInput.Name()) - if err != nil { - return nil, err - } - - fileOutput, err := os.Create("output.png") - if err != nil { - return nil, err - } - - err = fileOutput.Close() - if err != nil { - return nil, err - } - - fileOutputPath, err := filepath.Abs(fileOutput.Name()) - if err != nil { - return nil, err - } - - log.Println() - res, err := exec.Command("pwd").Output() - if err != nil { - return nil, err - } - log.Println(string(res)) - - res, err = exec.Command("ls").Output() - if err != nil { - return nil, err - } - - log.Println(string(res)) - - log.Println(fileInputPath + " " + fileOutputPath) - cmd := exec.Command("sh", "-c", "gs -sDEVICE=png16m -dNOPAUSE -dBATCH -dSAFER -sOutputFile="+fileOutputPath+" "+fileInputPath) - out, err := cmd.Output() - if err != nil { - return nil, err - } - - log.Println(out) - - fileBlob, err := os.ReadFile(fileOutputPath) - if err != nil { - return nil, err - } - - return fileBlob, nil -} - -func base64toJpg(data []byte) ([]byte, error) { - - reader := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(data)) - m, _, err := image.Decode(reader) - if err != nil { - return nil, err - } - - //Encode from image format to writer - buf := new(bytes.Buffer) - - err = jpeg.Encode(buf, m, &jpeg.Options{Quality: 75}) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} diff --git a/internal/service/pdf/pdf.go b/internal/service/pdf/pdf.go deleted file mode 100644 index 41ef451c..00000000 --- a/internal/service/pdf/pdf.go +++ /dev/null @@ -1,227 +0,0 @@ -package pdf - -import ( - "bytes" - "fmt" - "github.com/signintech/gopdf" - "gitlab.com/distributed_lab/logan/v3/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/config" - "gitlab.com/tokend/course-certificates/ccp/internal/data" - "image" - "io" - "log" - "os" - "strings" -) - -func (p *PDF) Prepare(data PDFData, cfg config.Config, templateQ data.TemplateQ, backgroundImg []byte, userID int64) ([]byte, string, []byte, error) { - var err error - pdf := gopdf.GoPdf{} - pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: p.Width, H: p.High}}) - pdf.AddPage() - pdf.SetTextColor(255, 255, 255) - err = pdf.AddTTFFont("italic", "/usr/local/bin/staff/font/Inter-Italic.ttf") - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to add font") - } - err = pdf.AddTTFFont("regular", "/usr/local/bin/staff/font/Inter-Regular.ttf") - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to add Inter-Regular") - } - err = pdf.AddTTFFont("semibold", "/usr/local/bin/staff/font/Inter-SemiBold.ttf") - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to add Inter-SemiBold.ttf") - } - - templateImg := cfg.TemplatesConfig()[data.Course] - - if backgroundImg == nil { - template, err := templateQ.GetByName(templateImg, userID) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to get background img") - } - if template == nil { - titles := cfg.TitlesConfig() - _ = titles - template, err = templateQ.GetByName(templateImg, userID) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to get default background img") - } - - } - - var back []byte - if template != nil { - back, err = base64toJpg(template.ImgBytes) - if err != nil { - return nil, "", nil, errors.Wrap(err, "cant to decode img") - - } - } else { - - file, err := os.Open(fmt.Sprintf("/usr/local/bin/staff/templates/%s.png", templateImg)) - fmt.Println(fmt.Sprintf("/usr/local/bin/staff/templates/%s.png", templateImg)) - defer file.Close() - if err != nil { - return nil, "", nil, errors.Wrap(err, "default template isn't found") - } - - back, err = io.ReadAll(file) - if err != nil { - return nil, "", nil, errors.Wrap(err, "cant to decode img") - - } - } - - backgroundImgHolder, err := gopdf.ImageHolderByBytes(back) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to prepare background") - } - - err = pdf.ImageByHolder(backgroundImgHolder, 0, 0, &gopdf.Rect{W: p.Width, H: p.High}) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set background") - } - } else { - backgroundImgHolder, err := gopdf.ImageHolderByBytes(backgroundImg) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to prepare background") - } - - err = pdf.ImageByHolder(backgroundImgHolder, 0, 0, &gopdf.Rect{W: p.Width, H: p.High}) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set background") - } - } - - ///////// name - err = pdf.SetFont("regular", "", p.Name.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - //pdf.SetX(p.centralizeName(data.Name, p.Width, p.Name.FontSize)) - pdf.SetY(p.Name.Y) - pdf.SetX(0) - //pdf.Cell(nil, data.Name) - fmt.Println(p.Width, p.High) - pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, data.Name, gopdf.CellOption{Align: gopdf.Center}) - - ///////////// credits - err = pdf.SetFont("italic", "", p.Credits.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - pdf.SetX(p.Credits.X) - pdf.SetY(p.Credits.Y) - pdf.Cell(&gopdf.Rect{W: p.Width, H: p.High}, fmt.Sprintf(data.Credits)) - - ///////////// Points - err = pdf.SetFont("italic", "", p.Points.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - - } - pdf.SetX(p.Points.X) - pdf.SetY(p.Points.Y) - pdf.Cell(&gopdf.Rect{W: p.Width, H: p.High}, fmt.Sprintf("Count of points: %s", data.Points)) - - ///////////// SerialNumber - err = pdf.SetFont("italic", "", p.SerialNumber.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - - pdf.SetX(p.SerialNumber.X) - pdf.SetY(p.SerialNumber.Y) - pdf.Cell(nil, data.SerialNumber) - - ///////////// Date - err = pdf.SetFont("italic", "", p.Date.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - - pdf.SetX(p.Date.X) - pdf.SetY(p.Date.Y) - pdf.Cell(&gopdf.Rect{W: p.Width, H: p.High}, fmt.Sprintf("Issued on: %s", data.Date)) - - ///////////// Course - err = pdf.SetFont("italic", "", p.Course.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - //pdf.SetTextColor() - pdf.SetX(0) - pdf.SetY(p.Course.Y) - titles := cfg.TitlesConfig() - isLevel, title, level := p.checkLevel(titles[templateImg]) - pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, title, gopdf.CellOption{Align: gopdf.Center}) - - /////////// QR - if data.QR != nil { - img, _, err := image.Decode(bytes.NewReader(data.QR)) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to convert bytes to image") - } - - log.Println("p.QR.High: ", p.QR.High) - log.Println("p.QR.Width: ", p.QR.High) - err = pdf.ImageFrom(img, p.QR.X, p.QR.Y, &gopdf.Rect{W: p.QR.High, H: p.QR.High}) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set image") - } - } - - /////////////// Exam - err = pdf.SetFont("italic", "", p.Exam.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - pdf.SetX(0) - pdf.SetY(p.Exam.Y) - ex := cfg.ExamsConfig() - pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, ex[data.Exam], gopdf.CellOption{Align: gopdf.Center}) - ///////////// Level - if isLevel { - err = pdf.SetFont("italic", "", p.Level.FontSize) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to set font") - } - pdf.SetX(0) - pdf.SetY(p.Level.Y) - pdf.CellWithOption(&gopdf.Rect{W: p.Width, H: p.High}, level, gopdf.CellOption{Align: gopdf.Center}) - - } - - parsedName := strings.Split(data.Name, " ") - name := "" - if len(parsedName) < 2 { - name = fmt.Sprintf("certificate_%s_%s.pdf", parsedName[0], cfg.TemplatesConfig()[data.Course]) - } else { - name = fmt.Sprintf("certificate_%s_%s_%s.pdf", parsedName[0], parsedName[1], cfg.TemplatesConfig()[data.Course]) - } - - pdfBlob := pdf.GetBytesPdf() - - imgBlob, err := Convert("png", pdfBlob) - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to convert pdf to png") - } - file, err := os.Create("test.png") - if err != nil { - return nil, "", nil, errors.Wrap(err, "failed to create png file") - } - - file.Write(imgBlob) - file.Close() - return pdfBlob, name, imgBlob, nil - -} - -func (p *PDF) checkLevel(title string) (bool, string, string) { - strs := strings.Split(title, "Level:") - if len(strs) > 1 { - return true, strs[0], fmt.Sprint("Level:", strs[1]) - } - return false, strs[0], "" -} diff --git a/internal/service/pdf/types.go b/internal/service/pdf/types.go deleted file mode 100644 index d8f73457..00000000 --- a/internal/service/pdf/types.go +++ /dev/null @@ -1,288 +0,0 @@ -package pdf - -type PDF struct { - High float64 `json:"high"` - Width float64 `json:"width"` - Name Field `json:"name"` - Course Field `json:"course"` - Credits Field `json:"credits"` - Points Field `json:"points"` - SerialNumber Field `json:"serial_number"` - Date Field `json:"date"` - QR Field `json:"qr"` - Exam Field `json:"exam"` - Level Field `json:"level"` - Note Field `json:"note"` -} - -type Field struct { - X float64 `json:"x"` - Y float64 `json:"y"` - XCenter bool `json:"x_center"` - YCenter bool `json:"y_center"` - FontSize int `json:"font_size"` - Color string `json:"color"` - Font string `json:"font"` - High float64 `json:"high"` - Width float64 `json:"width"` -} - -type PDFData struct { - Name string - Course string - Credits string - Points string - SerialNumber string - Date string - QR []byte - Exam string - Level string - Note string -} - -var DefaultTemplateNormal = PDF{ - High: 595, - Width: 842, - Name: Field{ - X: 200, - Y: 217, - FontSize: 28, - Font: "semibold", - }, - Course: Field{ - X: 61, - Y: 259, - FontSize: 14, - Font: "semibold", - }, - Credits: Field{ - X: 70, - Y: 56, - FontSize: 12, - Font: "regular", - }, - Points: Field{ - X: 70, - Y: 79, - FontSize: 12, - Font: "regular", - }, - SerialNumber: Field{ - X: 641, - Y: 56, - FontSize: 12, - Font: "regular", - }, - Date: Field{ - X: 641, - Y: 79, - FontSize: 12, - Font: "regular", - }, - QR: Field{ - X: 658, - Y: 106, - High: 114, - Width: 114, - }, - Exam: Field{ - X: 300, - Y: 300, - FontSize: 15, - Font: "italic", - }, - Level: Field{ - X: 300, - Y: 277, - FontSize: 14, - Font: "semibold", - }, -} - -var DefaultTemplateTall = PDF{ - High: 1190, - Width: 1684, - Name: Field{ - Y: 434, - FontSize: 56, - Font: "semibold", - }, - Course: Field{ - Y: 518, - FontSize: 28, - Font: "semibold", - }, - Credits: Field{ //todo get from front and save to db - X: 140, - Y: 112, - FontSize: 24, - Font: "regular", - }, - Points: Field{ - X: 140, - Y: 158, - FontSize: 24, - Font: "regular", - }, - SerialNumber: Field{ - X: 1270, - Y: 112, - FontSize: 24, - Font: "regular", - }, - Date: Field{ - X: 1282, - Y: 158, - FontSize: 24, - Font: "regular", - }, - QR: Field{ - X: 1316, - Y: 212, - High: 228, - Width: 228, - }, - Exam: Field{ - Y: 600, - FontSize: 30, - Font: "italic", - }, - Level: Field{ - Y: 554, - FontSize: 28, - Font: "semibold", - }, -} - -var DefaultData = PDFData{ - Name: "Test Name", - Course: "Blockchain and Distributed Systems", - Credits: " 99", - Points: "100", - SerialNumber: "694d0f5a7afe6fbc99cb", - Date: "30.05.2018", - QR: nil, - Exam: "passed", - Level: "graduated with honors", - Note: "************************************************", -} - -func NewPDF(high, width float64) *PDF { - return &PDF{ - High: high, - Width: width, - } -} - -func NewData(name, course, credits, points, serialNumber, date string, qr []byte, exam, level, note string) PDFData { - return PDFData{ - Name: name, - Course: course, - Credits: credits, - Points: points, - SerialNumber: serialNumber, - Date: date, - QR: qr, - Exam: exam, - Level: level, - Note: note, - } -} - -func (p *PDF) SetName(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Name = fl -} - -func (p *PDF) SetCourse(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Course = fl -} -func (p *PDF) SetCredits(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Credits = fl -} - -func (p *PDF) SetLevel(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Level = fl -} - -func (p *PDF) SetPoints(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Points = fl -} - -func (p *PDF) SetSerialNumber(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.SerialNumber = fl -} - -func (p *PDF) SetDate(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Date = fl -} -func (p *PDF) SetQR(x, y float64, size int, high, width float64) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - High: high, - Width: width, - } - - p.QR = fl -} - -func (p *PDF) SetExam(x, y float64, size int, font string) { - fl := Field{ - X: x, - Y: y, - FontSize: size, - Font: font, - } - - p.Exam = fl -} diff --git a/internal/service/requests/create_template.go b/internal/service/requests/create_template.go deleted file mode 100644 index 173dfe3f..00000000 --- a/internal/service/requests/create_template.go +++ /dev/null @@ -1,60 +0,0 @@ -package requests - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "github.com/pkg/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/service/pdf" - "gitlab.com/tokend/course-certificates/ccp/resources" - "image" - "image/jpeg" - "net/http" - "strings" -) - -type GenerateTemplate struct { - Data resources.Template -} - -func NewGenerateTemplate(r *http.Request) (pdf.PDF, []byte, GenerateTemplate, error) { - response := GenerateTemplate{} - err := json.NewDecoder(r.Body).Decode(&response) - if err != nil { - return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to decode data") - } - pdfTemplate := pdf.PDF{} - err = json.Unmarshal(response.Data.Attributes.Template, &pdfTemplate) - if err != nil { - return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to decode data") - } - - str := strings.ReplaceAll(response.Data.Attributes.BackgroundImg, "data:image/jpeg;base64,", "") - str = strings.ReplaceAll(str, "data:image/png;base64,", "") - - data, err := base64toJpg(str) - if err != nil { - return pdf.PDF{}, nil, GenerateTemplate{}, errors.Wrap(err, "failed to decode data") - - } - return pdfTemplate, data, response, err -} - -// Given a base64 string of a JPEG, encodes it into an JPEG image test.jpg -func base64toJpg(data string) ([]byte, error) { - - reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) - m, _, err := image.Decode(reader) - if err != nil { - return nil, err - } - - //Encode from image format to writer - buf := new(bytes.Buffer) - - err = jpeg.Encode(buf, m, &jpeg.Options{Quality: 75}) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} diff --git a/internal/service/requests/get_users.go b/internal/service/requests/get_users.go deleted file mode 100644 index b97b06c4..00000000 --- a/internal/service/requests/get_users.go +++ /dev/null @@ -1,31 +0,0 @@ -package requests - -import ( - "encoding/json" - "github.com/pkg/errors" - "gitlab.com/tokend/course-certificates/ccp/resources" - "net/http" - "strings" -) - -type GetUsers struct { - Data resources.UsersGetRequest -} - -func NewGetUsers(r *http.Request) (GetUsers, error) { - //https://docs.google.com/spreadsheets/d/1CYqLid0t90bgGm1HPx5j8q-h_RNVVLPVkot9iJZguuo/edit#gid=1988631106 - response := GetUsers{} - err := json.NewDecoder(r.Body).Decode(&response) - if err != nil { - return GetUsers{}, errors.Wrap(err, "failed to decode data") - } - response.Data.Url = response.parse() - - return response, err -} - -func (g *GetUsers) parse() string { - id := strings.Replace(g.Data.Url, "https://docs.google.com/spreadsheets/d/", "", 1) - id = strings.Replace(id, "/", "", 1) - return id -} diff --git a/internal/service/requests/ipfs_upload.go b/internal/service/requests/ipfs_upload.go deleted file mode 100644 index eab73ed1..00000000 --- a/internal/service/requests/ipfs_upload.go +++ /dev/null @@ -1,21 +0,0 @@ -package requests - -import ( - "encoding/json" - "github.com/pkg/errors" - "gitlab.com/tokend/course-certificates/ccp/resources" - "net/http" -) - -type UploadFileToIPFS struct { - Data resources.IpfsFileUploadRequest //todo replace string to []byte -} - -func NewUploadFileToIPFS(r *http.Request) (UploadFileToIPFS, error) { - response := UploadFileToIPFS{} - err := json.NewDecoder(r.Body).Decode(&response) - if err != nil { - return UploadFileToIPFS{}, errors.Wrap(err, "failed to decode data") - } - return response, err -} diff --git a/internal/service/requests/prepare_certificates.go b/internal/service/requests/prepare_certificates.go deleted file mode 100644 index 8a32a30e..00000000 --- a/internal/service/requests/prepare_certificates.go +++ /dev/null @@ -1,86 +0,0 @@ -package requests - -import ( - "encoding/json" - "github.com/pkg/errors" - "gitlab.com/tokend/course-certificates/ccp/internal/service/helpers" - "net/http" - "strings" -) - -type PrepareCertificates struct { - Data PdfsCreateRequest //todo update model -} - -type PdfsCreateRequest struct { - Address string `json:"address"` - Data []User `json:"users"` - Name string `json:"name"` - Url string `json:"url"` -} - -type User struct { - Certificate string `json:"certificate"` - CertificateImg string `json:"certificateImg"` - CourseTitle string `json:"courseTitle"` - DataHash string `json:"dataHash"` - Date string `json:"date"` - DigitalCertificate string `json:"digitalCertificate"` - ID int64 `json:"id"` - Msg string `json:"msg"` - Note string `json:"note"` - Participant string `json:"participant"` - Points string `json:"points"` - SerialNumber string `json:"serialNumber"` - Signature string `json:"signature"` - TxHash string `json:"txHash"` -} - -func NewPrepareCertificates(r *http.Request) (PrepareCertificates, error) { - response := PrepareCertificates{} - //response.Data.Data = make([]*resources.User, 0) - err := json.NewDecoder(r.Body).Decode(&response) - if err != nil { - return PrepareCertificates{}, errors.Wrap(err, "failed to decode data") - } - response.Data.Url = response.parse() - return response, err -} - -func (p PrepareCertificates) PrepareUsers() []*helpers.User { - result := make([]*helpers.User, 0) - for _, user := range p.Data.Data { - //id, err := strconv.ParseInt(user.ID, 16, 64) - //if err != nil { - // return nil - //} - img, err := base64toJpg(user.CertificateImg) - if err != nil { - img = nil - } - resUser := helpers.User{ - ID: int(user.ID), - Date: user.Date, - CourseTitle: user.CourseTitle, - TxHash: user.TxHash, - Signature: user.Signature, - DataHash: user.DataHash, - SerialNumber: user.SerialNumber, - Note: user.Note, - Msg: user.Msg, - Participant: user.Participant, - Points: user.Points, - Certificate: user.Certificate, - DigitalCertificate: user.DigitalCertificate, - ImageCertificate: img, - } - result = append(result, &resUser) - } - return result -} - -func (g *PrepareCertificates) parse() string { - id := strings.Replace(g.Data.Url, "https://docs.google.com/spreadsheets/d/", "", 1) - id = strings.Replace(id, "/", "", 1) - return id -} diff --git a/internal/service/requests/set_settings.go b/internal/service/requests/set_settings.go deleted file mode 100644 index 3192fb5e..00000000 --- a/internal/service/requests/set_settings.go +++ /dev/null @@ -1,21 +0,0 @@ -package requests - -import ( - "encoding/json" - "github.com/pkg/errors" - "gitlab.com/tokend/course-certificates/ccp/resources" - "net/http" -) - -type SetSettings struct { - Data resources.Settings -} - -func NewSetSettings(r *http.Request) (SetSettings, error) { - res := SetSettings{} - err := json.NewDecoder(r.Body).Decode(&res) - if err != nil { - return SetSettings{}, errors.Wrap(err, "failed to decode data") - } - return res, nil -} diff --git a/resources/model_container.go b/resources/model_container.go new file mode 100644 index 00000000..ddb7556f --- /dev/null +++ b/resources/model_container.go @@ -0,0 +1,31 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type Container struct { + Key + Attributes ContainerAttributes `json:"attributes"` +} +type ContainerResponse struct { + Data Container `json:"data"` + Included Included `json:"included"` +} + +type ContainerListResponse struct { + Data []Container `json:"data"` + Included Included `json:"included"` + Links *Links `json:"links"` +} + +// MustContainer - returns Container from include collection. +// if entry with specified key does not exist - returns nil +// if entry with specified key exists but type or ID mismatches - panics +func (c *Included) MustContainer(key Key) *Container { + var container Container + if c.tryFindEntry(key, &container) { + return &container + } + return nil +} diff --git a/resources/model_container_attributes.go b/resources/model_container_attributes.go new file mode 100644 index 00000000..8c649925 --- /dev/null +++ b/resources/model_container_attributes.go @@ -0,0 +1,11 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type ContainerAttributes struct { + Certificates []User `json:"certificates"` + ContainerId string `json:"container_id"` + Status string `json:"status"` +} diff --git a/resources/model_ipfs_file_upload.go b/resources/model_ipfs_file_upload.go new file mode 100644 index 00000000..19d31e1b --- /dev/null +++ b/resources/model_ipfs_file_upload.go @@ -0,0 +1,31 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type IpfsFileUpload struct { + Key + Attributes IpfsFileUploadAttributes `json:"attributes"` +} +type IpfsFileUploadResponse struct { + Data IpfsFileUpload `json:"data"` + Included Included `json:"included"` +} + +type IpfsFileUploadListResponse struct { + Data []IpfsFileUpload `json:"data"` + Included Included `json:"included"` + Links *Links `json:"links"` +} + +// MustIpfsFileUpload - returns IpfsFileUpload from include collection. +// if entry with specified key does not exist - returns nil +// if entry with specified key exists but type or ID mismatches - panics +func (c *Included) MustIpfsFileUpload(key Key) *IpfsFileUpload { + var ipfsFileUpload IpfsFileUpload + if c.tryFindEntry(key, &ipfsFileUpload) { + return &ipfsFileUpload + } + return nil +} diff --git a/resources/model_ipfs_file_upload_request.go b/resources/model_ipfs_file_upload_attributes.go similarity index 83% rename from resources/model_ipfs_file_upload_request.go rename to resources/model_ipfs_file_upload_attributes.go index a53b4cee..d683d239 100644 --- a/resources/model_ipfs_file_upload_request.go +++ b/resources/model_ipfs_file_upload_attributes.go @@ -4,7 +4,7 @@ package resources -type IpfsFileUploadRequest struct { +type IpfsFileUploadAttributes struct { Description string `json:"description"` Img []byte `json:"img"` Name string `json:"name"` diff --git a/resources/model_parse_users.go b/resources/model_parse_users.go new file mode 100644 index 00000000..c6be4856 --- /dev/null +++ b/resources/model_parse_users.go @@ -0,0 +1,31 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type ParseUsers struct { + Key + Attributes ParseUsersAttributes `json:"attributes"` +} +type ParseUsersResponse struct { + Data ParseUsers `json:"data"` + Included Included `json:"included"` +} + +type ParseUsersListResponse struct { + Data []ParseUsers `json:"data"` + Included Included `json:"included"` + Links *Links `json:"links"` +} + +// MustParseUsers - returns ParseUsers from include collection. +// if entry with specified key does not exist - returns nil +// if entry with specified key exists but type or ID mismatches - panics +func (c *Included) MustParseUsers(key Key) *ParseUsers { + var parseUsers ParseUsers + if c.tryFindEntry(key, &parseUsers) { + return &parseUsers + } + return nil +} diff --git a/resources/model_users_get_request.go b/resources/model_parse_users_attributes.go similarity index 80% rename from resources/model_users_get_request.go rename to resources/model_parse_users_attributes.go index 7f346d77..cfb71fbe 100644 --- a/resources/model_users_get_request.go +++ b/resources/model_parse_users_attributes.go @@ -4,7 +4,7 @@ package resources -type UsersGetRequest struct { +type ParseUsersAttributes struct { Name string `json:"name"` Url string `json:"url"` } diff --git a/resources/model_pdfs_create_request.go b/resources/model_pdfs_create_request.go deleted file mode 100644 index d7aabf26..00000000 --- a/resources/model_pdfs_create_request.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - * GENERATED. Do not modify. Your changes might be overwritten! - */ - -package resources - -type PdfsCreateRequest struct { - Address string `json:"address"` - Data []User `json:"data"` - Name string `json:"name"` - Url string `json:"url"` -} diff --git a/resources/model_prepare_certificates.go b/resources/model_prepare_certificates.go new file mode 100644 index 00000000..224f78fc --- /dev/null +++ b/resources/model_prepare_certificates.go @@ -0,0 +1,31 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type PrepareCertificates struct { + Key + Attributes PrepareCertificatesAttributes `json:"attributes"` +} +type PrepareCertificatesResponse struct { + Data PrepareCertificates `json:"data"` + Included Included `json:"included"` +} + +type PrepareCertificatesListResponse struct { + Data []PrepareCertificates `json:"data"` + Included Included `json:"included"` + Links *Links `json:"links"` +} + +// MustPrepareCertificates - returns PrepareCertificates from include collection. +// if entry with specified key does not exist - returns nil +// if entry with specified key exists but type or ID mismatches - panics +func (c *Included) MustPrepareCertificates(key Key) *PrepareCertificates { + var prepareCertificates PrepareCertificates + if c.tryFindEntry(key, &prepareCertificates) { + return &prepareCertificates + } + return nil +} diff --git a/resources/model_prepare_certificates_attributes.go b/resources/model_prepare_certificates_attributes.go new file mode 100644 index 00000000..edf938e5 --- /dev/null +++ b/resources/model_prepare_certificates_attributes.go @@ -0,0 +1,12 @@ +/* + * GENERATED. Do not modify. Your changes might be overwritten! + */ + +package resources + +type PrepareCertificatesAttributes struct { + Address string `json:"address"` + CertificatesData []UserBlob `json:"certificates_data"` + Name string `json:"name"` + Url string `json:"url"` +} diff --git a/resources/model_resource_type.go b/resources/model_resource_type.go index 4c200ce6..8f4bb417 100644 --- a/resources/model_resource_type.go +++ b/resources/model_resource_type.go @@ -8,8 +8,13 @@ type ResourceType string // List of ResourceType const ( - IPFS ResourceType = "ipfs" - LINK ResourceType = "link" - TEMPLATE ResourceType = "template" - USER ResourceType = "user" + CONTAINER ResourceType = "container" + IPFS_FILE ResourceType = "ipfs_file" + IPFS_FILE_UPLOAD ResourceType = "ipfs_file_upload" + LINK ResourceType = "link" + PARSE_USERS ResourceType = "parse_users" + PREPARE_CERTIFICATE ResourceType = "prepare_certificate" + SETTINGS ResourceType = "settings" + TEMPLATE ResourceType = "template" + USER ResourceType = "user" ) diff --git a/resources/model_response_template.go b/resources/model_response_template.go deleted file mode 100644 index 1ad565ec..00000000 --- a/resources/model_response_template.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - * GENERATED. Do not modify. Your changes might be overwritten! - */ - -package resources - -type ResponseTemplate struct { - Key - Attributes ResponseTemplateAttributes `json:"attributes"` -} -type ResponseTemplateResponse struct { - Data ResponseTemplate `json:"data"` - Included Included `json:"included"` -} - -type ResponseTemplateListResponse struct { - Data []ResponseTemplate `json:"data"` - Included Included `json:"included"` - Links *Links `json:"links"` -} - -// MustResponseTemplate - returns ResponseTemplate from include collection. -// if entry with specified key does not exist - returns nil -// if entry with specified key exists but type or ID mismatches - panics -func (c *Included) MustResponseTemplate(key Key) *ResponseTemplate { - var responseTemplate ResponseTemplate - if c.tryFindEntry(key, &responseTemplate) { - return &responseTemplate - } - return nil -} diff --git a/resources/model_settings.go b/resources/model_settings.go index d16937cb..cf113eee 100644 --- a/resources/model_settings.go +++ b/resources/model_settings.go @@ -5,6 +5,27 @@ package resources type Settings struct { - Code string `json:"code"` - Name string `json:"name"` + Key + Attributes SettingsAttributes `json:"attributes"` +} +type SettingsResponse struct { + Data Settings `json:"data"` + Included Included `json:"included"` +} + +type SettingsListResponse struct { + Data []Settings `json:"data"` + Included Included `json:"included"` + Links *Links `json:"links"` +} + +// MustSettings - returns Settings from include collection. +// if entry with specified key does not exist - returns nil +// if entry with specified key exists but type or ID mismatches - panics +func (c *Included) MustSettings(key Key) *Settings { + var settings Settings + if c.tryFindEntry(key, &settings) { + return &settings + } + return nil } diff --git a/resources/model_response_template_attributes.go b/resources/model_settings_attributes.go similarity index 51% rename from resources/model_response_template_attributes.go rename to resources/model_settings_attributes.go index 77ba270e..be7e132e 100644 --- a/resources/model_response_template_attributes.go +++ b/resources/model_settings_attributes.go @@ -4,6 +4,7 @@ package resources -type ResponseTemplateAttributes struct { - Image []byte `json:"image"` +type SettingsAttributes struct { + Code string `json:"code"` + Name string `json:"name"` } diff --git a/resources/model_user.go b/resources/model_user.go index c555f3b3..f5e901a2 100644 --- a/resources/model_user.go +++ b/resources/model_user.go @@ -6,7 +6,7 @@ package resources type User struct { Key - Attributes UserAttributes `json:"attributes"` + Attributes UserBlob `json:"attributes"` } type UserResponse struct { Data User `json:"data"` diff --git a/resources/model_user_attributes.go b/resources/model_user_blob.go similarity index 96% rename from resources/model_user_attributes.go rename to resources/model_user_blob.go index ef70a13e..03188d81 100644 --- a/resources/model_user_attributes.go +++ b/resources/model_user_blob.go @@ -4,7 +4,7 @@ package resources -type UserAttributes struct { +type UserBlob struct { Certificate string `json:"certificate"` CertificateImg []byte `json:"certificateImg"` CourseTitle string `json:"courseTitle"` diff --git a/staff/templates/blockchain.png b/staff/templates/blockchain.png deleted file mode 100644 index 31934ca5..00000000 Binary files a/staff/templates/blockchain.png and /dev/null differ diff --git a/staff/templates/defi.png b/staff/templates/defi.png deleted file mode 100644 index 13f9e41d..00000000 Binary files a/staff/templates/defi.png and /dev/null differ diff --git a/staff/font/Inter-Italic.ttf b/static/font/Inter-Italic.ttf similarity index 100% rename from staff/font/Inter-Italic.ttf rename to static/font/Inter-Italic.ttf diff --git a/staff/font/Inter-Regular.ttf b/static/font/Inter-Regular.ttf similarity index 100% rename from staff/font/Inter-Regular.ttf rename to static/font/Inter-Regular.ttf diff --git a/staff/font/Inter-SemiBold.ttf b/static/font/Inter-SemiBold.ttf similarity index 100% rename from staff/font/Inter-SemiBold.ttf rename to static/font/Inter-SemiBold.ttf diff --git a/staff/font/arial.ttf b/static/font/arial.ttf similarity index 100% rename from staff/font/arial.ttf rename to static/font/arial.ttf diff --git a/static/templates/blockchain.png b/static/templates/blockchain.png new file mode 100644 index 00000000..e69de29b diff --git a/staff/templates/cryptography.png b/static/templates/cryptography.png similarity index 100% rename from staff/templates/cryptography.png rename to static/templates/cryptography.png diff --git a/staff/templates/database.png b/static/templates/database.png similarity index 100% rename from staff/templates/database.png rename to static/templates/database.png diff --git a/staff/templates/databases.png b/static/templates/databases.png similarity index 100% rename from staff/templates/databases.png rename to static/templates/databases.png diff --git a/static/templates/defi.png b/static/templates/defi.png new file mode 100644 index 00000000..a802e43f Binary files /dev/null and b/static/templates/defi.png differ diff --git a/staff/templates/goland.png b/static/templates/goland.png similarity index 100% rename from staff/templates/goland.png rename to static/templates/goland.png diff --git a/staff/templates/golang.png b/static/templates/golang.png similarity index 100% rename from staff/templates/golang.png rename to static/templates/golang.png diff --git a/staff/templates/security.png b/static/templates/security.png similarity index 100% rename from staff/templates/security.png rename to static/templates/security.png diff --git a/staff/templates/solidity.png b/static/templates/solidity.png similarity index 100% rename from staff/templates/solidity.png rename to static/templates/solidity.png diff --git a/staff/templates/template.png b/static/templates/template.png similarity index 100% rename from staff/templates/template.png rename to static/templates/template.png diff --git a/static/templates/veterano.png b/static/templates/veterano.png new file mode 100644 index 00000000..48bf9a68 Binary files /dev/null and b/static/templates/veterano.png differ diff --git a/vendor/gopkg.in/gographics/imagick.v3/LICENSE b/vendor/gopkg.in/gographics/imagick.v3/LICENSE deleted file mode 100644 index 8f3fc551..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2013-2014, The GoGraphics Team -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of the organization nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 HERBERT G. FISCHER 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. - diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/affine_matrix.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/affine_matrix.go deleted file mode 100644 index 2eb1380d..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/affine_matrix.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -// AffineMatrix represents an ImageMagick AffineMatrix struct -type AffineMatrix struct { - am C.AffineMatrix -} - -// NewAffineMatrix constructs an AffineMatrix that is -// initialized to the indentify matrix -func NewAffineMatrix() *AffineMatrix { - am := &AffineMatrix{} - C.GetAffineMatrix(am.ptr()) - return am -} - -// ptr returns the underlying C AffineMatrix pointer -func (a *AffineMatrix) ptr() *C.AffineMatrix { - return &(a.am) -} - -// ResetToIdentity resets the AffineMatrix to the -// identity matrix -func (a *AffineMatrix) ResetToIdentity() { - C.GetAffineMatrix(a.ptr()) -} - -// TranslateX returns the TX value -func (a *AffineMatrix) TranslateX() float64 { - return float64(a.am.tx) -} - -// SetTranslateX sets the TX value -func (a *AffineMatrix) SetTranslateX(val float64) { - a.am.tx = C.double(val) -} - -// TranslateY returns the TY value -func (a *AffineMatrix) TranslateY() float64 { - return float64(a.am.ty) -} - -// SetTranslateY sets the TY value -func (a *AffineMatrix) SetTranslateY(val float64) { - a.am.ty = C.double(val) -} - -// RotateX returns the RX value -func (a *AffineMatrix) RotateX() float64 { - return float64(a.am.rx) -} - -// SetRotateX sets the RX value -func (a *AffineMatrix) SetRotateX(val float64) { - a.am.rx = C.double(val) -} - -// RotateY returns the RY value -func (a *AffineMatrix) RotateY() float64 { - return float64(a.am.ry) -} - -// SetRotateY sets the RY value -func (a *AffineMatrix) SetRotateY(val float64) { - a.am.ry = C.double(val) -} - -// ScaleX returns the SX value -func (a *AffineMatrix) ScaleX() float64 { - return float64(a.am.sx) -} - -// SetScaleX sets the SX value -func (a *AffineMatrix) SetScaleX(val float64) { - a.am.sx = C.double(val) -} - -// ScaleY returns the SY value -func (a *AffineMatrix) ScaleY() float64 { - return float64(a.am.sy) -} - -// SetScaleY sets the SY value -func (a *AffineMatrix) SetScaleY(val float64) { - a.am.sy = C.double(val) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/align_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/align_type.go deleted file mode 100644 index b40a8f11..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/align_type.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type AlignType int - -const ( - ALIGN_UNDEFINED AlignType = C.UndefinedAlign - ALIGN_LEFT AlignType = C.LeftAlign - ALIGN_CENTER AlignType = C.CenterAlign - ALIGN_RIGHT AlignType = C.RightAlign -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/alpha_channel_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/alpha_channel_type.go deleted file mode 100644 index a48746d0..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/alpha_channel_type.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type AlphaChannelType int - -const ( - ALPHA_CHANNEL_UNDEFINED AlphaChannelType = C.UndefinedAlphaChannel - ALPHA_CHANNEL_ACTIVATE AlphaChannelType = C.ActivateAlphaChannel - ALPHA_CHANNEL_ASSOCIATE AlphaChannelType = C.AssociateAlphaChannel - ALPHA_CHANNEL_BACKGROUND AlphaChannelType = C.BackgroundAlphaChannel - ALPHA_CHANNEL_COPY AlphaChannelType = C.CopyAlphaChannel - ALPHA_CHANNEL_DEACTIVATE AlphaChannelType = C.DeactivateAlphaChannel - ALPHA_CHANNEL_DISASSOCIATE AlphaChannelType = C.DisassociateAlphaChannel - ALPHA_CHANNEL_DISCRETE AlphaChannelType = C.DiscreteAlphaChannel - ALPHA_CHANNEL_EXTRACT AlphaChannelType = C.ExtractAlphaChannel - ALPHA_CHANNEL_OFF AlphaChannelType = C.OffAlphaChannel - ALPHA_CHANNEL_ON AlphaChannelType = C.OnAlphaChannel - ALPHA_CHANNEL_OPAQUE AlphaChannelType = C.OpaqueAlphaChannel - ALPHA_CHANNEL_REMOVE AlphaChannelType = C.RemoveAlphaChannel - ALPHA_CHANNEL_SET AlphaChannelType = C.SetAlphaChannel - ALPHA_CHANNEL_SHAPE AlphaChannelType = C.ShapeAlphaChannel - ALPHA_CHANNEL_TRANSPARENT AlphaChannelType = C.TransparentAlphaChannel -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_features.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_features.go deleted file mode 100644 index 72c7266d..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_features.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -//"fmt" -//"unsafe" - -type ChannelFeatures struct { - cf *C.ChannelFeatures -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_statistics.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_statistics.go deleted file mode 100644 index cb73e215..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_statistics.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -//"fmt" -//"unsafe" - -type ChannelStatistics struct { - cs *C.ChannelStatistics -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_type.go deleted file mode 100644 index 7a4606f5..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/channel_type.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ChannelType int - -const ( - CHANNEL_UNDEFINED ChannelType = C.UndefinedChannel - CHANNEL_RED ChannelType = C.RedChannel - CHANNEL_GRAY ChannelType = C.GrayChannel - CHANNEL_CYAN ChannelType = C.CyanChannel - CHANNEL_GREEN ChannelType = C.GreenChannel - CHANNEL_MAGENTA ChannelType = C.MagentaChannel - CHANNEL_BLUE ChannelType = C.BlueChannel - CHANNEL_YELLOW ChannelType = C.YellowChannel - CHANNEL_ALPHA ChannelType = C.AlphaChannel - CHANNEL_OPACITY ChannelType = C.OpacityChannel - CHANNEL_BLACK ChannelType = C.BlackChannel - CHANNEL_INDEX ChannelType = C.IndexChannel - CHANNEL_TRUE_ALPHA ChannelType = C.TrueAlphaChannel - CHANNELS_COMPOSITE ChannelType = C.CompositeChannels - CHANNELS_ALL ChannelType = C.AllChannels - CHANNELS_RGB ChannelType = C.RGBChannels - CHANNELS_GRAY ChannelType = C.GrayChannels - CHANNELS_SYNC ChannelType = C.SyncChannels - CHANNELS_DEFAULT ChannelType = C.DefaultChannels -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/clip_path_units.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/clip_path_units.go deleted file mode 100644 index f6d5d2e6..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/clip_path_units.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ClipPathUnits int - -const ( - CLIP_UNDEFINED_PATH ClipPathUnits = C.UndefinedPathUnits - CLIP_USER_SPACE ClipPathUnits = C.UserSpace - CLIP_USER_SPACE_ON_USE ClipPathUnits = C.UserSpaceOnUse - CLIP_OBJECT_BOUNDING_BOX ClipPathUnits = C.ObjectBoundingBox -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/colorspace_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/colorspace_type.go deleted file mode 100644 index 9a1c1cdf..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/colorspace_type.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ColorspaceType int - -const ( - COLORSPACE_UNDEFINED ColorspaceType = C.UndefinedColorspace - COLORSPACE_CMY ColorspaceType = C.CMYColorspace - COLORSPACE_CMYK ColorspaceType = C.CMYKColorspace - COLORSPACE_GRAY ColorspaceType = C.GRAYColorspace - COLORSPACE_HCL ColorspaceType = C.HCLColorspace - COLORSPACE_HCLP ColorspaceType = C.HCLpColorspace - COLORSPACE_HSB ColorspaceType = C.HSBColorspace - COLORSPACE_HSI ColorspaceType = C.HSIColorspace - COLORSPACE_HSL ColorspaceType = C.HSLColorspace - COLORSPACE_HSV ColorspaceType = C.HSVColorspace - COLORSPACE_HWB ColorspaceType = C.HWBColorspace - COLORSPACE_LAB ColorspaceType = C.LabColorspace - COLORSPACE_LCH ColorspaceType = C.LCHColorspace - COLORSPACE_LCHAB ColorspaceType = C.LCHabColorspace - COLORSPACE_LCHUV ColorspaceType = C.LCHuvColorspace - COLORSPACE_LMS ColorspaceType = C.LMSColorspace - COLORSPACE_LOG ColorspaceType = C.LogColorspace - COLORSPACE_LUV ColorspaceType = C.LuvColorspace - COLORSPACE_OHTA ColorspaceType = C.OHTAColorspace - COLORSPACE_REC601YCBCR ColorspaceType = C.Rec601YCbCrColorspace - COLORSPACE_REC709YCBCR ColorspaceType = C.Rec709YCbCrColorspace - COLORSPACE_RGB ColorspaceType = C.RGBColorspace - COLORSPACE_SCRGB ColorspaceType = C.scRGBColorspace - COLORSPACE_SRGB ColorspaceType = C.sRGBColorspace - COLORSPACE_TRANSPARENT ColorspaceType = C.TransparentColorspace - COLORSPACE_XYY ColorspaceType = C.xyYColorspace - COLORSPACE_XYZ ColorspaceType = C.XYZColorspace - COLORSPACE_YCBCR ColorspaceType = C.YCbCrColorspace - COLORSPACE_YCC ColorspaceType = C.YCCColorspace - COLORSPACE_YDDDR ColorspaceType = C.YDbDrColorspace - COLORSPACE_YIQ ColorspaceType = C.YIQColorspace - COLORSPACE_YPBPR ColorspaceType = C.YPbPrColorspace - COLORSPACE_YUV ColorspaceType = C.YUVColorspace -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/composite_operator.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/composite_operator.go deleted file mode 100644 index 4e2835b2..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/composite_operator.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type CompositeOperator int - -const ( - COMPOSITE_OP_UNDEFINED CompositeOperator = C.UndefinedCompositeOp - COMPOSITE_OP_ALPHA CompositeOperator = C.AlphaCompositeOp - COMPOSITE_OP_ATOP CompositeOperator = C.AtopCompositeOp - COMPOSITE_OP_BLEND CompositeOperator = C.BlendCompositeOp - COMPOSITE_OP_BLUR CompositeOperator = C.BlurCompositeOp - COMPOSITE_OP_BUMPMAP CompositeOperator = C.BumpmapCompositeOp - COMPOSITE_OP_CHANGE_MASK CompositeOperator = C.ChangeMaskCompositeOp - COMPOSITE_OP_CLEAR CompositeOperator = C.ClearCompositeOp - COMPOSITE_OP_COLOR_BURN CompositeOperator = C.ColorBurnCompositeOp - COMPOSITE_OP_COLOR_DODGE CompositeOperator = C.ColorDodgeCompositeOp - COMPOSITE_OP_COLORIZE CompositeOperator = C.ColorizeCompositeOp - COMPOSITE_OP_COPY CompositeOperator = C.CopyCompositeOp - COMPOSITE_OP_COPY_ALPHA CompositeOperator = C.CopyAlphaCompositeOp - COMPOSITE_OP_COPY_BLACK CompositeOperator = C.CopyBlackCompositeOp - COMPOSITE_OP_COPY_BLUE CompositeOperator = C.CopyBlueCompositeOp - COMPOSITE_OP_COPY_CYAN CompositeOperator = C.CopyCyanCompositeOp - COMPOSITE_OP_COPY_GREEN CompositeOperator = C.CopyGreenCompositeOp - COMPOSITE_OP_COPY_MAGENTA CompositeOperator = C.CopyMagentaCompositeOp - COMPOSITE_OP_COPY_RED CompositeOperator = C.CopyRedCompositeOp - COMPOSITE_OP_COPY_YELLOW CompositeOperator = C.CopyYellowCompositeOp - COMPOSITE_OP_DARKEN CompositeOperator = C.DarkenCompositeOp - COMPOSITE_OP_DARKEN_INTENSITY CompositeOperator = C.DarkenIntensityCompositeOp - COMPOSITE_OP_DIFFERENCE CompositeOperator = C.DifferenceCompositeOp - COMPOSITE_OP_DISPLACE CompositeOperator = C.DisplaceCompositeOp - COMPOSITE_OP_DISSOLVE CompositeOperator = C.DissolveCompositeOp - COMPOSITE_OP_DISTORT CompositeOperator = C.DistortCompositeOp - COMPOSITE_OP_DIVIDE__DST CompositeOperator = C.DivideDstCompositeOp - COMPOSITE_OP_DIVIDE_SRC CompositeOperator = C.DivideSrcCompositeOp - COMPOSITE_OP_DST CompositeOperator = C.DstCompositeOp - COMPOSITE_OP_DST_ATOP CompositeOperator = C.DstAtopCompositeOp - COMPOSITE_OP_DST_IN CompositeOperator = C.DstInCompositeOp - COMPOSITE_OP_DST_OUT CompositeOperator = C.DstOutCompositeOp - COMPOSITE_OP_DST_OVER CompositeOperator = C.DstOverCompositeOp - COMPOSITE_OP_EXCLUSION CompositeOperator = C.ExclusionCompositeOp - COMPOSITE_OP_HARD_LIGHT CompositeOperator = C.HardLightCompositeOp - COMPOSITE_OP_HARD_MIX CompositeOperator = C.HardMixCompositeOp - COMPOSITE_OP_HUE CompositeOperator = C.HueCompositeOp - COMPOSITE_OP_IN CompositeOperator = C.InCompositeOp - COMPOSITE_OP_INTENSITY CompositeOperator = C.IntensityCompositeOp - COMPOSITE_OP_LIGHTEN CompositeOperator = C.LightenCompositeOp - COMPOSITE_OP_LIGHTEN_INTENSITY CompositeOperator = C.LightenIntensityCompositeOp - COMPOSITE_OP_LINEAR_BURN CompositeOperator = C.LinearBurnCompositeOp - COMPOSITE_OP_LINEAR_DODGE CompositeOperator = C.LinearDodgeCompositeOp - COMPOSITE_OP_LINEAR_LIGHT CompositeOperator = C.LinearLightCompositeOp - COMPOSITE_OP_LUMINIZE CompositeOperator = C.LuminizeCompositeOp - COMPOSITE_OP_MATHEMATICS CompositeOperator = C.MathematicsCompositeOp - COMPOSITE_OP_MINUS_DST CompositeOperator = C.MinusDstCompositeOp - COMPOSITE_OP_MINUS_SRC CompositeOperator = C.MinusSrcCompositeOp - COMPOSITE_OP_MODULATE CompositeOperator = C.ModulateCompositeOp - COMPOSITE_OP_MODULUS_ADD CompositeOperator = C.ModulusAddCompositeOp - COMPOSITE_OP_MODULUS_SUBTRACT CompositeOperator = C.ModulusSubtractCompositeOp - COMPOSITE_OP_MULTIPLY CompositeOperator = C.MultiplyCompositeOp - COMPOSITE_OP_NO CompositeOperator = C.NoCompositeOp - COMPOSITE_OP_OUT CompositeOperator = C.OutCompositeOp - COMPOSITE_OP_OVER CompositeOperator = C.OverCompositeOp - COMPOSITE_OP_OVERLAY CompositeOperator = C.OverlayCompositeOp - COMPOSITE_OP_PEGTOP_LIGHT CompositeOperator = C.PegtopLightCompositeOp - COMPOSITE_OP_PIN_LIGHT CompositeOperator = C.PinLightCompositeOp - COMPOSITE_OP_PLUS CompositeOperator = C.PlusCompositeOp - COMPOSITE_OP_REPLACE CompositeOperator = C.ReplaceCompositeOp - COMPOSITE_OP_SATURATE CompositeOperator = C.SaturateCompositeOp - COMPOSITE_OP_SCREEN CompositeOperator = C.ScreenCompositeOp - COMPOSITE_OP_SOFT_LIGHT CompositeOperator = C.SoftLightCompositeOp - COMPOSITE_OP_SRC CompositeOperator = C.SrcCompositeOp - COMPOSITE_OP_SRC_ATOP CompositeOperator = C.SrcAtopCompositeOp - COMPOSITE_OP_SRC_IN CompositeOperator = C.SrcInCompositeOp - COMPOSITE_OP_SRC_OUT CompositeOperator = C.SrcOutCompositeOp - COMPOSITE_OP_SRC_OVER CompositeOperator = C.SrcOverCompositeOp - COMPOSITE_OP_THRESHOLD CompositeOperator = C.ThresholdCompositeOp - COMPOSITE_OP_VIVID_LIGHT CompositeOperator = C.VividLightCompositeOp - COMPOSITE_OP_XOR CompositeOperator = C.XorCompositeOp -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/compression_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/compression_type.go deleted file mode 100644 index 3b9914ec..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/compression_type.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type CompressionType int - -const ( - COMPRESSION_UNDEFINED CompressionType = C.UndefinedCompression - COMPRESSION_NO CompressionType = C.NoCompression - COMPRESSION_BZIP CompressionType = C.BZipCompression - COMPRESSION_DXT1 CompressionType = C.DXT1Compression - COMPRESSION_DXT3 CompressionType = C.DXT3Compression - COMPRESSION_DXT5 CompressionType = C.DXT5Compression - COMPRESSION_FAX CompressionType = C.FaxCompression - COMPRESSION_GROUP4 CompressionType = C.Group4Compression - COMPRESSION_JPEG CompressionType = C.JPEGCompression - COMPRESSION_JPEG2000 CompressionType = C.JPEG2000Compression - COMPRESSION_LOSSLESS_JPEG CompressionType = C.LosslessJPEGCompression - COMPRESSION_LZW CompressionType = C.LZWCompression - COMPRESSION_RLE CompressionType = C.RLECompression - COMPRESSION_ZIP CompressionType = C.ZipCompression - COMPRESSION_ZIPS CompressionType = C.ZipSCompression - COMPRESSION_PIZ CompressionType = C.PizCompression - COMPRESSION_PXR24 CompressionType = C.Pxr24Compression - COMPRESSION_B44 CompressionType = C.B44Compression - COMPRESSION_B44A CompressionType = C.B44ACompression - COMPRESSION_LZMA CompressionType = C.LZMACompression - COMPRESSION_JBIG1 CompressionType = C.JBIG1Compression - COMPRESSION_JBIG2 CompressionType = C.JBIG2Compression -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/conversions.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/conversions.go deleted file mode 100644 index 347d1024..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/conversions.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import "unsafe" - -// Convert a boolean to a integer -func b2i(boolean bool) C.MagickBooleanType { - if boolean { - return C.MagickBooleanType(1) - } - return C.MagickBooleanType(0) -} - -func cStringArrayToStringSlice(p **C.char) []string { - var strings []string - q := uintptr(unsafe.Pointer(p)) - for { - p = (**C.char)(unsafe.Pointer(q)) - if *p == nil { - break - } - strings = append(strings, C.GoString(*p)) - q += unsafe.Sizeof(q) - } - return strings -} - -func sizedCStringArrayToStringSlice(p **C.char, num C.size_t) []string { - var strings []string - q := uintptr(unsafe.Pointer(p)) - for i := 0; i < int(num); i++ { - p = (**C.char)(unsafe.Pointer(q)) - if *p == nil { - break - } - strings = append(strings, C.GoString(*p)) - q += unsafe.Sizeof(q) - } - return strings -} - -func sizedDoubleArrayToFloat64Slice(p *C.double, num C.size_t) []float64 { - var nums []float64 - q := uintptr(unsafe.Pointer(p)) - for i := 0; i < int(num); i++ { - p = (*C.double)(unsafe.Pointer(q)) - nums = append(nums, float64(*p)) - q += unsafe.Sizeof(q) - } - return nums -} - -func ConvertRGBToHSL(qr, qg, qb float64) (h, s, l float64) { - var dh, ds, dl C.double - C.ConvertRGBToHSL(C.double(qr), C.double(qg), C.double(qb), &dh, &ds, &dl) - return float64(dh), float64(ds), float64(dl) -} - -func ConvertHSLToRGB(fh, fs, fl float64) (r, g, b float64) { - var qr, qg, qb C.double - C.ConvertHSLToRGB(C.double(fh), C.double(fs), C.double(fl), &qr, &qg, &qb) - return float64(qr), float64(qg), float64(qb) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/decoration_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/decoration_type.go deleted file mode 100644 index 7976f4f6..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/decoration_type.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type DecorationType int - -const ( - DECORATION_UNDEFINED DecorationType = C.UndefinedDecoration - DECORATION_NONE DecorationType = C.NoDecoration - DECORATION_UNDERLINE DecorationType = C.UnderlineDecoration - DECORATION_OVERLINE DecorationType = C.OverlineDecoration - DECORATION_LINE_THROUGH DecorationType = C.LineThroughDecoration -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/destroy.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/destroy.go deleted file mode 100644 index ed88d149..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/destroy.go +++ /dev/null @@ -1,9 +0,0 @@ -package imagick - -import "gopkg.in/gographics/imagick.v3/imagick/types" - -// Destroy instance of Destroyer -// If GOGC=off you should call obj.Destroy() manually -func Destroy(d types.Destroyer) { - d.Destroy() -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/dispose_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/dispose_type.go deleted file mode 100644 index 4393b6b1..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/dispose_type.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type DisposeType int - -const ( - DISPOSE_UNRECOGNIZED DisposeType = C.UnrecognizedDispose - DISPOSE_UNDEFINED DisposeType = C.UndefinedDispose - DISPOSE_NONE DisposeType = C.NoneDispose - DISPOSE_BACKGROUND DisposeType = C.BackgroundDispose - DISPOSE_PREVIOUS DisposeType = C.PreviousDispose -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/distort_image_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/distort_image_method.go deleted file mode 100644 index 6a6fa43e..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/distort_image_method.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type DistortImageMethod int - -const ( - DISTORTION_UNDEFINED DistortImageMethod = C.UndefinedDistortion - DISTORTION_AFFINE DistortImageMethod = C.AffineDistortion - DISTORTION_AFFINE_PROJECTION DistortImageMethod = C.AffineProjectionDistortion - DISTORTION_ARC DistortImageMethod = C.ArcDistortion - DISTORTION_BARREL DistortImageMethod = C.BarrelDistortion - DISTORTION_BARREL_INVERSE DistortImageMethod = C.BarrelInverseDistortion - DISTORTION_BILINEAR DistortImageMethod = C.BilinearDistortion - DISTORTION_BILINEAR_FORWARD DistortImageMethod = C.BilinearForwardDistortion - DISTORTION_BILINEAR_REVERSE DistortImageMethod = C.BilinearReverseDistortion - DISTORTION_CYLINDER_2_PLANE DistortImageMethod = C.Cylinder2PlaneDistortion - DISTORTION_DE_POLAR DistortImageMethod = C.DePolarDistortion - DISTORTION_PERSPECTIVE DistortImageMethod = C.PerspectiveDistortion - DISTORTION_PERSPECTIVE_PROJECTION DistortImageMethod = C.PerspectiveProjectionDistortion - DISTORTION_PLANE_2_CYLINDER DistortImageMethod = C.Plane2CylinderDistortion - DISTORTION_POLAR DistortImageMethod = C.PolarDistortion - DISTORTION_POLYNOMIAL DistortImageMethod = C.PolynomialDistortion - DISTORTION_RESIZE DistortImageMethod = C.ResizeDistortion - DISTORTION_SCALE_ROTATE_TRANSLATE DistortImageMethod = C.ScaleRotateTranslateDistortion - DISTORTION_SENTINEL DistortImageMethod = C.SentinelDistortion - DISTORTION_SHEPARDS DistortImageMethod = C.ShepardsDistortion -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/dither_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/dither_method.go deleted file mode 100644 index 4af975fe..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/dither_method.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type DitherMethod int - -const ( - DITHER_METHOD_UNDEFINED DitherMethod = C.UndefinedDitherMethod - DITHER_METHOD_NO DitherMethod = C.NoDitherMethod - DITHER_METHOD_RIEMERSMA DitherMethod = C.RiemersmaDitherMethod - DITHER_METHOD_FLOYD_STEINBERG DitherMethod = C.FloydSteinbergDitherMethod -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/draw_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/draw_info.go deleted file mode 100644 index 2519e289..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/draw_info.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type DrawInfo struct { - di *C.DrawInfo -} - -func NewDrawInfo() *DrawInfo { - return &DrawInfo{C.AcquireDrawInfo()} -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand.go deleted file mode 100644 index c7f27528..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand.go +++ /dev/null @@ -1,1264 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import ( - "runtime" - "sync" - "sync/atomic" - "unsafe" -) - -type DrawingWand struct { - dw *C.DrawingWand - init sync.Once -} - -func newDrawingWand(cdw *C.DrawingWand) *DrawingWand { - dw := &DrawingWand{dw: cdw} - runtime.SetFinalizer(dw, Destroy) - dw.IncreaseCount() - - return dw -} - -// Returns a drawing wand required for all other methods in the API. -func NewDrawingWand() *DrawingWand { - return newDrawingWand(C.NewDrawingWand()) -} - -// Clears resources associated with the drawing wand. -func (dw *DrawingWand) Clear() { - C.ClearDrawingWand(dw.dw) - runtime.KeepAlive(dw) -} - -// Makes an exact copy of the specified wand. -func (dw *DrawingWand) Clone() *DrawingWand { - ret := newDrawingWand(C.CloneDrawingWand(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Frees all resources associated with the drawing wand. Once the drawing wand -// has been freed, it should not be used and further unless it re-allocated. -func (dw *DrawingWand) Destroy() { - if dw.dw == nil { - return - } - - dw.init.Do(func() { - dw.dw = C.DestroyDrawingWand(dw.dw) - relinquishMemory(unsafe.Pointer(dw.dw)) - runtime.SetFinalizer(dw, nil) - dw.dw = nil - - dw.DecreaseCount() - }) -} - -// Increase DrawingWand ref counter and set according "can`t be terminated status" -func (dw *DrawingWand) IncreaseCount() { - atomic.AddInt64(&drawingWandCounter, int64(1)) - unsetCanTerminate() -} - -// Decrease DrawingWand ref counter and set according "can be terminated status" -func (dw *DrawingWand) DecreaseCount() { - atomic.AddInt64(&drawingWandCounter, int64(-1)) - setCanTerminate() -} - -// Adjusts the current affine transformation matrix with the specified affine -// transformation matrix. Note that the current affine transform is adjusted -// rather than replaced. -// -// affine: Affine matrix parameters -func (dw *DrawingWand) Affine(affine *AffineMatrix) { - C.DrawAffine(dw.dw, affine.ptr()) - runtime.KeepAlive(dw) -} - -// Draws text on the image. -// x: x ordinate to left of text -// y: y ordinate to text baseline -// text: text to draw -func (dw *DrawingWand) Annotation(x, y float64, text string) { - cstext := (*C.uchar)((unsafe.Pointer)(C.CString(text))) - defer C.free(unsafe.Pointer(cstext)) - C.DrawAnnotation(dw.dw, C.double(x), C.double(y), cstext) - runtime.KeepAlive(dw) -} - -// Draws an arc falling within a specified bounding rectangle on the image. -// -// sx: starting x ordinate of bounding rectangle -// -// sy: starting y ordinate of bounding rectangle -// -// ex: ending x ordinate of bounding rectangle -// -// ey: ending y ordinate of bounding rectangle -// -// sd: starting degrees of rotation -// -// ed: ending degrees of rotation -func (dw *DrawingWand) Arc(sx, sy, ex, ey, sd, ed float64) { - C.DrawArc(dw.dw, C.double(sx), C.double(sy), C.double(ex), C.double(ey), C.double(sd), C.double(ed)) - runtime.KeepAlive(dw) -} - -// Draws a bezier curve through a set of points on the image. -func (dw *DrawingWand) Bezier(coordinates []PointInfo) { - ccoordinates := [1 << 16]C.PointInfo{} - for k, v := range coordinates { - ccoordinates[k] = C.PointInfo{C.double(v.X), C.double(v.Y)} - } - C.DrawBezier(dw.dw, C.size_t(len(coordinates)), (*C.PointInfo)(&ccoordinates[0])) - runtime.KeepAlive(dw) -} - -// Draws a circle on the image. -// -// ox: origin x ordinate -// -// oy: origin y ordinate -// -// px: perimeter x ordinate -// -// py: perimeter y ordinate -func (dw *DrawingWand) Circle(ox, oy, px, py float64) { - C.DrawCircle(dw.dw, C.double(ox), C.double(oy), C.double(px), C.double(py)) - runtime.KeepAlive(dw) -} - -// Composites an image onto the current image, using the specified composition -// operator, specified position, and at the specified size. -// -// compose: composition operator -// -// x: x ordinate of top left corner -// -// y: y ordinate of top left corner -// -// width: Width to resize image to prior to compositing. Specify zero to use -// existing width. -// -// height: Height to resize image to prior to compositing. Specify zero to use -// existing height. -// -// mw: Image to composite is obtained from this wand. -func (dw *DrawingWand) Composite(compose CompositeOperator, x, y, width, height float64, mw *MagickWand) error { - ok := C.DrawComposite(dw.dw, C.CompositeOperator(compose), C.double(x), C.double(y), C.double(width), C.double(height), mw.mw) - return dw.getLastErrorIfFailed(ok) -} - -// Draws color on image using the current fill color, starting at specified -// position, and using specified paint method. The available paint methods are: -// -// x: x ordinate. -// -// y: y ordinate. -// -// pm: paint method. PointMethod: Recolors the target pixel. ReplaceMethod: -// Recolor any pixel that matches the target pixel. FloodfillMethod: Recolors -// target pixels and matching neighbors. ResetMethod: Recolor all pixels. -func (dw *DrawingWand) Color(x, y float64, pm PaintMethod) { - C.DrawColor(dw.dw, C.double(x), C.double(y), C.PaintMethod(pm)) - runtime.KeepAlive(dw) -} - -// Adds a comment to a vector output stream. -func (dw *DrawingWand) Comment(comment string) { - cscomment := C.CString(comment) - defer C.free(unsafe.Pointer(cscomment)) - C.DrawComment(dw.dw, cscomment) - runtime.KeepAlive(dw) -} - -// Draws an ellipse on the image. -// -// ox: origin x ordinate -// -// oy: origin y ordinate -// -// rx: radius in x -// -// ry: radius in y -// -// start: starting rotation in degrees -// -// end: ending rotation in degrees -func (dw *DrawingWand) Ellipse(ox, oy, rx, ry, start, end float64) { - C.DrawEllipse(dw.dw, C.double(ox), C.double(oy), C.double(rx), C.double(ry), C.double(start), C.double(end)) - runtime.KeepAlive(dw) -} - -// Returns the border color used for drawing bordered objects. -func (dw *DrawingWand) GetBorderColor() (pw *PixelWand) { - pw = NewPixelWand() - C.DrawGetBorderColor(dw.dw, pw.pw) - runtime.KeepAlive(dw) - return -} - -// Obtains the current clipping path ID. -func (dw *DrawingWand) GetClipPath() string { - cscp := C.DrawGetClipPath(dw.dw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(cscp)) - return C.GoString(cscp) -} - -// Returns the current polygon fill rule to be used by the clipping path. -func (dw *DrawingWand) GetClipRule() FillRule { - ret := FillRule(C.DrawGetClipRule(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the interpretation of clip path units. -func (dw *DrawingWand) GetClipUnits() ClipPathUnits { - ret := ClipPathUnits(C.DrawGetClipUnits(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the fill color used for drawing filled objects. -func (dw *DrawingWand) GetFillColor() (pw *PixelWand) { - pw = NewPixelWand() - C.DrawGetFillColor(dw.dw, pw.pw) - runtime.KeepAlive(dw) - return -} - -// Returns the opacity used when drawing using the fill color or fill texture. -// Fully opaque is 1.0. -func (dw *DrawingWand) GetFillOpacity() float64 { - ret := float64(C.DrawGetFillOpacity(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the fill rule used while drawing polygons. -func (dw *DrawingWand) GetFillRule() FillRule { - ret := FillRule(C.DrawGetFillRule(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns a string specifying the font used when annotating with text. -func (dw *DrawingWand) GetFont() string { - csfont := C.DrawGetFont(dw.dw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(csfont)) - return C.GoString(csfont) -} - -// Returns the font family to use when annotating with text. -func (dw *DrawingWand) GetFontFamily() string { - csfamily := C.DrawGetFontFamily(dw.dw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(csfamily)) - return C.GoString(csfamily) -} - -// Gets the image X and Y resolution. -func (dw *DrawingWand) GetFontResolution() (x, y float64, err error) { - ok := C.DrawGetFontResolution(dw.dw, (*C.double)(&x), (*C.double)(&y)) - err = dw.getLastErrorIfFailed(ok) - return -} - -// Returns the font stretch used when annotating with text. -func (dw *DrawingWand) GetFontStretch() StretchType { - ret := StretchType(C.DrawGetFontStretch(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the font style used when annotating with text. -func (dw *DrawingWand) GetFontStyle() StyleType { - ret := StyleType(C.DrawGetFontStyle(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the font weight used when annotating with text. -func (dw *DrawingWand) GetFontWeight() uint { - ret := uint(C.DrawGetFontWeight(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the text placement gravity used when annotating with text. -func (dw *DrawingWand) GetGravity() GravityType { - ret := GravityType(C.DrawGetGravity(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the opacity used when drawing with the fill or stroke color or -// texture. Fully opaque is 1.0. -func (dw *DrawingWand) GetOpacity() float64 { - ret := float64(C.DrawGetOpacity(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the current stroke antialias setting. Stroked outlines are -// antialiased by default. When antialiasing is disabled stroked pixels are -// thresholded to determine if the stroke color or underlying canvas color -// should be used. -func (dw *DrawingWand) GetStrokeAntialias() bool { - ret := 1 == C.DrawGetStrokeAntialias(dw.dw) - runtime.KeepAlive(dw) - return ret -} - -// Returns the color used for stroking object outlines. -func (dw *DrawingWand) GetStrokeColor() (pw *PixelWand) { - pw = NewPixelWand() - C.DrawGetStrokeColor(dw.dw, pw.pw) - runtime.KeepAlive(dw) - return -} - -// Returns an array representing the pattern of dashes and gaps used to stroke -// paths (see SetStrokeDashArray). The array must be freed once it is no longer -// required by the user. -func (dw *DrawingWand) GetStrokeDashArray() (nums []float64) { - count := C.size_t(0) - p := C.DrawGetStrokeDashArray(dw.dw, &count) - runtime.KeepAlive(dw) - nums = sizedDoubleArrayToFloat64Slice(p, count) - return -} - -// Returns the offset into the dash pattern to start the dash. -func (dw *DrawingWand) GetStrokeDashOffset() float64 { - ret := float64(C.DrawGetStrokeDashOffset(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the shape to be used at the end of open subpaths when they are -// stroked. Values of LineCap are UndefinedCap, ButtCap, RoundCap, and -// SquareCap. -func (dw *DrawingWand) GetStrokeLineCap() LineCap { - ret := LineCap(C.DrawGetStrokeLineCap(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the shape to be used at the corners of paths (or other vector -// shapes) when they are stroked. Values of LineJoin are UndefinedJoin, -// MiterJoin, RoundJoin, and BevelJoin. -func (dw *DrawingWand) GetStrokeLineJoin() LineJoin { - ret := LineJoin(C.DrawGetStrokeLineJoin(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the miter limit. When two line segments meet at a sharp angle and -// miter joins have been specified for 'lineJoin', it is possible for the -// miter to extend far beyond the thickness of the line stroking the path. -// The miterLimit' imposes a limit on the ratio of the miter length to the -// 'lineWidth'. -func (dw *DrawingWand) GetStrokeMiterLimit() uint { - ret := uint(C.DrawGetStrokeMiterLimit(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the opacity of stroked object outlines. -func (dw *DrawingWand) GetStrokeOpacity() float64 { - ret := float64(C.DrawGetStrokeOpacity(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the width of the stroke used to draw object outlines. -func (dw *DrawingWand) GetStrokeWidth() float64 { - ret := float64(C.DrawGetStrokeWidth(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the alignment applied when annotating with text. -func (dw *DrawingWand) GetTextAlignment() AlignType { - ret := AlignType(C.DrawGetTextAlignment(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the current text antialias setting, which determines whether text -// is antialiased. Text is antialiased by default. -func (dw *DrawingWand) GetTextAntialias() bool { - ret := 1 == C.DrawGetTextAntialias(dw.dw) - runtime.KeepAlive(dw) - return ret -} - -// Returns the decoration applied when annotating with text. -func (dw *DrawingWand) GetTextDecoration() DecorationType { - ret := DecorationType(C.DrawGetTextDecoration(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns a string which specifies the code set used for text annotations. -func (dw *DrawingWand) GetTextEncoding() string { - cstr := C.DrawGetTextEncoding(dw.dw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Gets the spacing between characters in text. -func (dw *DrawingWand) GetTextKerning() float64 { - ret := float64(C.DrawGetTextKerning(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Gets the spacing between lines in text. -func (dw *DrawingWand) GetTextInterlineSpacing() float64 { - ret := float64(C.DrawGetTextInterlineSpacing(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Gets the spacing between words in text. -func (dw *DrawingWand) GetTextInterwordSpacing() float64 { - ret := float64(C.DrawGetTextInterwordSpacing(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns a string which specifies the vector graphics generated by any -// graphics calls made since the wand was instantiated. -func (dw *DrawingWand) GetVectorGraphics() string { - cstr := C.DrawGetVectorGraphics(dw.dw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Returns the color of a background rectangle to place under text annotations. -func (dw *DrawingWand) GetTextUnderColor() (pw *PixelWand) { - pw = NewPixelWand() - C.DrawGetTextUnderColor(dw.dw, pw.pw) - runtime.KeepAlive(dw) - return -} - -// Draws a line on the image using the current stroke color, stroke opacity, -// and stroke width. -// -// sx: starting x ordinate -// -// sy: starting y ordinate -// -// ex: ending x ordinate -// -// ey: ending y ordinate -func (dw *DrawingWand) Line(sx, sy, ex, ey float64) { - C.DrawLine(dw.dw, C.double(sx), C.double(sy), C.double(ex), C.double(ey)) - runtime.KeepAlive(dw) -} - -// Deprecated in ImageMagick-7.x -// Use Alpha() -func (dw *DrawingWand) Matte(x, y float64, pmethod PaintMethod) { - C.DrawAlpha(dw.dw, C.double(x), C.double(y), C.PaintMethod(pmethod)) - runtime.KeepAlive(dw) -} - -// Paints on the image's opacity channel in order to set effected pixels to -// transparent. to influence the opacity of pixels. The available paint -// methods are: -// -// ResetMethod: Select all pixels. -// -// PointMethod: Select the target pixel -// -// ReplaceMethod: Select any pixel that matches the target pixel. -// -// FloodfillMethod: Select the target pixel and matching neighbors. -// -// FillToBorderMethod: Select the target pixel and neighbors not matching -// border color. -// -// x, y: x, y ordinates -// pmethod: paint method -func (dw *DrawingWand) Alpha(x, y float64, pmethod PaintMethod) { - C.DrawAlpha(dw.dw, C.double(x), C.double(y), C.PaintMethod(pmethod)) - runtime.KeepAlive(dw) -} - -// Adds a path element to the current path which closes the current subpath by -// drawing a straight line from the current point to the current subpath's most -// recent starting point (usually, the most recent moveto point). -func (dw *DrawingWand) PathClose() { - C.DrawPathClose(dw.dw) - runtime.KeepAlive(dw) -} - -// Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as -// the control point at the beginning of the curve and (x2,y2) as the control -// point at the end of the curve using absolute coordinates. At the end of the -// command, the new current point becomes the final (x,y) coordinate pair used -// in the polybezier. -// -// x1, y1: x, y ordinates of control point for curve beginning -// -// x2, y2: x, y ordinates of control point for curve ending -// -// x, y: x, y ordinates of the end of the curve -func (dw *DrawingWand) PathCurveToAbsolute(x1, y1, x2, y2, x, y float64) { - C.DrawPathCurveToAbsolute(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as -// the control point at the beginning of the curve and (x2,y2) as the control -// point at the end of the curve using relative coordinates. At the end of the -// command, the new current point becomes the final (x,y) coordinate pair used -// in the polybezier. -// -// x1, y1: x, y ordinates of control point for curve beginning -// -// x2, y2: x, y ordinates of control point for curve ending -// -// x, y: x, y ordinates of the end of the curve -func (dw *DrawingWand) PathCurveToRelative(x1, y1, x2, y2, x, y float64) { - C.DrawPathCurveToRelative(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) -// as the control point using absolute coordinates. At the end of the command, -// the new current point becomes the final (x,y) coordinate pair used in the -// polybezier. -// -// x1, y1: ordinates of the control point -// -// x, y: ordinates of final point -func (dw *DrawingWand) PathCurveToQuadraticBezierAbsolute(x1, y1, x, y float64) { - C.DrawPathCurveToQuadraticBezierAbsolute(dw.dw, C.double(x1), C.double(y1), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) -// as the control point using relative coordinates. At the end of the command, -// the new current point becomes the final (x,y) coordinate pair used in the -// polybezier. -// x1, y1: ordinates of the control point -// x, y: ordinates of final point -func (dw *DrawingWand) PathCurveToQuadraticBezierRelative(x1, y1, x, y float64) { - C.DrawPathCurveToQuadraticBezierRelative(dw.dw, C.double(x1), C.double(y1), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a quadratic Bezier curve (using absolute coordinates) from the current -// point to (x,y). The control point is assumed to be the reflection of the -// control point on the previous command relative to the current point. (If -// there is no previous command or if the previous command was not a -// PathCurveToQuadraticBezierAbsolute, PathCurveToQuadraticBezierRelative, -// PathCurveToQuadraticBezierSmoothAbsolute or -// PathCurveToQuadraticBezierSmoothRelative, assume the control point is -// coincident with the current point.). At the end of the command, the new -// current point becomes the final (x,y) coordinate pair used in the polybezier. -// -// x, y: ordinates of final point -func (dw *DrawingWand) PathCurveToQuadraticBezierSmoothAbsolute(x, y float64) { - C.DrawPathCurveToQuadraticBezierSmoothAbsolute(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a quadratic Bezier curve (using relative coordinates) from the current -// point to (x,y). The control point is assumed to be the reflection of the -// control point on the previous command relative to the current point. (If -// there is no previous command or if the previous command was not a -// PathCurveToQuadraticBezierAbsolute, PathCurveToQuadraticBezierRelative, -// PathCurveToQuadraticBezierSmoothAbsolute or -// PathCurveToQuadraticBezierSmoothRelative, assume the control point is -// coincident with the current point.). At the end of the command, the new -// current point becomes the final (x,y) coordinate pair used in the polybezier. -// -// x, y: ordinates of final point -func (dw *DrawingWand) PathCurveToQuadraticBezierSmoothRelative(x, y float64) { - C.DrawPathCurveToQuadraticBezierSmoothRelative(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a cubic Bezier curve from the current point to (x,y) using absolute -// coordinates. The first control point is assumed to be the reflection of the -// second control point on the previous command relative to the current point. -// (If there is no previous command or if the previous command was not an -// PathCurveToAbsolute, PathCurveToRelative, PathCurveToSmoothAbsolute or -// PathCurveToSmoothRelative, assume the first control point is coincident -// with the current point.) (x2,y2) is the second control point (i.e., the -// control point at the end of the curve). At the end of the command, the new -// current point becomes the final (x,y) coordinate pair used in the polybezier. -// -// x2, y2: ordinates of second control point -// -// x, y: ordinates of termination point -func (dw *DrawingWand) PathCurveToSmoothAbsolute(x2, y2, x, y float64) { - C.DrawPathCurveToSmoothAbsolute(dw.dw, C.double(x2), C.double(y2), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a cubic Bezier curve from the current point to (x,y) using relative -// coordinates. The first control point is assumed to be the reflection of the -// second control point on the previous command relative to the current point. -// (If there is no previous command or if the previous command was not an -// PathCurveToAbsolute, PathCurveToRelative, PathCurveToSmoothAbsolute or -// PathCurveToSmoothRelative, assume the first control point is coincident -// with the current point.) (x2,y2) is the second control point (i.e., the -// control point at the end of the curve). At the end of the command, the new -// current point becomes the final (x,y) coordinate pair used in the polybezier. -// -// x2, y2: ordinates of second control point -// -// x, y: ordinates of termination point -func (dw *DrawingWand) PathCurveToSmoothRelative(x2, y2, x, y float64) { - C.DrawPathCurveToSmoothRelative(dw.dw, C.double(x2), C.double(y2), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws an elliptical arc from the current point to (x, y) using absolute -// coordinates. The size and orientation of the ellipse are defined by two -// radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a -// whole is rotated relative to the current coordinate system. The center (cx, -// cy) of the ellipse is calculated automagically to satisfy the constraints -// imposed by the other parameters. largeArcFlag and sweepFlag contribute to -// the automatic calculations and help determine how the arc is drawn. If -// largeArcFlag is true then draw the larger of the available arcs. If -// sweepFlag is true, then draw the arc matching a clock-wise rotation. -// -// rx, ry: x, y radius -// -// xAxisRotation: indicates how the ellipse as a whole is rotated relative to -// the current coordinate system -// -// largeArcFlag: If true then draw the larger of the available arcs -// -// sweepFlag: If true then draw the arc matching a clock-wise rotation -func (dw *DrawingWand) PathEllipticArcAbsolute(rx, ry, xAxisRotation float64, largeArcFlag, sweepFlag bool, x, y float64) { - C.DrawPathEllipticArcAbsolute(dw.dw, C.double(rx), C.double(ry), C.double(xAxisRotation), b2i(largeArcFlag), b2i(sweepFlag), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws an elliptical arc from the current point to (x, y) using relative -// coordinates. The size and orientation of the ellipse are defined by two -// radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a -// whole is rotated relative to the current coordinate system. The center (cx, -// cy) of the ellipse is calculated automagically to satisfy the constraints -// imposed by the other parameters. largeArcFlag and sweepFlag contribute to -// the automatic calculations and help determine how the arc is drawn. If -// largeArcFlag is true then draw the larger of the available arcs. If -// sweepFlag is true, then draw the arc matching a clock-wise rotation. -// -// rx, ry: x, y radius -// -// xAxisRotation: indicates how the ellipse as a whole is rotated relative to -// the current coordinate system -// -// largeArcFlag: If true then draw the larger of the available arcs -// -// sweepFlag: If true then draw the arc matching a clock-wise rotation -func (dw *DrawingWand) PathEllipticArcRelative(rx, ry, xAxisRotation float64, largeArcFlag, sweepFlag bool, x, y float64) { - C.DrawPathEllipticArcRelative(dw.dw, C.double(rx), C.double(ry), C.double(xAxisRotation), b2i(largeArcFlag), b2i(sweepFlag), C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Terminates the current path. -func (dw *DrawingWand) PathFinish() { - C.DrawPathFinish(dw.dw) - runtime.KeepAlive(dw) -} - -// Draws a line path from the current point to the given coordinate using -// absolute coordinates. The coordinate then becomes the new current point. -// -// x, y: target x and y ordinates -func (dw *DrawingWand) PathLineToAbsolute(x, y float64) { - C.DrawPathLineToAbsolute(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a line path from the current point to the given coordinate using -// relative coordinates. The coordinate then becomes the new current point. -// -// x, y: target x and y ordinates -func (dw *DrawingWand) PathLineToRelative(x, y float64) { - C.DrawPathLineToRelative(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a horizontal line path from the current point to the target point -// using absolute coordinates. The target point then becomes the new current -// point. -// -// x: target x ordinate -func (dw *DrawingWand) PathLineToHorizontalAbsolute(x float64) { - C.DrawPathLineToHorizontalAbsolute(dw.dw, C.double(x)) - runtime.KeepAlive(dw) -} - -// Draws a horizontal line path from the current point to the target point -// using relative coordinates. The target point then becomes the new current -// point. -// -// x: target x ordinate -func (dw *DrawingWand) PathLineToHorizontalRelative(x float64) { - C.DrawPathLineToHorizontalRelative(dw.dw, C.double(x)) - runtime.KeepAlive(dw) -} - -// Draws a vertical line path from the current point to the target point using -// absolute coordinates. The target point then becomes the new current point. -// -// y: target y ordinate -func (dw *DrawingWand) PathLineToVerticalAbsolute(y float64) { - C.DrawPathLineToVerticalAbsolute(dw.dw, C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a vertical line path from the current point to the target point using -// relative coordinates. The target point then becomes the new current point. -// -// y: target y ordinate -func (dw *DrawingWand) PathLineToVerticalRelative(y float64) { - C.DrawPathLineToVerticalRelative(dw.dw, C.double(y)) - runtime.KeepAlive(dw) -} - -// Starts a new sub-path at the given coordinate using absolute coordinates. -// The current point then becomes the specified coordinate. -// -// x, y: target x and y ordinates -func (dw *DrawingWand) PathMoveToAbsolute(x, y float64) { - C.DrawPathMoveToAbsolute(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Starts a new sub-path at the given coordinate using relative coordinates. -// The current point then becomes the specified coordinate. -// -// x, y: target x and y ordinates -func (dw *DrawingWand) PathMoveToRelative(x, y float64) { - C.DrawPathMoveToRelative(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Declares the start of a path drawing list which is terminated by a matching -// PathFinish() command. All other Path commands must be enclosed between a -// PathStart() and a PathFinish() command. This is because path drawing -// commands are subordinate commands and they do not function by themselves. -func (dw *DrawingWand) PathStart() { - C.DrawPathStart(dw.dw) - runtime.KeepAlive(dw) -} - -// Draws a point using the current fill color. -// -// x, y: target x, y coordinates -func (dw *DrawingWand) Point(x, y float64) { - C.DrawPoint(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Draws a polygon using the current stroke, stroke width, and fill color or -// texture, using the specified array of coordinates. -func (dw *DrawingWand) Polygon(coordinates []PointInfo) { - ccoordinates := [1 << 16]C.PointInfo{} - for k, v := range coordinates { - ccoordinates[k] = C.PointInfo{C.double(v.X), C.double(v.Y)} - } - C.DrawPolygon(dw.dw, C.size_t(len(coordinates)), (*C.PointInfo)(&ccoordinates[0])) - runtime.KeepAlive(dw) -} - -// Draws a polyline using the current stroke, stroke width, and fill color or -// texture, using the specified array of coordinates. -func (dw *DrawingWand) Polyline(coordinates []PointInfo) { - ccoordinates := [1 << 16]C.PointInfo{} - for k, v := range coordinates { - ccoordinates[k] = C.PointInfo{C.double(v.X), C.double(v.Y)} - } - C.DrawPolyline(dw.dw, C.size_t(len(coordinates)), (*C.PointInfo)(&ccoordinates[0])) - runtime.KeepAlive(dw) -} - -// Terminates a clip path definition. -func (dw *DrawingWand) PopClipPath() { - C.DrawPopClipPath(dw.dw) - runtime.KeepAlive(dw) -} - -// Terminates a definition list. -func (dw *DrawingWand) PopDefs() { - C.DrawPopDefs(dw.dw) - runtime.KeepAlive(dw) -} - -// Terminates a pattern definition. -func (dw *DrawingWand) PopPattern() error { - ok := C.DrawPopPattern(dw.dw) - return dw.getLastErrorIfFailed(ok) -} - -// Starts a clip path definition which is comprized of any number of drawing -// commands and terminated by a DrawPopClipPath() command. -// -// clipMaskId: string identifier to associate with the clip path for later use. -func (dw *DrawingWand) PushClipPath(clipMaskId string) { - cstr := C.CString(clipMaskId) - defer C.free(unsafe.Pointer(cstr)) - C.DrawPushClipPath(dw.dw, cstr) - runtime.KeepAlive(dw) -} - -// Indicates that commands up to a terminating PopDefs() command create named -// elements (e.g. clip-paths, textures, etc.) which may safely be processed -// earlier for the sake of efficiency. -func (dw *DrawingWand) PushDefs() { - C.DrawPushDefs(dw.dw) - runtime.KeepAlive(dw) -} - -// Indicates that subsequent commands up to a PopPattern() command comprise the -// definition of a named pattern. The pattern space is assigned top left corner -// coordinates, a width and height, and becomes its own drawing space. Anything -// which can be drawn may be used in a pattern definition. Named patterns may -// be used as stroke or brush definitions. -// -// patternId: pattern identification for later reference -// -// x, y: ordinates of top left corner -// -// width, height of pattern space -func (dw *DrawingWand) PushPattern(patternId string, x, y, width, height float64) error { - cstr := C.CString(patternId) - defer C.free(unsafe.Pointer(cstr)) - ok := C.DrawPushPattern(dw.dw, cstr, C.double(x), C.double(y), C.double(width), C.double(height)) - return dw.getLastErrorIfFailed(ok) -} - -// Draws a rectangle given two coordinates and using the current stroke, stroke -// width, and fill settings. -// -// x1, y1: ordinates of first coordinate -// -// x2, y2: ordinates of second coordinate -func (dw *DrawingWand) Rectangle(x1, y1, x2, y2 float64) { - C.DrawRectangle(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2)) - runtime.KeepAlive(dw) -} - -// Resets the vector graphics associated with the specified wand. -func (dw *DrawingWand) ResetVectorGraphics() { - C.DrawResetVectorGraphics(dw.dw) - runtime.KeepAlive(dw) -} - -// Applies the specified rotation to the current coordinate space. -// -// degrees: degrees of rotation -func (dw *DrawingWand) Rotate(degrees float64) { - C.DrawRotate(dw.dw, C.double(degrees)) - runtime.KeepAlive(dw) -} - -// Draws a rounted rectangle given two coordinates, x & y corner radiuses and -// using the current stroke, stroke width, and fill settings. -// -// x1, y1: ordinates of first coordinate -// -// x2, y2: ordinates of second coordinate -// -// rx, ry: radius of corner in horizontal and vertical directions -func (dw *DrawingWand) RoundRectangle(x1, y1, x2, y2, rx, ry float64) { - C.DrawRoundRectangle(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2), C.double(rx), C.double(ry)) - runtime.KeepAlive(dw) -} - -// Adjusts the scaling factor to apply in the horizontal and vertical -// directions to the current coordinate space. -// -// x: horizontal scale factor -// -// y: vertical scale factor -func (dw *DrawingWand) Scale(x, y float64) { - C.DrawScale(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Sets the border color to be used for drawing bordered objects. -func (dw *DrawingWand) SetBorderColor(borderWand *PixelWand) { - C.DrawSetBorderColor(dw.dw, borderWand.pw) - runtime.KeepAlive(dw) -} - -// Associates a named clipping path with the image. Only the areas drawn on by -// the clipping path will be modified as C.ssize_t(as) it remains in effect. -// clipMaskId: name of clipping path to associate with image -func (dw *DrawingWand) SetClipPath(clipMaskId string) error { - cstr := C.CString(clipMaskId) - defer C.free(unsafe.Pointer(cstr)) - ok := C.DrawSetClipPath(dw.dw, cstr) - return dw.getLastErrorIfFailed(ok) -} - -// Set the polygon fill rule to be used by the clipping path. -func (dw *DrawingWand) SetClipRule(fillRule FillRule) { - C.DrawSetClipRule(dw.dw, C.FillRule(fillRule)) - runtime.KeepAlive(dw) -} - -// Sets the interpretation of clip path units. -// clipUnits: units to use -func (dw *DrawingWand) SetClipUnits(clipUnits ClipPathUnits) { - C.DrawSetClipUnits(dw.dw, C.ClipPathUnits(clipUnits)) - runtime.KeepAlive(dw) -} - -// Sets the fill color to be used for drawing filled objects. -func (dw *DrawingWand) SetFillColor(fillWand *PixelWand) { - C.DrawSetFillColor(dw.dw, fillWand.pw) - runtime.KeepAlive(dw) -} - -// Sets the opacity to use when drawing using the fill color or fill texture. -// Fully opaque is 1.0. -func (dw *DrawingWand) SetFillOpacity(opacity float64) { - C.DrawSetFillOpacity(dw.dw, C.double(opacity)) - runtime.KeepAlive(dw) -} - -// Sets the image resolution. -// -// xRes, yRes: the image x and y resolutions -func (dw *DrawingWand) SetFontResolution(xRes, yRes float64) error { - ok := C.DrawSetFontResolution(dw.dw, C.double(xRes), C.double(yRes)) - return dw.getLastErrorIfFailed(ok) -} - -// Sets the opacity to use when drawing using the fill or stroke color or -// texture. Fully opaque is 1.0. -func (dw *DrawingWand) SetOpacity(opacity float64) { - C.DrawSetOpacity(dw.dw, C.double(opacity)) - runtime.KeepAlive(dw) -} - -// Sets the URL to use as a fill pattern for filling objects. Only local URLs -// ("#identifier") are supported at this time. These local URLs are normally -// created by defining a named fill pattern with PushPattern/PopPattern. -// -// fillUrl: URL to use to obtain fill pattern. -func (dw *DrawingWand) SetFillPatternURL(fillUrl string) error { - cstr := C.CString(fillUrl) - defer C.free(unsafe.Pointer(cstr)) - ok := C.DrawSetFillPatternURL(dw.dw, cstr) - return dw.getLastErrorIfFailed(ok) -} - -// Sets the fill rule to use while drawing polygons. -func (dw *DrawingWand) SetFillRule(fillRule FillRule) { - C.DrawSetFillRule(dw.dw, C.FillRule(fillRule)) - runtime.KeepAlive(dw) -} - -// Sets the fully-sepecified font to use when annotating with text. -func (dw *DrawingWand) SetFont(fontName string) error { - csFontName := C.CString(fontName) - defer C.free(unsafe.Pointer(csFontName)) - ok := C.DrawSetFont(dw.dw, csFontName) - return dw.getLastErrorIfFailed(ok) -} - -// Sets the font family to use when annotating with text. -func (dw *DrawingWand) SetFontFamily(fontFamily string) error { - csFontFamily := C.CString(fontFamily) - defer C.free(unsafe.Pointer(csFontFamily)) - ok := C.DrawSetFontFamily(dw.dw, csFontFamily) - return dw.getLastErrorIfFailed(ok) -} - -// Sets the font pointsize to use when annotating with text. -// -// pointSize: text pointsize -func (dw *DrawingWand) SetFontSize(pointSize float64) { - C.DrawSetFontSize(dw.dw, C.double(pointSize)) - runtime.KeepAlive(dw) -} - -// Sets the font stretch to use when annotating with text. The AnyStretch -// enumeration acts as a wild-card "don't care" option. -func (dw *DrawingWand) SetFontStretch(fontStretch StretchType) { - C.DrawSetFontStretch(dw.dw, C.StretchType(fontStretch)) - runtime.KeepAlive(dw) -} - -// Sets the font style to use when annotating with text. The AnyStyle -// enumeration acts as a wild-card "don't care" option. -func (dw *DrawingWand) SetFontStyle(style StyleType) { - C.DrawSetFontStyle(dw.dw, C.StyleType(style)) - runtime.KeepAlive(dw) -} - -// Sets the font weight to use when annotating with text. -// -// fontWeight: font weight (valid range 100-900) -func (dw *DrawingWand) SetFontWeight(fontWeight uint) { - C.DrawSetFontWeight(dw.dw, C.size_t(fontWeight)) - runtime.KeepAlive(dw) -} - -// Sets the text placement gravity to use when annotating with text. -func (dw *DrawingWand) SetGravity(gravity GravityType) { - C.DrawSetGravity(dw.dw, C.GravityType(gravity)) - runtime.KeepAlive(dw) -} - -// Sets the color used for stroking object outlines. -func (dw *DrawingWand) SetStrokeColor(strokeWand *PixelWand) { - C.DrawSetStrokeColor(dw.dw, strokeWand.pw) - runtime.KeepAlive(dw) -} - -// Sets the pattern used for stroking object outlines. -// -// strokeUrl: URL specifying pattern ID (e.g. "#pattern_id") -func (dw *DrawingWand) SetStrokePatternURL(strokeUrl string) error { - csStrokeUrl := C.CString(strokeUrl) - defer C.free(unsafe.Pointer(csStrokeUrl)) - ok := C.DrawSetStrokePatternURL(dw.dw, csStrokeUrl) - return dw.getLastErrorIfFailed(ok) -} - -// Controls whether stroked outlines are antialiased. Stroked outlines are -// antialiased by default. When antialiasing is disabled stroked pixels are -// thresholded to determine if the stroke color or underlying canvas color -// should be used. -// -// antialias: set to false to disable antialiasing -func (dw *DrawingWand) SetStrokeAntialias(antialias bool) { - C.DrawSetStrokeAntialias(dw.dw, b2i(antialias)) - runtime.KeepAlive(dw) -} - -// Specifies the pattern of dashes and gaps used to stroke paths. The stroke -// dash array represents an array of numbers that specify the lengths of -// alternating dashes and gaps in pixels. If an odd number of values is -// provided, then the list of values is repeated to yield an even number of -// values. To remove an existing dash array, pass an empty slice. A typical -// stroke dash array might contain the members 5 3 2. -func (dw *DrawingWand) SetStrokeDashArray(dash []float64) error { - if len(dash) == 0 { - ok := C.DrawSetStrokeDashArray(dw.dw, C.size_t(0), nil) - return dw.getLastErrorIfFailed(ok) - } - cdash := [1 << 16]C.double{} - for k, v := range dash { - cdash[k] = C.double(v) - } - ok := C.DrawSetStrokeDashArray(dw.dw, C.size_t(len(dash)), (*C.double)(&cdash[0])) - return dw.getLastErrorIfFailed(ok) -} - -// Specifies the offset into the dash pattern to start the dash. -func (dw *DrawingWand) SetStrokeDashOffset(offset float64) { - C.DrawSetStrokeDashOffset(dw.dw, C.double(offset)) - runtime.KeepAlive(dw) -} - -// Specifies the shape to be used at the end of open subpaths when they are -// stroked. -func (dw *DrawingWand) SetStrokeLineCap(lineCap LineCap) { - C.DrawSetStrokeLineCap(dw.dw, C.LineCap(lineCap)) - runtime.KeepAlive(dw) -} - -// Specifies the shape to be used at the corners of paths (or other vector -// shapes) when they are stroked. -func (dw *DrawingWand) SetStrokeLineJoin(lineJoin LineJoin) { - C.DrawSetStrokeLineJoin(dw.dw, C.LineJoin(lineJoin)) - runtime.KeepAlive(dw) -} - -// Specifies the miter limit. When two line segments meet at a sharp angle and -// miter joins have been specified for 'lineJoin', it is possible for the miter -// to extend far beyond the thickness of the line stroking the path. The -// miterLimit' imposes a limit on the ratio of the miter length to the -// 'lineWidth'. -func (dw *DrawingWand) SetStrokeMiterLimit(miterLimit uint) { - C.DrawSetStrokeMiterLimit(dw.dw, C.size_t(miterLimit)) - runtime.KeepAlive(dw) -} - -// Specifies the opacity of stroked object outlines. -// -// opacity: stroke opacity. The value 1.0 is opaque. -func (dw *DrawingWand) SetStrokeOpacity(opacity float64) { - C.DrawSetStrokeOpacity(dw.dw, C.double(opacity)) - runtime.KeepAlive(dw) -} - -// Sets the width of the stroke used to draw object outlines. -func (dw *DrawingWand) SetStrokeWidth(width float64) { - C.DrawSetStrokeWidth(dw.dw, C.double(width)) - runtime.KeepAlive(dw) -} - -// Specifies a text alignment to be applied when annotating with text. -func (dw *DrawingWand) SetTextAlignment(alignment AlignType) { - C.DrawSetTextAlignment(dw.dw, C.AlignType(alignment)) - runtime.KeepAlive(dw) -} - -// Controls whether text is antialiased. Text is antialiased by default. -func (dw *DrawingWand) SetTextAntialias(antialias bool) { - C.DrawSetTextAntialias(dw.dw, b2i(antialias)) - runtime.KeepAlive(dw) -} - -// Specifies a decoration to be applied when annotating with text. -func (dw *DrawingWand) SetTextDecoration(decoration DecorationType) { - C.DrawSetTextDecoration(dw.dw, C.DecorationType(decoration)) - runtime.KeepAlive(dw) -} - -// Specifies the code set to use for text annotations. The only character -// encoding which may be specified at this time is "UTF-8" for representing -// Unicode as a sequence of bytes. Specify an empty string to set text -// encoding to the system's default. Successful text annotation using Unicode -// may require fonts designed to support Unicode. -func (dw *DrawingWand) SetTextEncoding(encoding string) { - csencoding := C.CString(encoding) - defer C.free(unsafe.Pointer(csencoding)) - C.DrawSetTextEncoding(dw.dw, csencoding) - runtime.KeepAlive(dw) -} - -// Sets the spacing between characters in text. -func (dw *DrawingWand) SetTextKerning(kerning float64) { - C.DrawSetTextKerning(dw.dw, C.double(kerning)) - runtime.KeepAlive(dw) -} - -// Sets the spacing between line in text. -func (dw *DrawingWand) SetTextInterlineSpacing(spacing float64) { - C.DrawSetTextInterlineSpacing(dw.dw, C.double(spacing)) - runtime.KeepAlive(dw) -} - -// Sets the spacing between words in text. -func (dw *DrawingWand) SetTextInterwordSpacing(spacing float64) { - C.DrawSetTextInterwordSpacing(dw.dw, C.double(spacing)) - runtime.KeepAlive(dw) -} - -// Specifies the color of a background rectangle to place under text -// annotations. -func (dw *DrawingWand) SetTextUnderColor(underWand *PixelWand) { - C.DrawSetTextUnderColor(dw.dw, underWand.pw) - runtime.KeepAlive(dw) -} - -// Sets the vector graphics associated with the specified wand. Use this method -// with GetVectorGraphics() as a method to persist the vector graphics state. -func (dw *DrawingWand) SetVectorGraphics(xml string) error { - csxml := C.CString(xml) - defer C.free(unsafe.Pointer(csxml)) - ok := C.DrawSetVectorGraphics(dw.dw, csxml) - return dw.getLastErrorIfFailed(ok) -} - -// Skews the current coordinate system in the horizontal direction. -// -// degrees: number of degrees to skew the coordinates -func (dw *DrawingWand) SkewX(degrees float64) { - C.DrawSkewX(dw.dw, C.double(degrees)) - runtime.KeepAlive(dw) -} - -// Skews the current coordinate system in the vertical direction. -// -// degrees: number of degrees to skew the coordinates -func (dw *DrawingWand) SkewY(degrees float64) { - C.DrawSkewY(dw.dw, C.double(degrees)) - runtime.KeepAlive(dw) -} - -// Applies a translation to the current coordinate system which moves the -// coordinate system origin to the specified coordinate. -// -// x, y: new x, y ordinate for coordinate system origin -func (dw *DrawingWand) Translate(x, y float64) { - C.DrawTranslate(dw.dw, C.double(x), C.double(y)) - runtime.KeepAlive(dw) -} - -// Sets the overall canvas size to be recorded with the drawing vector data. -// Usually this will be specified using the same size as the canvas image. -// When the vector data is saved to SVG or MVG formats, the viewbox is use to -// specify the size of the canvas image that a viewer will render the vector -// data on. -// -// x1: left x ordinate -// -// y1: top y ordinate -// -// x2: right x ordinate -// -// y2: bottom y ordinate -func (dw *DrawingWand) SetViewbox(x1, y1, x2, y2 float64) { - C.DrawSetViewbox(dw.dw, C.double(x1), C.double(y1), C.double(x2), C.double(y2)) - runtime.KeepAlive(dw) -} - -// Returns true if the wand is verified as a drawing wand. -func (dw *DrawingWand) IsVerified() bool { - if dw.dw == nil { - return false - } - ret := 1 == C.IsDrawingWand(dw.dw) - runtime.KeepAlive(dw) - return ret -} - -// Returns the current drawing wand. -func (dw *DrawingWand) PeekDrawingWand() *DrawInfo { - ret := &DrawInfo{C.PeekDrawingWand(dw.dw)} - runtime.KeepAlive(dw) - return ret -} - -// Destroys the current drawing wand and returns to the previously pushed -// drawing wand. Multiple drawing wands may exist. It is an error to attempt -// to pop more drawing wands than have been pushed, and it is proper form to -// pop all drawing wands which have been pushed. -func (dw *DrawingWand) PopDrawingWand() error { - ok := C.PopDrawingWand(dw.dw) - return dw.getLastErrorIfFailed(ok) -} - -// Clones the current drawing wand to create a new drawing wand. The original -// drawing wand(s) may be returned to by invoking PopDrawingWand(). The drawing -// wands are stored on a drawing wand stack. For every Pop there must have -// already been an equivalent Push. -func (dw *DrawingWand) PushDrawingWand() error { - ok := C.PushDrawingWand(dw.dw) - return dw.getLastErrorIfFailed(ok) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand_exception.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand_exception.go deleted file mode 100644 index 33e9da26..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/drawing_wand_exception.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" - "runtime" - "unsafe" -) - -type DrawingWandException struct { - kind ExceptionType - description string -} - -func (dwe *DrawingWandException) Error() string { - return fmt.Sprintf("%s: %s", dwe.kind.String(), dwe.description) -} - -// Clears any exceptions associated with the wand -func (dw *DrawingWand) clearException() bool { - ret := 1 == C.int(C.DrawClearException(dw.dw)) - runtime.KeepAlive(dw) - return ret -} - -// Returns the kind, reason and description of any error that occurs when using other methods in this API -func (dw *DrawingWand) GetLastError() error { - var et C.ExceptionType - csdescription := C.DrawGetException(dw.dw, &et) - defer relinquishMemory(unsafe.Pointer(csdescription)) - if ExceptionType(et) != EXCEPTION_UNDEFINED { - dw.clearException() - return &DrawingWandException{ExceptionType(C.int(et)), C.GoString(csdescription)} - } - runtime.KeepAlive(dw) - return nil -} - -func (dw *DrawingWand) getLastErrorIfFailed(ok C.MagickBooleanType) error { - if C.int(ok) == 0 { - return dw.GetLastError() - } else { - return nil - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/endian_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/endian_type.go deleted file mode 100644 index aaa0de43..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/endian_type.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type EndianType int - -const ( - ENDIAN_UNDEFINED EndianType = C.UndefinedEndian - ENDIAN_LSB EndianType = C.LSBEndian - ENDIAN_MSB EndianType = C.MSBEndian -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/evaluate_operator.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/evaluate_operator.go deleted file mode 100644 index 1db215dc..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/evaluate_operator.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type EvaluateOperator int - -const ( - EVAL_OP_UNDEFINED EvaluateOperator = C.UndefinedEvaluateOperator - EVAL_OP_ADD EvaluateOperator = C.AddEvaluateOperator - EVAL_OP_AND EvaluateOperator = C.AndEvaluateOperator - EVAL_OP_DIVIDE EvaluateOperator = C.DivideEvaluateOperator - EVAL_OP_LEFT_SHIFT EvaluateOperator = C.LeftShiftEvaluateOperator - EVAL_OP_MAX EvaluateOperator = C.MaxEvaluateOperator - EVAL_OP_MIN EvaluateOperator = C.MinEvaluateOperator - EVAL_OP_MULTIPLY EvaluateOperator = C.MultiplyEvaluateOperator - EVAL_OP_OR EvaluateOperator = C.OrEvaluateOperator - EVAL_OP_RIGHT_SHIFT EvaluateOperator = C.RightShiftEvaluateOperator - EVAL_OP_SET EvaluateOperator = C.SetEvaluateOperator - EVAL_OP_SUBTRACT EvaluateOperator = C.SubtractEvaluateOperator - EVAL_OP_XOR EvaluateOperator = C.XorEvaluateOperator - EVAL_OP_POW EvaluateOperator = C.PowEvaluateOperator - EVAL_OP_LOG EvaluateOperator = C.LogEvaluateOperator - EVAL_OP_THRESHOLD EvaluateOperator = C.ThresholdEvaluateOperator - EVAL_OP_THRESHOLD_BLACK EvaluateOperator = C.ThresholdBlackEvaluateOperator - EVAL_OP_THRESHOLD_WHITE EvaluateOperator = C.ThresholdWhiteEvaluateOperator - EVAL_OP_GAUSSIAN_NOISE EvaluateOperator = C.GaussianNoiseEvaluateOperator - EVAL_OP_IMPULSE_NOISE EvaluateOperator = C.ImpulseNoiseEvaluateOperator - EVAL_OP_LAPLACIAN_NOISE EvaluateOperator = C.LaplacianNoiseEvaluateOperator - EVAL_OP_MULTIPLICATIVE_NOISE EvaluateOperator = C.MultiplicativeNoiseEvaluateOperator - EVAL_OP_POISSON_NOISE EvaluateOperator = C.PoissonNoiseEvaluateOperator - EVAL_OP_UNIFORM_NOISE EvaluateOperator = C.UniformNoiseEvaluateOperator - EVAL_OP_COSINE EvaluateOperator = C.CosineEvaluateOperator - EVAL_OP_SINE EvaluateOperator = C.SineEvaluateOperator - EVAL_OP_ADD_MODULUS EvaluateOperator = C.AddModulusEvaluateOperator - EVAL_OP_MEAN EvaluateOperator = C.MeanEvaluateOperator - EVAL_OP_ABS EvaluateOperator = C.AbsEvaluateOperator - EVAL_OP_EXPONENTIAL EvaluateOperator = C.ExponentialEvaluateOperator - EVAL_OP_MEDIAN EvaluateOperator = C.MedianEvaluateOperator - EVAL_OP_SUM EvaluateOperator = C.SumEvaluateOperator -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_info.go deleted file mode 100644 index 41ee61b5..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_info.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import "fmt" - -// ExceptionInfo is an error type returned by certain -// New* API calls. -type ExceptionInfo struct { - kind ExceptionType - errno int - reason string - description string -} - -// Create a new ExceptionInfo wrapper around a C ExceptionInfo ptr -func newExceptionInfo(errInfo *C.ExceptionInfo) *ExceptionInfo { - if errInfo == nil { - return nil - } - - return &ExceptionInfo{ - kind: ExceptionType(errInfo.severity), - errno: int(errInfo.error_number), - reason: C.GoString(errInfo.reason), - description: C.GoString(errInfo.description), - } -} - -// Check if a given C ExceptionInfo ptr is an error. -// Returns a valid ExceptionInfo if there was an error, -// otherwise returns nil -func checkExceptionInfo(errInfo *C.ExceptionInfo) *ExceptionInfo { - if errInfo != nil && errInfo.error_number != 0 { - return newExceptionInfo(errInfo) - } - - return nil -} - -func (e *ExceptionInfo) Clear() { - if e == nil { - return - } - *e = ExceptionInfo{kind: EXCEPTION_UNDEFINED} -} - -// IsSet returns true if any exception level is set, be it -// a warning or error kind -func (e *ExceptionInfo) IsSet() bool { - if e == nil { - return false - } - return e.kind > EXCEPTION_UNDEFINED -} - -// IsWarningKind returns true if the exception level is set -// to a warning -func (e *ExceptionInfo) IsWarningKind() bool { - if e == nil { - return false - } - return e.kind >= EXCEPTION_WARNING && e.kind < EXCEPTION_ERROR -} - -// IsErrorKind returns true if the exception level is set -// to at least an error -func (e *ExceptionInfo) IsErrorKind() bool { - if e == nil { - return false - } - return e.kind >= EXCEPTION_ERROR -} - -func (e *ExceptionInfo) Error() string { - if e == nil { - return "" - } - return fmt.Sprintf("%s (%d): %s %s", - e.kind.String(), e.Errno(), e.Reason(), e.Description()) -} - -// Errno returns the ExceptionInfo error number (non-zero if error) -func (e *ExceptionInfo) Errno() int { - if e == nil { - return 0 - } - return e.errno -} - -// Kind returns the exception level. -// EXCEPTION_UNDEFINED indicates that no exception has been set -func (e *ExceptionInfo) Kind() ExceptionType { - if e == nil { - return EXCEPTION_UNDEFINED - } - return e.kind -} - -// Reason returns the string reason for the Exception -func (e *ExceptionInfo) Reason() string { - if e == nil { - return "" - } - return e.reason -} - -// Description returns the string description for the Exception -func (e *ExceptionInfo) Description() string { - if e == nil { - return "" - } - return e.description -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_type.go deleted file mode 100644 index 940489fb..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/exception_type.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" -) - -type ExceptionType int - -const ( - EXCEPTION_UNDEFINED ExceptionType = C.UndefinedException - EXCEPTION_WARNING ExceptionType = C.WarningException - WARNING_RESOURCE_LIMIT ExceptionType = C.ResourceLimitWarning - WARNING_TYPE ExceptionType = C.TypeWarning - WARNING_OPTION ExceptionType = C.OptionWarning - WARNING_DELEGATE ExceptionType = C.DelegateWarning - WARNING_MISSING_DELEGATE ExceptionType = C.MissingDelegateWarning - WARNING_CORRUPT_IMAGE ExceptionType = C.CorruptImageWarning - WARNING_FILE_OPEN ExceptionType = C.FileOpenWarning - WARNING_BLOB ExceptionType = C.BlobWarning - WARNING_STREAM ExceptionType = C.StreamWarning - WARNING_CACHE ExceptionType = C.CacheWarning - WARNING_CODER ExceptionType = C.CoderWarning - WARNING_FILTER ExceptionType = C.FilterWarning - WARNING_MODULE ExceptionType = C.ModuleWarning - WARNING_DRAW ExceptionType = C.DrawWarning - WARNING_IMAGE ExceptionType = C.ImageWarning - WARNING_WAND ExceptionType = C.WandWarning - WARNING_RANDOM ExceptionType = C.RandomWarning - WARNING_XSERVER ExceptionType = C.XServerWarning - WARNING_MONITOR ExceptionType = C.MonitorWarning - WARNING_REGISTRY ExceptionType = C.RegistryWarning - WARNING_CONFIGURE ExceptionType = C.ConfigureWarning - WARNING_POLICY ExceptionType = C.PolicyWarning - EXCEPTION_ERROR ExceptionType = C.ErrorException - ERROR_RESOURCE_LIMIT ExceptionType = C.ResourceLimitError - ERROR_TYPE ExceptionType = C.TypeError - ERROR_OPTION ExceptionType = C.OptionError - ERROR_DELEGATE ExceptionType = C.DelegateError - ERROR_MISSING_DELEGATE ExceptionType = C.MissingDelegateError - ERROR_CORRUPT_IMAGE ExceptionType = C.CorruptImageError - ERROR_FILE_OPEN ExceptionType = C.FileOpenError - ERROR_BLOB ExceptionType = C.BlobError - ERROR_STREAM ExceptionType = C.StreamError - ERROR_CACHE ExceptionType = C.CacheError - ERROR_CODER ExceptionType = C.CoderError - ERROR_FILTER ExceptionType = C.FilterError - ERROR_MODULE ExceptionType = C.ModuleError - ERROR_DRAW ExceptionType = C.DrawError - ERROR_IMAGE ExceptionType = C.ImageError - ERROR_WAND ExceptionType = C.WandError - ERROR_RANDOM ExceptionType = C.RandomError - ERROR_XSERVER ExceptionType = C.XServerError - ERROR_MONITOR ExceptionType = C.MonitorError - ERROR_REGISTRY ExceptionType = C.RegistryError - ERROR_CONFIGURE ExceptionType = C.ConfigureError - ERROR_POLICY ExceptionType = C.PolicyError - EXCEPTION_FATAL_ERROR ExceptionType = C.FatalErrorException - FATAL_ERROR_RESOURCE_LIMIT ExceptionType = C.ResourceLimitFatalError - FATAL_ERROR_TYPE ExceptionType = C.TypeFatalError - FATAL_ERROR_OPTION ExceptionType = C.OptionFatalError - FATAL_ERROR_DELEGATE ExceptionType = C.DelegateFatalError - FATAL_ERROR_MISSING_DELEGATE ExceptionType = C.MissingDelegateFatalError - FATAL_ERROR_CORRUPT_IMAGE ExceptionType = C.CorruptImageFatalError - FATAL_ERROR_FILE_OPEN ExceptionType = C.FileOpenFatalError - FATAL_ERROR_BLOB ExceptionType = C.BlobFatalError - FATAL_ERROR_STREAM ExceptionType = C.StreamFatalError - FATAL_ERROR_CACHE ExceptionType = C.CacheFatalError - FATAL_ERROR_CODER ExceptionType = C.CoderFatalError - FATAL_ERROR_FILTER ExceptionType = C.FilterFatalError - FATAL_ERROR_MODULE ExceptionType = C.ModuleFatalError - FATAL_ERROR_DRAW ExceptionType = C.DrawFatalError - FATAL_ERROR_IMAGE ExceptionType = C.ImageFatalError - FATAL_ERROR_WAND ExceptionType = C.WandFatalError - FATAL_ERROR_RANDOM ExceptionType = C.RandomFatalError - FATAL_ERROR_XSERVER ExceptionType = C.XServerFatalError - FATAL_ERROR_MONITOR ExceptionType = C.MonitorFatalError - FATAL_ERROR_REGISTRY ExceptionType = C.RegistryFatalError - FATAL_ERROR_CONFIGURE ExceptionType = C.ConfigureFatalError - FATAL_ERROR_POLICY ExceptionType = C.PolicyFatalError -) - -var exceptionTypeStrings = map[ExceptionType]string{ - EXCEPTION_UNDEFINED: "EXCEPTION_UNDEFINED", - EXCEPTION_WARNING: "EXCEPTION_WARNING", - WARNING_TYPE: "WARNING_TYPE", - WARNING_OPTION: "WARNING_OPTION", - WARNING_DELEGATE: "WARNING_DELEGATE", - WARNING_MISSING_DELEGATE: "WARNING_MISSING_DELEGATE", - WARNING_CORRUPT_IMAGE: "WARNING_CORRUPT_IMAGE", - WARNING_FILE_OPEN: "WARNING_FILE_OPEN", - WARNING_BLOB: "WARNING_BLOB", - WARNING_STREAM: "WARNING_STREAM", - WARNING_CACHE: "WARNING_CACHE", - WARNING_CODER: "WARNING_CODER", - WARNING_FILTER: "WARNING_FILTER", - WARNING_MODULE: "WARNING_MODULE", - WARNING_DRAW: "WARNING_DRAW", - WARNING_IMAGE: "WARNING_IMAGE", - WARNING_WAND: "WARNING_WAND", - WARNING_RANDOM: "WARNING_RANDOM", - WARNING_XSERVER: "WARNING_XSERVER", - WARNING_MONITOR: "WARNING_MONITOR", - WARNING_REGISTRY: "WARNING_REGISTRY", - WARNING_CONFIGURE: "WARNING_CONFIGURE", - WARNING_POLICY: "WARNING_POLICY", - EXCEPTION_ERROR: "EXCEPTION_ERROR", - ERROR_TYPE: "ERROR_TYPE", - ERROR_OPTION: "ERROR_OPTION", - ERROR_DELEGATE: "ERROR_DELEGATE", - ERROR_MISSING_DELEGATE: "ERROR_MISSING_DELEGATE", - ERROR_CORRUPT_IMAGE: "ERROR_CORRUPT_IMAGE", - ERROR_FILE_OPEN: "ERROR_FILE_OPEN", - ERROR_BLOB: "ERROR_BLOB", - ERROR_STREAM: "ERROR_STREAM", - ERROR_CACHE: "ERROR_CACHE", - ERROR_CODER: "ERROR_CODER", - ERROR_FILTER: "ERROR_FILTER", - ERROR_MODULE: "ERROR_MODULE", - ERROR_DRAW: "ERROR_DRAW", - ERROR_IMAGE: "ERROR_IMAGE", - ERROR_WAND: "ERROR_WAND", - ERROR_RANDOM: "ERROR_RANDOM", - ERROR_XSERVER: "ERROR_XSERVER", - ERROR_MONITOR: "ERROR_MONITOR", - ERROR_REGISTRY: "ERROR_REGISTRY", - ERROR_CONFIGURE: "ERROR_CONFIGURE", - ERROR_POLICY: "ERROR_POLICY", - EXCEPTION_FATAL_ERROR: "EXCEPTION_FATAL_ERROR", - FATAL_ERROR_TYPE: "FATAL_ERROR_TYPE", - FATAL_ERROR_OPTION: "FATAL_ERROR_OPTION", - FATAL_ERROR_DELEGATE: "FATAL_ERROR_DELEGATE", - FATAL_ERROR_MISSING_DELEGATE: "FATAL_ERROR_MISSING_DELEGATE", - FATAL_ERROR_CORRUPT_IMAGE: "FATAL_ERROR_CORRUPT_IMAGE", - FATAL_ERROR_FILE_OPEN: "FATAL_ERROR_FILE_OPEN", - FATAL_ERROR_BLOB: "FATAL_ERROR_BLOB", - FATAL_ERROR_STREAM: "FATAL_ERROR_STREAM", - FATAL_ERROR_CACHE: "FATAL_ERROR_CACHE", - FATAL_ERROR_CODER: "FATAL_ERROR_CODER", - FATAL_ERROR_FILTER: "FATAL_ERROR_FILTER", - FATAL_ERROR_MODULE: "FATAL_ERROR_MODULE", - FATAL_ERROR_DRAW: "FATAL_ERROR_DRAW", - FATAL_ERROR_IMAGE: "FATAL_ERROR_IMAGE", - FATAL_ERROR_WAND: "FATAL_ERROR_WAND", - FATAL_ERROR_RANDOM: "FATAL_ERROR_RANDOM", - FATAL_ERROR_XSERVER: "FATAL_ERROR_XSERVER", - FATAL_ERROR_MONITOR: "FATAL_ERROR_MONITOR", - FATAL_ERROR_REGISTRY: "FATAL_ERROR_REGISTRY", - FATAL_ERROR_CONFIGURE: "FATAL_ERROR_CONFIGURE", - FATAL_ERROR_POLICY: "FATAL_ERROR_POLICY", - //WARNING_RESOURCE_LIMIT: "WARNING_RESOURCE_LIMIT", - //ERROR_RESOURCE_LIMIT: "ERROR_RESOURCE_LIMIT", - //FATAL_ERROR_RESOURCE_LIMIT: "FATAL_ERROR_RESOURCE_LIMIT", -} - -func (et *ExceptionType) String() string { - if v, ok := exceptionTypeStrings[ExceptionType(*et)]; ok { - return v - } - return fmt.Sprintf("UnknownError[%d]", *et) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/fill_rule.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/fill_rule.go deleted file mode 100644 index f4d89c90..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/fill_rule.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type FillRule int - -const ( - FILL_UNDEFINED FillRule = C.UndefinedRule - FILL_EVEN_ODD FillRule = C.EvenOddRule - FILL_NON_ZERO FillRule = C.NonZeroRule -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/filter_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/filter_type.go deleted file mode 100644 index c3f74888..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/filter_type.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type FilterType int - -const ( - FILTER_UNDEFINED FilterType = C.UndefinedFilter - FILTER_POINT FilterType = C.PointFilter - FILTER_BOX FilterType = C.BoxFilter - FILTER_TRIANGLE FilterType = C.TriangleFilter - FILTER_HERMITE FilterType = C.HermiteFilter - FILTER_HANNING FilterType = C.HanningFilter - FILTER_HAMMING FilterType = C.HammingFilter - FILTER_BLACKMAN FilterType = C.BlackmanFilter - FILTER_GAUSSIAN FilterType = C.GaussianFilter - FILTER_QUADRATIC FilterType = C.QuadraticFilter - FILTER_CUBIC FilterType = C.CubicFilter - FILTER_CATROM FilterType = C.CatromFilter - FILTER_MITCHELL FilterType = C.MitchellFilter - FILTER_JINC FilterType = C.JincFilter - FILTER_SINC FilterType = C.SincFilter - FILTER_SINC_FAST FilterType = C.SincFastFilter - FILTER_KAISER FilterType = C.KaiserFilter - FILTER_WELSH FilterType = C.WelshFilter - FILTER_PARZEN FilterType = C.ParzenFilter - FILTER_BOHMAN FilterType = C.BohmanFilter - FILTER_BARTLETT FilterType = C.BartlettFilter - FILTER_LAGRANGE FilterType = C.LagrangeFilter - FILTER_LANCZOS FilterType = C.LanczosFilter - FILTER_LANCZOS_SHARP FilterType = C.LanczosSharpFilter - FILTER_LANCZOS2 FilterType = C.Lanczos2Filter - FILTER_LANCZOS2_SHARP FilterType = C.Lanczos2SharpFilter - FILTER_ROBIDOUX FilterType = C.RobidouxFilter - FILTER_ROBIDOUX_SHARP FilterType = C.RobidouxSharpFilter - FILTER_COSINE FilterType = C.CosineFilter - FILTER_SPLINE FilterType = C.SplineFilter - FILTER_SENTINEL FilterType = C.SentinelFilter - FILTER_LANCZOS_RADIUS FilterType = C.LanczosRadiusFilter -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/fix_32_bit.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/fix_32_bit.go deleted file mode 100644 index 7e6f33da..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/fix_32_bit.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build 386 - -package imagick - -//#cgo CFLAGS: -DMAGICKCORE_SIZEOF_FLOAT_T=MAGICKCORE_SIZEOF_DOUBLE -import "C" diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/font_metrics.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/font_metrics.go deleted file mode 100644 index 8f5541e0..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/font_metrics.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -type FontMetrics struct { - CharacterWidth float64 - CharacterHeight float64 - Ascender float64 - Descender float64 - TextWidth float64 - TextHeight float64 - MaximumHorizontalAdvance float64 - BoundingBoxX1 float64 - BoundingBoxY1 float64 - BoundingBoxX2 float64 - BoundingBoxY2 float64 - OriginX float64 - OriginY float64 -} - -func NewFontMetricsFromArray(arr []float64) *FontMetrics { - if len(arr) != 13 { - panic("Wrong number of font metric items") - } - return &FontMetrics{arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9], arr[10], arr[11], arr[12]} -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_flags.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_flags.go deleted file mode 100644 index b64d9d36..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_flags.go +++ /dev/null @@ -1,39 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -const ( - NOVALUE = C.NoValue // = 0x0000 - XVALUE = C.XValue ////= 0x0001 - XIVALUE = C.XiValue //= 0x0001 - YVALUE = C.YValue //= 0x0002 - PSIVALUE = C.PsiValue //= 0x0002 - - WIDTHVALUE = C.WidthValue //= 0x0004 - RHOVALUE = C.RhoValue //= 0x0004 - - HEIGHTVALUE = C.HeightValue //= 0x0008 - SIGMAVALUE = C.SigmaValue //= 0x0008 - CHIVALUE = C.ChiValue //= 0x0010 - XINEGATIVE = C.XiNegative //= 0x0020 - - XNEGATIVE = C.XNegative //= 0x0020 - PSINEGATIVE = C.PsiNegative //= 0x0040 - YNEGATIVE = C.YNegative //= 0x0040 - CHINEGATIVE = C.ChiNegative //= 0x0080 - PERCENTVALUE = C.PercentValue //= 0x1000 /* '%' percentage of something */ - ASPECTVALUE = C.AspectValue //= 0x2000 /* '!' resize no-aspect - special use flag */ - NORMALIZEVALUE = C.NormalizeValue //= 0x2000 /* '!' ScaleKernelValue() in morphology.c */ - LESSVALUE = C.LessValue //= 0x4000 /* '<' resize smaller - special use flag */ - GREATERVALUE = C.GreaterValue //= 0x8000 /* '>' resize larger - spacial use flag */ - MINIMUMVALUE = C.MinimumValue //= 0x10000 /* '^' special handling needed */ - CORRELATENORMALIZEVALUE = C.CorrelateNormalizeValue //= 0x10000 /* '^' see ScaleKernelValue() */ - AREAVALUE = C.AreaValue //= 0x20000 /* '@' resize to area - special use flag */ - DECIMALVALUE = C.DecimalValue //= 0x40000 /* '.' floating point numbers found */ - SEPARATORVALUE = C.SeparatorValue //= 0x80000 /* 'x' separator found */ - - ALLVALUES = C.AllValues //= 0x7fffffff -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_info.go deleted file mode 100644 index 39190826..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/geometry_info.go +++ /dev/null @@ -1,10 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -type GeometryInfo struct { - gi C.GeometryInfo -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/gradient_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/gradient_type.go deleted file mode 100644 index b95506dd..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/gradient_type.go +++ /dev/null @@ -1,41 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -type GradientType int - -const ( - GRADIENT_TYPE_UNDEFINED GradientType = C.UndefinedGradient - GRADIENT_TYPE_LINEAR GradientType = C.LinearGradient - GRADIENT_TYPE_RADIAL GradientType = C.RadialGradient -) - -// StopInfo describes the color and offset of a -// color stop component in a gradient -type StopInfo struct { - info C.StopInfo -} - -// NewStopInfo creates a StopInfo from the color of a -// PixelInfo, and a stop offset value in the gradient. -// The offset value is from 0.0 to 1.0 -func NewStopInfo(pi *PixelInfo, offset float64) StopInfo { - var stop StopInfo - stop.SetPixelInfo(pi) - stop.SetOffset(offset) - return stop -} - -// SetPixelInfo sets the gradient stop color value -func (s *StopInfo) SetPixelInfo(pi *PixelInfo) { - s.info.color = *(pi.pi) -} - -// SetOffset sets the stop offset within the gradient, -// from 0.0 to 1.0 -func (s *StopInfo) SetOffset(offset float64) { - s.info.offset = C.double(offset) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/gravity_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/gravity_type.go deleted file mode 100644 index 83d5f157..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/gravity_type.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type GravityType int - -const ( - GRAVITY_UNDEFINED GravityType = C.UndefinedGravity - GRAVITY_FORGET GravityType = C.ForgetGravity - GRAVITY_NORTH_WEST GravityType = C.NorthWestGravity - GRAVITY_NORTH GravityType = C.NorthGravity - GRAVITY_NORTH_EAST GravityType = C.NorthEastGravity - GRAVITY_WEST GravityType = C.WestGravity - GRAVITY_CENTER GravityType = C.CenterGravity - GRAVITY_EAST GravityType = C.EastGravity - GRAVITY_SOUTH_WEST GravityType = C.SouthWestGravity - GRAVITY_SOUTH GravityType = C.SouthGravity - GRAVITY_SOUTH_EAST GravityType = C.SouthEastGravity -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/image.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/image.go deleted file mode 100644 index 0231565c..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/image.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -#include -*/ -import "C" -import ( - "runtime" - "unsafe" -) - -type Image struct { - img *C.Image -} - -func NewMagickImage(info *ImageInfo, width, height uint, - background *PixelInfo) (*Image, *ExceptionInfo) { - - var exc C.ExceptionInfo - - img := C.NewMagickImage( - info.info, - C.size_t(width), C.size_t(height), - background.pi, - &exc) - - runtime.KeepAlive(info) - - if err := checkExceptionInfo(&exc); err != nil { - return nil, err - } - - return &Image{img: img}, nil -} - -// ImageCommandResult is returned by a call to -// ConvertImageCommand. It contains the ImageInfo -// and Metadata string generated by the convert command. -type ImageCommandResult struct { - Info *ImageInfo - Meta string -} - -/* -ConvertImageCommand reads one or more images, applies one or more image -processing operations, and writes out the image in the same or differing -format. -The first item in the args list is expected to be the program name, ie "convert". -*/ -func ConvertImageCommand(args []string) (*ImageCommandResult, error) { - size := len(args) - - cmdArr := make([]*C.char, size) - for i, s := range args { - cmdArr[i] = C.CString(s) - } - - empty := C.CString("") - metaStr := C.AcquireString(empty) - C.free(unsafe.Pointer(empty)) - - defer func() { - for i := range cmdArr { - C.free(unsafe.Pointer(cmdArr[i])) - } - - C.DestroyString(metaStr) - }() - - imageInfo := newImageInfo() - - var exc *C.ExceptionInfo = C.AcquireExceptionInfo() - defer C.DestroyExceptionInfo(exc) - - ok := C.ConvertImageCommand( - imageInfo.info, - C.int(size), // argc - &cmdArr[0], // argv - &metaStr, // metadata - exc, // exception - ) - if C.int(ok) == 0 { - imageInfo.Destroy() - return nil, newExceptionInfo(exc) - } - - ret := &ImageCommandResult{ - Info: imageInfo, - Meta: C.GoString(metaStr), - } - return ret, nil -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/image_info.go deleted file mode 100644 index c14de4ae..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_info.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import "runtime" - -type ImageInfo struct { - info *C.ImageInfo -} - -func newImageInfo() *ImageInfo { - ptr := C.AcquireImageInfo() - C.GetImageInfo(ptr) - imageInfo := &ImageInfo{ptr} - runtime.SetFinalizer(imageInfo, Destroy) - return imageInfo -} - -// Destroy the ImageInfo immediately. -// This will also be called automatically during garbage collection. -func (ii *ImageInfo) Destroy() { - if ii.info != nil { - C.DestroyImageInfo(ii.info) - runtime.SetFinalizer(ii, nil) - ii.info = nil - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_layer_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/image_layer_method.go deleted file mode 100644 index 203a0c54..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_layer_method.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type LayerMethod int - -const ( - IMAGE_LAYER_UNDEFINED LayerMethod = C.UndefinedLayer - IMAGE_LAYER_COALESCE LayerMethod = C.CoalesceLayer - IMAGE_LAYER_COMPARE_ANY LayerMethod = C.CompareAnyLayer - IMAGE_LAYER_COMPARE_CLEAR LayerMethod = C.CompareClearLayer - IMAGE_LAYER_COMPARE_OVERLAY LayerMethod = C.CompareOverlayLayer - IMAGE_LAYER_DISPOSE LayerMethod = C.DisposeLayer - IMAGE_LAYER_OPTIMIZE LayerMethod = C.OptimizeLayer - IMAGE_LAYER_OPTIMIZE_IMAGE LayerMethod = C.OptimizeImageLayer - IMAGE_LAYER_OPTIMIZE_PLUS LayerMethod = C.OptimizePlusLayer - IMAGE_LAYER_OPTIMIZE_TRANS LayerMethod = C.OptimizeTransLayer - IMAGE_LAYER_REMOVE_DUPS LayerMethod = C.RemoveDupsLayer - IMAGE_LAYER_REMOVE_ZERO LayerMethod = C.RemoveZeroLayer - IMAGE_LAYER_COMPOSITE LayerMethod = C.CompositeLayer - IMAGE_LAYER_MERGE LayerMethod = C.MergeLayer - IMAGE_LAYER_FLATTEN LayerMethod = C.FlattenLayer - IMAGE_LAYER_MOSAIC LayerMethod = C.MosaicLayer - IMAGE_LAYER_TRIM_BOUNDS LayerMethod = C.TrimBoundsLayer -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/image_type.go deleted file mode 100644 index 85349214..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/image_type.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ImageType int - -const ( - IMAGE_TYPE_UNDEFINED ImageType = C.UndefinedType - IMAGE_TYPE_BILEVEL ImageType = C.BilevelType - IMAGE_TYPE_COLOR_SEPARATION ImageType = C.ColorSeparationType - IMAGE_TYPE_COLOR_SEPARATION_ALPHA ImageType = C.ColorSeparationAlphaType - IMAGE_TYPE_GRAYSCALE ImageType = C.GrayscaleType - IMAGE_TYPE_GRAYSCALE_ALPHA ImageType = C.GrayscaleAlphaType - IMAGE_TYPE_OPTIMIZE ImageType = C.OptimizeType - IMAGE_TYPE_PALETTE ImageType = C.PaletteType - IMAGE_TYPE_PALETTE_ALPHA ImageType = C.PaletteAlphaType - IMAGE_TYPE_PALETTE_BILEVEL_ALPHA ImageType = C.PaletteBilevelAlphaType - IMAGE_TYPE_TRUE_COLOR ImageType = C.TrueColorType - IMAGE_TYPE_TRUE_COLOR_ALPHA ImageType = C.TrueColorAlphaType -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/imagick.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/imagick.go deleted file mode 100644 index 8cda6847..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/imagick.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick // import "gopkg.in/gographics/imagick.v3/imagick" - -/* -#cgo !no_pkgconfig pkg-config: MagickWand MagickCore -*/ -import "C" diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/index_packet.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/index_packet.go deleted file mode 100644 index 00666360..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/index_packet.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type IndexPacket Quantum diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/interlace_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/interlace_type.go deleted file mode 100644 index 61079d72..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/interlace_type.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type InterlaceType int - -const ( - INTERLACE_UNDEFINED InterlaceType = C.UndefinedInterlace - INTERLACE_NO InterlaceType = C.NoInterlace - INTERLACE_LINE InterlaceType = C.LineInterlace - INTERLACE_PLANE InterlaceType = C.PlaneInterlace - INTERLACE_PARTITION InterlaceType = C.PartitionInterlace - INTERLACE_GIF InterlaceType = C.GIFInterlace - INTERLACE_JPEG InterlaceType = C.JPEGInterlace - INTERLACE_PNG InterlaceType = C.PNGInterlace -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/interpolate_pixel_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/interpolate_pixel_method.go deleted file mode 100644 index 57743b06..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/interpolate_pixel_method.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PixelInterpolateMethod int - -const ( - INTERPOLATE_PIXEL_UNDEFINED PixelInterpolateMethod = C.UndefinedInterpolatePixel - INTERPOLATE_PIXEL_AVERAGE PixelInterpolateMethod = C.AverageInterpolatePixel // Average 4 nearest neighbours - INTERPOLATE_PIXEL_AVERAGE16 PixelInterpolateMethod = C.Average16InterpolatePixel // Average 16 nearest neighbours - INTERPOLATE_PIXEL_AVERAGE9 PixelInterpolateMethod = C.Average9InterpolatePixel // Average 9 nearest neighbours - INTERPOLATE_PIXEL_BACKGROUND PixelInterpolateMethod = C.BackgroundInterpolatePixel // just return background color - INTERPOLATE_PIXEL_BILINEAR PixelInterpolateMethod = C.BilinearInterpolatePixel // Triangular filter interpolation - INTERPOLATE_PIXEL_BLEND PixelInterpolateMethod = C.BlendInterpolatePixel // blend of nearest 1, 2 or 4 pixels - INTERPOLATE_PIXEL_CATROM PixelInterpolateMethod = C.CatromInterpolatePixel // Catmull-Rom interpolation - INTERPOLATE_PIXEL_INTEGER PixelInterpolateMethod = C.IntegerInterpolatePixel // Integer (floor) interpolation - INTERPOLATE_PIXEL_MESH PixelInterpolateMethod = C.MeshInterpolatePixel // Triangular mesh interpolation - INTERPOLATE_PIXEL_NEAREST_INTERPOLATE PixelInterpolateMethod = C.NearestInterpolatePixel // Nearest neighbour only - INTERPOLATE_PIXEL_SPLINE PixelInterpolateMethod = C.SplineInterpolatePixel // Cubic Spline (blurred) interpolation -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info.go deleted file mode 100644 index 4687dafd..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "runtime" - "unsafe" -) - -// This struct represents the KernelInfo C API of ImageMagick -type KernelInfo struct { - info *C.KernelInfo -} - -func newKernelInfo(cki *C.KernelInfo) *KernelInfo { - ki := &KernelInfo{info: cki} - runtime.SetFinalizer(ki, Destroy) - return ki -} - -// Destroy the KernelInfo immediately. -// This will also be called automatically during garbage collection. -func (ki *KernelInfo) Destroy() { - if ki.info != nil { - C.DestroyKernelInfo(ki.info) - runtime.SetFinalizer(ki, nil) - ki.info = nil - } -} - -// Convert the current KernelInfo to an 2d-array of values. The values are either -// a float64 if the element is used, or NaN if the element is not used by the kernel -func (ki *KernelInfo) ToArray() [][]float64 { - var values [][]float64 - - count := 0 - cValues := (*[1 << 10]C.double)(unsafe.Pointer(ki.info.values)) - - for y := C.size_t(0); y < ki.info.height; y++ { - rowValues := make([]float64, ki.info.width) - for x := C.size_t(0); x < ki.info.width; x++ { - rowValues[x] = float64(cValues[count]) - count++ - } - values = append(values, rowValues) - } - - runtime.KeepAlive(ki) - return values -} - -/* -NewKernelInfo takes the given string (generally supplied by the user) and converts it -into a Morphology/Convolution Kernel. This allows users to specify a kernel from a number -of pre-defined kernels, or to fully specify their own kernel for a specific Convolution -or Morphology Operation. - -Returns a *ExceptionInfo on error - -Ref: http://www.imagemagick.org/api/morphology.php#AcquireKernelBuiltIn - -Details: - -The kernel so generated can be any rectangular array of floating point values (doubles) -with the 'control point' or 'pixel being affected' anywhere within that array of values. - -Previously IM was restricted to a square of odd size using the exact center as origin, -this is no longer the case, and any rectangular kernel with any value being declared the origin. -This in turn allows the use of highly asymmetrical kernels. - -The floating point values in the kernel can also include a special value known as 'nan' -or 'not a number' to indicate that this value is not part of the kernel array. This allows -you to shaped the kernel within its rectangular area. That is 'nan' values provide a 'mask' -for the kernel shape. However at least one non-nan value must be provided for correct working -of a kernel. - -Input kernel defintion strings can consist of any of three types. - -"name:args[[@><]" Select from one of the built in kernels, using the name and geometry -arguments supplied. See NewKernelInfoBuiltIn() - -"WxH[+X+Y][@><]:num, num, num ..." a kernel of size W by H, with W*H floating point numbers -following. the 'center' can be optionally be defined at +X+Y (such that +0+0 is top left corner). -If not defined the pixel in the center, for odd sizes, or to the immediate top or left of center -for even sizes is automatically selected. - -"num, num, num, num, ..." list of floating point numbers defining an 'old style' odd sized -square kernel. At least 9 values should be provided for a 3x3 square kernel, 25 for a 5x5 square -kernel, 49 for 7x7, etc. Values can be space or comma separated. This is not recommended. - -You can define a 'list of kernels' which can be used by some morphology operators A list is -defined as a semi-colon separated list kernels. - -" kernel ; kernel ; kernel ; " - -Any extra ';' characters, at start, end or between kernel defintions are simply ignored. - -The special flags will expand a single kernel, into a list of rotated kernels. A '@' flag will -expand a 3x3 kernel into a list of 45-degree cyclic rotations, while a '>' will generate a list -of 90-degree rotations. The '<' also exands using 90-degree rotates, but giving a 180-degree -reflected kernel before the +/- 90-degree rotations, which can be important for Thinning operations. - -Note that 'name' kernels will start with an alphabetic character while the new kernel specification -has a ':' character in its specification string. If neither is the case, it is assumed an old style -of a simple list of numbers generating a odd-sized square kernel has been given. -*/ -func NewKernelInfo(kernel string) (*KernelInfo, error) { - ckernel := C.CString(kernel) - defer C.free(unsafe.Pointer(ckernel)) - - var exc C.ExceptionInfo - kernel_info := C.AcquireKernelInfo(ckernel, &exc) - if err := checkExceptionInfo(&exc); err != nil { - return nil, err - } - - return newKernelInfo(kernel_info), nil -} - -// Create a kernel from a builtin in kernel. -// -// Returns an *ExceptionInfo on error -// -// See http://www.imagemagick.org/Usage/morphology/#kernel -// for examples. Currently the 'rotation' symbols are not supported. Example: -// kernel_info := NewKernelInfoBuiltIn(KERNEL_RING, "2,1") -func NewKernelInfoBuiltIn(typ KernelInfoType, kernel string) (*KernelInfo, error) { - var ginfo C.GeometryInfo - - ckernel := C.CString(kernel) - defer C.free(unsafe.Pointer(ckernel)) - - result := C.ParseGeometry(ckernel, &ginfo) - gflags := int(result) - - cleanGeometryInfo(typ, gflags, &ginfo) - - var exc C.ExceptionInfo - kernel_info := C.AcquireKernelBuiltIn(C.KernelInfoType(typ), &ginfo, &exc) - if err := checkExceptionInfo(&exc); err != nil { - return nil, err - } - - return newKernelInfo(kernel_info), nil -} - -// ScaleKernelInfo() scales the given kernel list by the given amount, with or without -// normalization of the sum of the kernel values (as per given flags). The exact behaviour -// of this function depends on the normalization type being used please see -// http://www.imagemagick.org/api/morphology.php#ScaleKernelInfo for details. -// -// Flag should be one of: -// KERNEL_NORMALIZE_NONE -// KERNEL_NORMALIZE_VALUE -// KERNEL_NORMALIZE_CORRELATE -// KERNEL_NORMALIZE_PERCENT -func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) { - C.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType)) - runtime.KeepAlive(ki) -} - -// cleanGeometryInfo peforms some tidy up of the geometry info for the kernel. -func cleanGeometryInfo(typ KernelInfoType, geometryFlags int, - geometryInfo *C.GeometryInfo) { - - // special handling of missing values in input string - switch typ { - - // Shape Kernel Defaults - case KERNEL_UNITY: - if (geometryFlags & WIDTHVALUE) == 0 { - geometryInfo.rho = 1.0 /* Default scale = 1.0, zero is valid */ - } - - case KERNEL_SQUARE, KERNEL_DIAMOND, KERNEL_OCTAGON, - KERNEL_DISK, KERNEL_PLUS, KERNEL_CROSS: - if (geometryFlags & HEIGHTVALUE) == 0 { - geometryInfo.sigma = 1.0 /* Default scale = 1.0, zero is valid */ - } - - case KERNEL_RING: - if (geometryFlags & XVALUE) == 0 { - geometryInfo.xi = 1.0 /* Default scale = 1.0, zero is valid */ - } - - case KERNEL_RECTANGLE: - // Rectangle - set size defaults - if (geometryFlags & WIDTHVALUE) == 0 { /* if no width then */ - geometryInfo.rho = geometryInfo.sigma /* then width = height */ - } - if geometryInfo.rho < 1.0 { /* if width too small */ - geometryInfo.rho = 3 /* then width = 3 */ - } - if geometryInfo.sigma < 1.0 { /* if height too small */ - geometryInfo.sigma = geometryInfo.rho /* then height = width */ - } - //TODO - casting shenanigans - //if ((geometryFlags & XVALUE) == 0) { /* center offset if not defined */ - // geometryInfo.xi = (double)(((ssize_t)geometryInfo.rho-1)/2); - //} - //if ((geometryFlags & YVALUE) == 0) { - // geometryInfo.psi = (double)(((ssize_t)geometryInfo.sigma-1)/2); - //} - - // Distance Kernel Defaults - case KERNEL_CHEBYSHEV, KERNEL_MANHATTAN, KERNEL_OCTAGONAL, KERNEL_EUCLIDEAN: - if (geometryFlags & HEIGHTVALUE) == 0 { /* no distance scale */ - geometryInfo.sigma = 100.0 /* default distance scaling */ - } - //TODO casting shenanigans - //else if ((flags & AspectValue ) != 0) { /* '!' flag */ - // geometryInfo.sigma = QuantumRange/(geometryInfo.sigma+1); /* maximum pixel distance */ - //} - //else if ((flags & PercentValue ) != 0) { /* '%' flag */ - // geometryInfo.sigma *= QuantumRange/100.0; /* percentage of color range */ - //} - - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info_type.go deleted file mode 100644 index 8c78b9d9..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_info_type.go +++ /dev/null @@ -1,49 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -type KernelInfoType int - -const ( - KERNEL_UNDEFINED KernelInfoType = C.UndefinedKernel /* equivalent to UnityKernel */ - KERNEL_UNITY KernelInfoType = C.UnityKernel /* The no-op or 'original image' kernel */ - KERNEL_GAUSSIAN KernelInfoType = C.GaussianKernel /* Convolution Kernels Gaussian Based */ - KERNEL_DOG KernelInfoType = C.DoGKernel - KERNEL_LOG KernelInfoType = C.LoGKernel - KERNEL_BLUR KernelInfoType = C.BlurKernel - KERNEL_COMET KernelInfoType = C.CometKernel - KERNEL_LAPLACIAN KernelInfoType = C.LaplacianKernel /* Convolution Kernels by Name */ - KERNEL_SOBEL KernelInfoType = C.SobelKernel - KERNEL_FREICHEN KernelInfoType = C.FreiChenKernel - KERNEL_ROBERTS KernelInfoType = C.RobertsKernel - KERNEL_PREWITT KernelInfoType = C.PrewittKernel - KERNEL_COMPASS KernelInfoType = C.CompassKernel - KERNEL_KIRSCH KernelInfoType = C.KirschKernel - KERNEL_DIAMOND KernelInfoType = C.DiamondKernel /* Shape Kernels */ - KERNEL_SQUARE KernelInfoType = C.SquareKernel - KERNEL_RECTANGLE KernelInfoType = C.RectangleKernel - KERNEL_OCTAGON KernelInfoType = C.OctagonKernel - KERNEL_DISK KernelInfoType = C.DiskKernel - KERNEL_PLUS KernelInfoType = C.PlusKernel - KERNEL_CROSS KernelInfoType = C.CrossKernel - KERNEL_RING KernelInfoType = C.RingKernel - KERNEL_PEAKS KernelInfoType = C.PeaksKernel /* Hit And Miss Kernels */ - KERNEL_EDGES KernelInfoType = C.EdgesKernel - KERNEL_CORNERS KernelInfoType = C.CornersKernel - KERNEL_DIAGONALS KernelInfoType = C.DiagonalsKernel - KERNEL_LINEENDS KernelInfoType = C.LineEndsKernel - KERNEL_LINEJUNCTIONS KernelInfoType = C.LineJunctionsKernel - KERNEL_RIDGES KernelInfoType = C.RidgesKernel - KERNEL_CONVEXHULL KernelInfoType = C.ConvexHullKernel - KERNEL_THINSE KernelInfoType = C.ThinSEKernel - KERNEL_SKELETON KernelInfoType = C.SkeletonKernel - KERNEL_CHEBYSHEV KernelInfoType = C.ChebyshevKernel /* Distance Measuring Kernels */ - KERNEL_MANHATTAN KernelInfoType = C.ManhattanKernel - KERNEL_OCTAGONAL KernelInfoType = C.OctagonalKernel - KERNEL_EUCLIDEAN KernelInfoType = C.EuclideanKernel - KERNEL_USERDEFINED KernelInfoType = C.UserDefinedKernel /* User Specified Kernel Array */ - KERNEL_BINOMIAL KernelInfoType = C.BinomialKernel -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_normalize_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_normalize_type.go deleted file mode 100644 index 328d9341..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/kernel_normalize_type.go +++ /dev/null @@ -1,28 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -type KernelNormalizeType int - -const ( - // The kernel is scaled directly using given scaling factor without change. - KERNEL_NORMALIZE_NONE KernelNormalizeType = 0 - - // Kernel normalization ('normalize_flags' given) is designed to ensure - // that any use of the kernel scaling factor with 'Convolve' or 'Correlate' - // morphology methods will fall into -1.0 to +1.0 range. - KERNEL_NORMALIZE_VALUE KernelNormalizeType = C.NormalizeValue - - // For special kernels designed for locating shapes using 'Correlate', (often - // only containing +1 and -1 values, representing foreground/brackground - // matching) a special normalization method is provided to scale the positive - // values separately to those of the negative values, so the kernel will be - // forced to become a zero-sum kernel better suited to such searches. - KERNEL_NORMALIZE_CORRELATE KernelNormalizeType = C.CorrelateNormalizeValue - - // Scale the kernel by a percent. - KERNEL_NORMALIZE_PERCENT KernelNormalizeType = C.PercentValue -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/line_cap.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/line_cap.go deleted file mode 100644 index 5245b449..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/line_cap.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type LineCap int - -const ( - LINE_CAP_UNDEFINED LineCap = C.UndefinedCap - LINE_CAP_BUTT LineCap = C.ButtCap - LINE_CAP_ROUND LineCap = C.RoundCap - LINE_CAP_SQUARE LineCap = C.SquareCap -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/line_join.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/line_join.go deleted file mode 100644 index abf99a58..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/line_join.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type LineJoin int - -const ( - LINE_JOIN_UNDEFINED LineJoin = C.UndefinedJoin - LINE_JOIN_MITER LineJoin = C.MiterJoin - LINE_JOIN_ROUND LineJoin = C.RoundJoin - LINE_JOIN_BEVEL LineJoin = C.BevelJoin -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_core_env.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_core_env.go deleted file mode 100644 index 03bb5a76..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_core_env.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "unsafe" -) - -func IsCoreInstantiated() bool { - return 1 == C.int(C.IsMagickCoreInstantiated()) -} - -func CoreInitialize(path string) { - cspath := C.CString(path) - defer C.free(unsafe.Pointer(cspath)) - C.MagickCoreGenesis(cspath, 0) -} - -func CoreTerminate() { - C.MagickCoreTerminus() -} - -func GetPrecision() int { - return int(C.GetMagickPrecision()) -} - -func SetPrecision(precision int) { - C.SetMagickPrecision(C.int(precision)) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_function.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_function.go deleted file mode 100644 index 1df484cb..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_function.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type MagickFunction int - -const ( - FUNCTION_UNDEFINED MagickFunction = C.UndefinedFunction - FUNCTION_POLYNOMIAL MagickFunction = C.PolynomialFunction - FUNCTION_SINUSOID MagickFunction = C.SinusoidFunction - FUNCTION_ARCSIN MagickFunction = C.ArcsinFunction - FUNCTION_ARCTAN MagickFunction = C.ArctanFunction -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_version.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_version.go deleted file mode 100644 index ea487d4a..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_version.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import "unsafe" - -// Returns the ImageMagick API copyright as a string constant. -func GetCopyright() string { - cstr := C.MagickGetCopyright() - return C.GoString(cstr) -} - -// Returns the ImageMagick home URL. -func GetHomeURL() string { - cstr := C.MagickGetHomeURL() - defer relinquishMemory(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Returns the ImageMagick package name as a string constant. -func GetPackageName() string { - cstr := C.MagickGetPackageName() - return C.GoString(cstr) -} - -// Returns the ImageMagick release date as a string constant. -func GetReleaseDate() string { - cstr := C.MagickGetReleaseDate() - return C.GoString(cstr) -} - -// Returns the ImageMagick quantum depth as a string constant. -func GetQuantumDepth() (string, uint) { - cst := C.size_t(0) - csq := C.MagickGetQuantumDepth(&cst) - return C.GoString(csq), uint(cst) -} - -// Returns the ImageMagick quantum range as a string constant. -func GetQuantumRange() (string, uint) { - cst := C.size_t(0) - csq := C.MagickGetQuantumRange(&cst) - return C.GoString(csq), uint(cst) -} - -// Returns the specified resource in megabytes. -func GetResource(rtype ResourceType) int64 { - return int64(C.MagickGetResource(C.ResourceType(rtype))) - -} - -// Returns the specified resource limit in megabytes. -func GetResourceLimit(rtype ResourceType) int64 { - return int64(C.MagickGetResourceLimit(C.ResourceType(rtype))) -} - -// Returns the ImageMagick API version as a string constant and as a number. -func GetVersion() (version string, nversion uint) { - cnver := C.size_t(0) - csver := C.MagickGetVersion(&cnver) - version = C.GoString(csver) - nversion = uint(cnver) - return -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand.go deleted file mode 100644 index 68cc8b3c..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand.go +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" - "runtime" - "sync" - "sync/atomic" - "unsafe" -) - -// This struct represents the MagickWand C API of ImageMagick -type MagickWand struct { - mw *C.MagickWand - init sync.Once -} - -func newMagickWand(cmw *C.MagickWand) *MagickWand { - mw := &MagickWand{mw: cmw} - runtime.SetFinalizer(mw, Destroy) - mw.IncreaseCount() - - return mw -} - -// Returns a wand required for all other methods in the API. A fatal exception is thrown if there is not enough memory to allocate the wand. -func NewMagickWand() *MagickWand { - return newMagickWand(C.NewMagickWand()) -} - -// Returns a wand with an image -func NewMagickWandFromImage(img *Image) *MagickWand { - ret := newMagickWand(C.NewMagickWandFromImage(img.img)) - runtime.KeepAlive(img) - return ret -} - -// Clear resources associated with the wand, leaving the wand blank, and ready to be used for a new set of images. -func (mw *MagickWand) Clear() { - C.ClearMagickWand(mw.mw) - runtime.KeepAlive(mw) -} - -// Makes an exact copy of the MagickWand object -func (mw *MagickWand) Clone() *MagickWand { - ret := newMagickWand(C.CloneMagickWand(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Deallocates memory associated with an MagickWand -func (mw *MagickWand) Destroy() { - if mw.mw == nil { - return - } - - mw.init.Do(func() { - mw.mw = C.DestroyMagickWand(mw.mw) - relinquishMemory(unsafe.Pointer(mw.mw)) - runtime.SetFinalizer(mw, nil) - mw.mw = nil - - mw.DecreaseCount() - }) -} - -// Returns true if the wand is a verified magick wand -func (mw *MagickWand) IsVerified() bool { - if mw.mw != nil { - return 1 == C.int(C.IsMagickWand(mw.mw)) - } - runtime.KeepAlive(mw) - return false -} - -// Increase MagickWand ref counter and set according "can`t be terminated status" -func (mw *MagickWand) IncreaseCount() { - atomic.AddInt64(&magickWandCounter, int64(1)) - unsetCanTerminate() -} - -// Decrease MagickWand ref counter and set according "can be terminated status" -func (mw *MagickWand) DecreaseCount() { - atomic.AddInt64(&magickWandCounter, int64(-1)) - setCanTerminate() -} - -// Returns the position of the iterator in the image list -func (mw *MagickWand) GetIteratorIndex() uint { - ret := uint(C.MagickGetIteratorIndex(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the value associated with the specified configure option -func (mw *MagickWand) QueryConfigureOption(option string) (string, error) { - csoption := C.CString(option) - defer C.free(unsafe.Pointer(csoption)) - availableOptions := mw.QueryConfigureOptions(option) - for _, availableOption := range availableOptions { - if availableOption == option { - return C.GoString(C.MagickQueryConfigureOption(csoption)), nil - } - } - return "", fmt.Errorf("Unknown option \"%s\"", option) -} - -// Returns any configure options that match the specified pattern (e.g. "*" for all). Options include NAME, VERSION, LIB_VERSION, etc -func (mw *MagickWand) QueryConfigureOptions(pattern string) (options []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - var num C.size_t - copts := C.MagickQueryConfigureOptions(cspattern, &num) - defer relinquishMemoryCStringArray(copts) - options = sizedCStringArrayToStringSlice(copts, num) - return -} - -// Returns a FontMetrics struct -func (mw *MagickWand) QueryFontMetrics(dw *DrawingWand, textLine string) *FontMetrics { - cstext := C.CString(textLine) - defer C.free(unsafe.Pointer(cstext)) - cdoubles := C.MagickQueryFontMetrics(mw.mw, dw.dw, cstext) - runtime.KeepAlive(mw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(cdoubles)) - doubles := sizedDoubleArrayToFloat64Slice(cdoubles, 13) - return NewFontMetricsFromArray(doubles) -} - -// Returns a FontMetrics struct related to the multiline text -func (mw *MagickWand) QueryMultilineFontMetrics(dw *DrawingWand, textParagraph string) *FontMetrics { - cstext := C.CString(textParagraph) - defer C.free(unsafe.Pointer(cstext)) - cdoubles := C.MagickQueryMultilineFontMetrics(mw.mw, dw.dw, cstext) - runtime.KeepAlive(mw) - runtime.KeepAlive(dw) - defer relinquishMemory(unsafe.Pointer(cdoubles)) - doubles := sizedDoubleArrayToFloat64Slice(cdoubles, 13) - return NewFontMetricsFromArray(doubles) -} - -// Returns any font that match the specified pattern (e.g. "*" for all) -func (mw *MagickWand) QueryFonts(pattern string) (fonts []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - var num C.size_t - copts := C.MagickQueryFonts(cspattern, &num) - defer relinquishMemoryCStringArray(copts) - fonts = sizedCStringArrayToStringSlice(copts, num) - return -} - -// Returns any supported image format that match the specified pattern (e.g. "*" for all) -func (mw *MagickWand) QueryFormats(pattern string) (formats []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - var num C.size_t - copts := C.MagickQueryFormats(cspattern, &num) - defer relinquishMemoryCStringArray(copts) - formats = sizedCStringArrayToStringSlice(copts, num) - return -} - -// This method resets the wand iterator. -// It is typically used either before iterating though images, or before calling specific methods such as AppendImages() -// to append all images together. -// Afterward you can use NextImage() to iterate over all the images in a wand container, starting with the first image. -// Using this before AddImages() or ReadImages() will cause new images to be inserted between the first and second image. -func (mw *MagickWand) ResetIterator() { - C.MagickResetIterator(mw.mw) - runtime.KeepAlive(mw) -} - -// This method sets the wand iterator to the first image. -// After using any images added to the wand using AddImage() or ReadImage() will be prepended before any image in the wand. -// Also the current image has been set to the first image (if any) in the MagickWand. Using NextImage() will then set the -// current image to the second image in the list (if present). -// This operation is similar to ResetIterator() but differs in how AddImage(), ReadImage(), and NextImage() behaves afterward. -func (mw *MagickWand) SetFirstIterator() { - C.MagickSetFirstIterator(mw.mw) - runtime.KeepAlive(mw) -} - -// This method set the iterator to the given position in the image list specified with the index parameter. -// A zero index will set the first image as current, and so on. Negative indexes can be used to specify an -// image relative to the end of the images in the wand, with -1 being the last image in the wand. -// If the index is invalid (range too large for number of images in wand) the function will return false. -// In that case the current image will not change. -// After using any images added to the wand using AddImage() or ReadImage() will be added after the image indexed, -// regardless of if a zero (first image in list) or negative index (from end) is used. -// Jumping to index 0 is similar to ResetIterator() but differs in how NextImage() behaves afterward. -func (mw *MagickWand) SetIteratorIndex(index int) bool { - ret := 1 == C.int(C.MagickSetIteratorIndex(mw.mw, C.ssize_t(index))) - runtime.KeepAlive(mw) - return ret -} - -// SetLastIterator() sets the wand iterator to the last image. -// The last image is actually the current image, and the next use of PreviousImage() will not change this allowing this function -// to be used to iterate over the images in the reverse direction. In this sense it is more like ResetIterator() than SetFirstIterator(). -// Typically this function is used before AddImage(), ReadImage() functions to ensure new images are appended to the very end of wand's image list. -func (mw *MagickWand) SetLastIterator() { - C.MagickSetLastIterator(mw.mw) - runtime.KeepAlive(mw) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_env.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_env.go deleted file mode 100644 index e6ac602b..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_env.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import ( - "runtime" - "sync" - "sync/atomic" -) - -var ( - initOnce sync.Once - terminateOnce *sync.Once - - // Indicates that terminate method can be called (there are no any ImageMagick objects) - canTerminate = make(chan struct{}, 1) - - envSemaphore = make(chan struct{}, 1) - - // Ref counters - magickWandCounter int64 - drawingWandCounter int64 - pixelIteratorCounter int64 - pixelWandCounter int64 -) - -// Initializes the MagickWand environment -func Initialize() { - envSemaphore <- struct{}{} - defer func() { - <-envSemaphore - }() - - initOnce.Do(func() { - C.MagickWandGenesis() - terminateOnce = &sync.Once{} - setCanTerminate() - }) -} - -// Terminates the MagickWand environment -// wait until all imageMagick objects destroyed -func Terminate() { - envSemaphore <- struct{}{} - defer func() { - <-envSemaphore - }() - - if terminateOnce != nil { - terminateOnce.Do(func() { - runtime.GC() - terminate() - }) - } -} - -// Guarantees that C.MagickWandTerminus run after all ImageMagick objects are destroyed -// or we got the panic from C.MagickWandTerminus -func terminate() { - <-canTerminate - C.MagickWandTerminus() - initOnce = sync.Once{} -} - -// Set status "terminate can be called" -func setCanTerminate() { - if isImageMagickCleaned() { - select { - case canTerminate <- struct{}{}: - // Now we can terminate - default: - // Nothing to do - } - } -} - -// Set status "terminate can`t be called" -func unsetCanTerminate() { - select { - case <-canTerminate: - // Now we can`t terminate - default: - // Nothing to do - } -} - -// Check are all IM objects are collected by GC -func isImageMagickCleaned() bool { - if atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 { - return false - } - - return true -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_exception.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_exception.go deleted file mode 100644 index e9961b4e..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_exception.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" - "runtime" - "unsafe" -) - -type MagickWandException struct { - kind ExceptionType - description string -} - -func (mwe *MagickWandException) Error() string { - return fmt.Sprintf("%s: %s", mwe.kind.String(), mwe.description) -} - -// Clears any exceptions associated with the wand -func (mw *MagickWand) clearException() bool { - return 1 == C.int(C.MagickClearException(mw.mw)) -} - -// Returns the kind, reason and description of any error that occurs when using other methods in this API -func (mw *MagickWand) GetLastError() error { - var et C.ExceptionType - csdescription := C.MagickGetException(mw.mw, &et) - defer relinquishMemory(unsafe.Pointer(csdescription)) - if ExceptionType(et) != EXCEPTION_UNDEFINED { - mw.clearException() - return &MagickWandException{ExceptionType(C.int(et)), C.GoString(csdescription)} - } - runtime.KeepAlive(mw) - return nil -} - -func (mw *MagickWand) getLastErrorIfFailed(ok C.MagickBooleanType) error { - if C.int(ok) == 0 { - return mw.GetLastError() - } else { - return nil - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_image.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_image.go deleted file mode 100644 index 295e6c42..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_image.go +++ /dev/null @@ -1,2962 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -#include -#include - -// declare symbols only defined in C source and not in header -WandExport MagickBooleanType MagickSetImageMask( - MagickWand *wand, const PixelMask type, const MagickWand *clip_mask -); -*/ -import "C" - -import ( - "errors" - "fmt" - "os" - "reflect" - "runtime" - "syscall" - "unsafe" -) - -func checkColsRows(cols, rows uint) error { - if cols == 0 { - return errors.New("bad parameter value: cols=0") - } - if rows == 0 { - return errors.New("bad parameter value: rows=0") - } - return nil -} - -// Returns the current image from the magick wand -func (mw *MagickWand) GetImageFromMagickWand() *Image { - return &Image{C.GetImageFromMagickWand(mw.mw)} -} - -// Adaptively blurs the image by blurring less intensely near image edges and -// more intensely far from edges. We blur the image with a Gaussian operator of -// the given radius and standard deviation (sigma). For reasonable results, -// radius should be larger than sigma. Use a radius of 0 and -// AdaptiveBlurImage() selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel -// -// sigma: the standard deviation of the Gaussian, in pixels -// -func (mw *MagickWand) AdaptiveBlurImage(radius, sigma float64) error { - ok := C.MagickAdaptiveBlurImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Adaptively resize image with data dependent triangulation -func (mw *MagickWand) AdaptiveResizeImage(cols, rows uint) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickAdaptiveResizeImage(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Adaptively sharpens the image by sharpening more intensely near image edges -// and less intensely far from edges. We sharpen the image with a Gaussian -// operator of the given radius and standard deviation (sigma). For reasonable -// results, radius should be larger than sigma. Use a radius of 0 and -// AdaptiveSharpenImage() selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -func (mw *MagickWand) AdaptiveSharpenImage(radius, sigma float64) error { - ok := C.MagickAdaptiveSharpenImage(mw.mw, C.double(radius), C.double(sigma)) - runtime.KeepAlive(mw) - return mw.getLastErrorIfFailed(ok) -} - -// Selects an individual threshold for each pixel based on the range of -// intensity values in its local neighborhood. This allows for thresholding -// of an image whose global intensity histogram doesn't contain distinctive -// peaks. -func (mw *MagickWand) AdaptiveThresholdImage(width, height uint, offset float64) error { - ok := C.MagickAdaptiveThresholdImage(mw.mw, C.size_t(width), C.size_t(height), C.double(offset)) - return mw.getLastErrorIfFailed(ok) -} - -// Adds a clone of the images from the second wand and inserts them into the -// first wand. Use SetLastIterator(), to append new images into an existing -// wand, current image will be set to last image so later adds with also be -// appened to end of wand. Use SetFirstIterator() to prepend new images into -// wand, any more images added will also be prepended before other images in -// the wand. However the order of a list of new images will not change. -// Otherwise the new images will be inserted just after the current image, and -// any later image will also be added after this current image but before the -// previously added images. Caution is advised when multiple image adds are -// inserted into the middle of the wand image list. -func (mw *MagickWand) AddImage(wand *MagickWand) error { - ok := C.MagickAddImage(mw.mw, wand.mw) - runtime.KeepAlive(wand) - return mw.getLastErrorIfFailed(ok) -} - -// Adds random noise to the image -func (mw *MagickWand) AddNoiseImage(noiseType NoiseType, offset float64) error { - ok := C.MagickAddNoiseImage(mw.mw, C.NoiseType(noiseType), C.double(offset)) - return mw.getLastErrorIfFailed(ok) -} - -// Transforms an image as dictaded by the affine matrix of the drawing wand -func (mw *MagickWand) AffineTransformImage(drawingWand *DrawingWand) error { - ok := C.MagickAffineTransformImage(mw.mw, drawingWand.dw) - runtime.KeepAlive(drawingWand) - return mw.getLastErrorIfFailed(ok) -} - -// Annotates an image with text -// -// x: ordinate to left of text -// -// y: ordinate to text baseline -// -// angle: rotate text relative to this angle -// -func (mw *MagickWand) AnnotateImage(drawingWand *DrawingWand, x, y, angle float64, text string) error { - cstext := C.CString(text) - defer C.free(unsafe.Pointer(cstext)) - ok := C.MagickAnnotateImage(mw.mw, drawingWand.dw, C.double(x), C.double(y), C.double(angle), cstext) - runtime.KeepAlive(mw) - runtime.KeepAlive(drawingWand) - return mw.getLastErrorIfFailed(ok) -} - -// Animates an image or image sequence -func (mw *MagickWand) AnimateImages(server string) error { - csserver := C.CString(server) - defer C.free(unsafe.Pointer(csserver)) - ok := C.MagickAnimateImages(mw.mw, csserver) - return mw.getLastErrorIfFailed(ok) -} - -// Append the images in a wand from the current image onwards, creating a new -// wand with the single image result. This is affected by the gravity and -// background setting of the first image. Typically you would call either -// ResetIterator() or SetFirstImage() before calling this function to ensure -// that all the images in the wand's image list will be appended together. -// By default, images are stacked left-to-right. Set topToBottom to true to -// stack them top-to-bottom. -func (mw *MagickWand) AppendImages(topToBottom bool) *MagickWand { - ret := newMagickWand(C.MagickAppendImages(mw.mw, b2i(topToBottom))) - runtime.KeepAlive(mw) - return ret -} - -// Extracts the 'mean' from the image and adjust the image to try make set -// it's gamma appropriatally -func (mw *MagickWand) AutoGammaImage() error { - ok := C.MagickAutoGammaImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Adjust the levels of a particular image by scaling the minimum and maximum -// values to the full quantum range. -func (mw *MagickWand) AutoLevelImage() error { - ok := C.MagickAutoLevelImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// This is like ThresholdImage() but forces all pixels below the threshold -// into black while leaving all pixels above the threshold unchanged. -func (mw *MagickWand) BlackThresholdImage(threshold *PixelWand) error { - ok := C.MagickBlackThresholdImage(mw.mw, threshold.pw) - runtime.KeepAlive(threshold) - return mw.getLastErrorIfFailed(ok) -} - -// Mutes the colors of the image to simulate a scene at nighttime in the -// moonlight. -func (mw *MagickWand) BlueShiftImage(factor float64) error { - ok := C.MagickBlueShiftImage(mw.mw, C.double(factor)) - return mw.getLastErrorIfFailed(ok) -} - -// Blurs an image. We convolve the image with a gaussian operator of the -// given radius and standard deviation (sigma). For reasonable results, the -// radius should be larger than sigma. Use a radius of 0 and BlurImage() -// selects a suitable radius for you. -// -// radius: the radius of the, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the, in pixels -// -func (mw *MagickWand) BlurImage(radius, sigma float64) error { - ok := C.MagickBlurImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Surrounds the image with a border of the color defined by the bordercolor -// pixel wand. -func (mw *MagickWand) BorderImage(borderColor *PixelWand, width, height uint, - compose CompositeOperator) error { - - ok := C.MagickBorderImage(mw.mw, borderColor.pw, - C.size_t(width), C.size_t(height), C.CompositeOperator(compose)) - - runtime.KeepAlive(borderColor) - return mw.getLastErrorIfFailed(ok) -} - -// Use this to change the brightness and/or contrast of an image. It converts -// the brightness and contrast. -// -// brighness: the brightness percent (-100 .. 100) -// -// contrast: the brightness percent (-100 .. 100) -// -func (mw *MagickWand) BrightnessContrastImage(brightness, contrast float64) error { - ok := C.MagickBrightnessContrastImage(mw.mw, C.double(brightness), C.double(contrast)) - return mw.getLastErrorIfFailed(ok) -} - -// Simulates a charcoal drawing -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel -// -// sigma: the standard deviation of the Gaussian, in pixels -// -func (mw *MagickWand) CharcoalImage(radius, sigma float64) error { - ok := C.MagickCharcoalImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Removes a region of an image and collapses the image to occupy the removed -// portion. -// -// width, height: the region width and height -// -// x, y: the region x and y offsets -// -func (mw *MagickWand) ChopImage(width, height uint, x, y int) error { - ok := C.MagickChopImage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Restricts the color range from 0 to the quantum depth -func (mw *MagickWand) ClampImage() error { - ok := C.MagickClampImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Clips along the first path from the 8BIM profile, if present -func (mw *MagickWand) ClipImage() error { - ok := C.MagickClipImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Clips along the named paths from the 8BOM profile, if present. Later -// operations take effect inside the path. Id may be a number if preceded with -// #, to work on a numbered path, e.g. "#1" to use the first path. -// pathname: name of clipping path resource. If name is preceded by #, use -// clipping path numbered by name. -// -// inside: if true, later operations take effect inside clipping path. Otherwise -// later operations take effect outside clipping path. -func (mw *MagickWand) ClipImagePath(pathname string, inside bool) error { - cspathname := C.CString(pathname) - defer C.free(unsafe.Pointer(cspathname)) - ok := C.MagickClipImagePath(mw.mw, cspathname, b2i(inside)) - return mw.getLastErrorIfFailed(ok) -} - -// Replaces colors in the image from a color lookup table -func (mw *MagickWand) ClutImage(clut *MagickWand, interp PixelInterpolateMethod) error { - ok := C.MagickClutImage(mw.mw, clut.mw, C.PixelInterpolateMethod(interp)) - runtime.KeepAlive(clut) - return mw.getLastErrorIfFailed(ok) -} - -// Composites a set of images while respecting any page offsets and disposal -// methods. GIF, MIFF, and MNG animation sequences typically start with an -// image background and each subsequent image varies in size and offset. -// CoalesceImages() returns a new sequence where each image in the sequence -// is the same size as the first and composited with the next image in the -// sequence. -func (mw *MagickWand) CoalesceImages() *MagickWand { - return newMagickWand(C.MagickCoalesceImages(mw.mw)) -} - -// Accepts a lightweight Color Correction Collection (CCC) file which solely -// contains one or more color corrections and applies the color correction to -// the image. Here is a sample CCC file content: -// -// -// -// -// 0.9 1.2 0.5 -// 0.4 -0.5 0.6 -// 1.0 0.8 1.5 -// -// -// 0.85 -// -// -// -// -func (mw *MagickWand) ColorDecisionListImage(cccXML string) error { - cscccXML := C.CString(cccXML) - defer C.free(unsafe.Pointer(cscccXML)) - ok := C.MagickColorDecisionListImage(mw.mw, cscccXML) - return mw.getLastErrorIfFailed(ok) -} - -// Blends the fill color with each pixel in the image -func (mw *MagickWand) ColorizeImage(colorize, opacity *PixelWand) error { - ok := C.MagickColorizeImage(mw.mw, colorize.pw, opacity.pw) - runtime.KeepAlive(colorize) - runtime.KeepAlive(opacity) - return mw.getLastErrorIfFailed(ok) -} - -// Apply color transformation to an image. The method permits saturation -// changes, hue rotation, luminance to alpha, and various other effects. -// Although variable-sized transformation matrices can be used, typically one -// uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with -// offsets). The matrix is similar to those used by Adobe Flash except offsets -// are in column 6 rather than 5 (in support of CMYKA images) and offsets are -// normalized (divide Flash offset by 255). -func (mw *MagickWand) ColorMatrixImage(colorMatrix *KernelInfo) error { - ok := C.MagickColorMatrixImage(mw.mw, colorMatrix.info) - runtime.KeepAlive(colorMatrix) - return mw.getLastErrorIfFailed(ok) -} - -// Combines one or more images into a single image. The grayscale value of -// the pixels of each image in the sequence is assigned in order to the -// specified channels of the combined image. The typical ordering would be -// image 1 => Red, 2 => Green, 3 => Blue, etc. -func (mw *MagickWand) CombineImages(cs ColorspaceType) *MagickWand { - ret := newMagickWand(C.MagickCombineImages(mw.mw, C.ColorspaceType(cs))) - runtime.KeepAlive(mw) - return ret -} - -// Adds a comment to your image -func (mw *MagickWand) CommentImage(comment string) error { - cscomment := C.CString(comment) - defer C.free(unsafe.Pointer(cscomment)) - ok := C.MagickCommentImage(mw.mw, cscomment) - return mw.getLastErrorIfFailed(ok) -} - -// Compares each image with the next in a sequence and returns the maximum -// bounding region of any pixel differences it discovers. -func (mw *MagickWand) CompareImagesLayers(method LayerMethod) *MagickWand { - return newMagickWand(C.MagickCompareImagesLayers(mw.mw, C.LayerMethod(method))) -} - -// CompareImages() compares an image to a reconstructed image and returns the -// specified difference image. Returns the new MagickWand and the computed -// distortion between the images -func (mw *MagickWand) CompareImages(reference *MagickWand, metric MetricType) (wand *MagickWand, distortion float64) { - cmw := C.MagickCompareImages(mw.mw, reference.mw, C.MetricType(metric), (*C.double)(&distortion)) - wand = newMagickWand(cmw) - runtime.KeepAlive(mw) - runtime.KeepAlive(reference) - return -} - -// Composite one image onto another at the specified offset. -// source: The magick wand holding source image. -// compose: This operator affects how the composite is applied to the image. -// The default is Over. -// -// x: the column offset of the composited image. -// -// y: the row offset of the composited image. -// -func (mw *MagickWand) CompositeImage(source *MagickWand, - compose CompositeOperator, clipToSelf bool, x, y int) error { - - var clip C.MagickBooleanType = 0 - if clipToSelf { - clip = 1 - } - - ok := C.MagickCompositeImage(mw.mw, source.mw, - C.CompositeOperator(compose), clip, - C.ssize_t(x), C.ssize_t(y)) - - runtime.KeepAlive(source) - return mw.getLastErrorIfFailed(ok) -} - -// Composite one image onto another at the specified offset. -// source: The magick wand holding source image. -// compose: This operator affects how the composite is applied to the image. -// The default is Over. -// gravity : positioning gravity. -// -func (mw *MagickWand) CompositeImageGravity(source *MagickWand, compose CompositeOperator, gravity GravityType) error { - ok := C.MagickCompositeImageGravity(mw.mw, source.mw, C.CompositeOperator(compose), C.GravityType(gravity)) - runtime.KeepAlive(source) - return mw.getLastErrorIfFailed(ok) -} - -// Composite the images in the source wand over the images in the destination -// wand in sequence, starting with the current image in both lists. Each layer -// from the two image lists are composted together until the end of one of the -// image lists is reached. The offset of each composition is also adjusted to -// match the virtual canvas offsets of each layer. As such the given offset is -// relative to the virtual canvas, and not the actual image. -// Composition uses given x and y offsets, as the 'origin' location of the -// source images virtual canvas (not the real image) allowing you to compose a -// list of 'layer images' into the destination images. This makes it well -// suitable for directly composing 'Clears Frame Animations' or 'Coaleased -// Animations' onto a static or other 'Coaleased Animation' destination image -// list. GIF disposal handling is not looked at. Special case: If one of the -// image sequences is the last image (just a single image remaining), that -// image is repeatally composed with all the images in the other image list. -// Either the source or destination lists may be the single image, for this -// situation. In the case of a single destination image (or last image given), -// that image will ve cloned to match the number of images remaining in the -// source image list. This is equivelent to the "-layer Composite" Shell API -// operator. -// source: the wand holding the source images -// -// compose, x, y: composition arguments -// -func (mw *MagickWand) CompositeLayers(source *MagickWand, compose CompositeOperator, x, y int) error { - ok := C.MagickCompositeLayers(mw.mw, source.mw, C.CompositeOperator(compose), C.ssize_t(x), C.ssize_t(y)) - runtime.KeepAlive(source) - return mw.getLastErrorIfFailed(ok) -} - -// Enhances the intensity differences between the lighter and darker elements -// of the image. Set sharpen to a value other than 0 to increase the image -// contrast otherwise the contrast is reduced. -// -// sharpen: increase or decrease image contrast -// -func (mw *MagickWand) ContrastImage(sharpen bool) error { - ok := C.MagickContrastImage(mw.mw, b2i(sharpen)) - return mw.getLastErrorIfFailed(ok) -} - -// Enhances the contrast of a color image by adjusting the pixels color to -// span the entire range of colors available. You can also reduce the -// influence of a particular channel with a gamma value of 0. -func (mw *MagickWand) ContrastStretchImage(blackPoint, whitePoint float64) error { - ok := C.MagickContrastStretchImage(mw.mw, C.double(blackPoint), C.double(whitePoint)) - return mw.getLastErrorIfFailed(ok) -} - -// Applies a custom convolution kernel to the image. -// -// kernel: KernelInfo -// -func (mw *MagickWand) ConvolveImage(kernel *KernelInfo) error { - ok := C.MagickConvolveImage(mw.mw, kernel.info) - runtime.KeepAlive(mw) - runtime.KeepAlive(kernel) - return mw.getLastErrorIfFailed(ok) -} - -// Extracts a region of the image -func (mw *MagickWand) CropImage(width, height uint, x, y int) error { - ok := C.MagickCropImage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - runtime.KeepAlive(mw) - return mw.getLastErrorIfFailed(ok) -} - -// CropImageToTiles crops a single image, into a possible list of tiles. -// This may include a single sub-region of the image. This basically applies -// all the normal geometry flags for Crop. -// The new cropped image replaces the current image. -func (mw *MagickWand) CropImageToTiles(cropGeom string) error { - var exc *C.ExceptionInfo = C.AcquireExceptionInfo() - defer C.DestroyExceptionInfo(exc) - - cstr := C.CString(cropGeom) - defer C.free(unsafe.Pointer(cstr)) - - img := mw.GetImageFromMagickWand() - newImg := C.CropImageToTiles(img.img, cstr, exc) - - if exc != nil { - err := newExceptionInfo(exc) - if err.IsSet() { - return err - } - } - - defer C.MagickDestroyImage(newImg) - - newWand := NewMagickWandFromImage(&Image{newImg}) - defer newWand.Destroy() - - if err := mw.AddImage(newWand); err != nil { - return fmt.Errorf("error replacing image: %v", err) - } - - mw.PreviousImage() - - if err := mw.RemoveImage(); err != nil { - return fmt.Errorf("error removing current image: %v", err) - } - - runtime.KeepAlive(mw) - runtime.KeepAlive(img) - - return nil -} - -// Displaces an Image's colormap by a given number of positions. If you cycle -// the colormap a number of times you can produce a psychodelic effect. -func (mw *MagickWand) CycleColormapImage(displace int) error { - ok := C.MagickCycleColormapImage(mw.mw, C.ssize_t(displace)) - runtime.KeepAlive(mw) - return mw.getLastErrorIfFailed(ok) -} - -// Adds an image to the wand comprised of the pixel data you supply. The pixel -// data must be in scanline order top-to-bottom. -// -// stype: Define the data type of the pixels. Float and double types are -// expected to be normalized [0..1] otherwise [0..QuantumRange]. -// -// pmap: This string reflects the expected ordering of the pixel array. It can -// be any combination or order of R = red, G = green, B = blue, A = alpha -// (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, -// M = magenta, K = black, I = intensity (for grayscale), P = pad. -// -// pixels: This array of values contain the pixel components as defined by the -// type. -// -func (mw *MagickWand) ConstituteImage(cols, rows uint, pmap string, stype StorageType, pixels interface{}) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - cspmap := C.CString(pmap) - defer C.free(unsafe.Pointer(cspmap)) - ptr, calculatedStype, err := pixelInterfaceToPtr(pixels) - if err != nil { - return err - } - if stype == PIXEL_UNDEFINED { - stype = calculatedStype - } - ok := C.MagickConstituteImage(mw.mw, C.size_t(cols), C.size_t(rows), cspmap, C.StorageType(stype), ptr) - return mw.getLastErrorIfFailed(ok) -} - -// Converts cipher pixels to plain pixels -func (mw *MagickWand) DecipherImage(passphrase string) error { - cspassphrase := C.CString(passphrase) - defer C.free(unsafe.Pointer(cspassphrase)) - ok := C.MagickDecipherImage(mw.mw, cspassphrase) - runtime.KeepAlive(mw) - return mw.getLastErrorIfFailed(ok) -} - -// Compares each image with the next in a sequence and returns the maximum -// bouding region of any pixel differences it discovers. -func (mw *MagickWand) DeconstructImages() *MagickWand { - ret := newMagickWand(C.MagickDeconstructImages(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Removes skew from the image. Skew is an artifact that occurs in scanned -// images because of the camera being misaligned, imperfections in the -// scanning or surface, or simply because the paper was not placed completely -// flat when scanned. -// threshold: separate background from foreground -func (mw *MagickWand) DeskewImage(threshold float64) error { - ok := C.MagickDeskewImage(mw.mw, C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Reduces the speckle noise in an image while perserving the edges of the -// original image. -func (mw *MagickWand) DespeckleImage() error { - ok := C.MagickDespeckleImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Dereferences an image, deallocating memory associated with the image if the -// reference count becomes zero. -func (mw *MagickWand) DestroyImage(img *Image) *Image { - ret := &Image{C.MagickDestroyImage(img.img)} - runtime.KeepAlive(mw) - runtime.KeepAlive(img) - return ret -} - -// Displays and image -func (mw *MagickWand) DisplayImage(server string) error { - cstring := C.CString(server) - defer C.free(unsafe.Pointer(cstring)) - ok := C.MagickDisplayImage(mw.mw, cstring) - return mw.getLastErrorIfFailed(ok) -} - -// Displays and image or image sequence -func (mw *MagickWand) DisplayImages(server string) error { - cstring := C.CString(server) - defer C.free(unsafe.Pointer(cstring)) - ok := C.MagickDisplayImages(mw.mw, cstring) - return mw.getLastErrorIfFailed(ok) -} - -// DistortImage() distorts an image using various distortion methods, by -// mapping color lookups of the source image to a new destination image usally -// of the same size as the source image, unless 'bestfit' is set to true. If -// 'bestfit' is enabled, and distortion allows it, the destination image is -// adjusted to ensure the whole source 'image' will just fit within the final -// destination image, which will be sized and offset accordingly. Also in many -// cases the virtual offset of the source image will be taken into account in -// the mapping. -// -// method: the method of image distortion. ArcDistortion always ignores the -// source image offset, and always 'bestfit' the destination image with the -// top left corner offset relative to the polar mapping center. Bilinear has -// no simple inverse mapping so it does not allow 'bestfit' style of image -// distortion. Affine, Perspective, and Bilinear, do least squares fitting of -// the distortion when more than the minimum number of control point pairs are -// provided. Perspective, and Bilinear, falls back to a Affine distortion when -// less that 4 control point pairs are provided. While Affine distortions let -// you use any number of control point pairs, that is Zero pairs is a no-Op -// (viewport only) distortion, one pair is a translation and two pairs of -// control points do a scale-rotate-translate, without any shearing. -// -// args: the arguments for this distortion method. -// -// bestfit: Attempt to resize destination to fit distorted source. -// -func (mw *MagickWand) DistortImage(method DistortImageMethod, args []float64, bestfit bool) error { - ok := C.MagickDistortImage(mw.mw, C.DistortMethod(method), C.size_t(len(args)), (*C.double)(&args[0]), b2i(bestfit)) - return mw.getLastErrorIfFailed(ok) -} - -// Renders the drawing wand on the current image -func (mw *MagickWand) DrawImage(drawingWand *DrawingWand) error { - ok := C.MagickDrawImage(mw.mw, drawingWand.dw) - runtime.KeepAlive(drawingWand) - return mw.getLastErrorIfFailed(ok) -} - -// Enhance edges within the image with a convolution filter of the given -// radius. Use a radius of 0 and Edge() selects a suitable radius for you. -// -// radius: the radius of the pixel neighborhood -// -func (mw *MagickWand) EdgeImage(radius float64) error { - ok := C.MagickEdgeImage(mw.mw, C.double(radius)) - return mw.getLastErrorIfFailed(ok) -} - -// Returns a grayscale image with a three-dimensional effect. We convolve the -// image with a Gaussian operator of the given radius and standard deviation -// (sigma). For reasonable results, radius should be larger than sigma. Use a -// radius of 0 and Emboss() selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel -// -// sigma: the standard deviation of the Gaussian, in pixels -// -func (mw *MagickWand) EmbossImage(radius, sigma float64) error { - ok := C.MagickEmbossImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Converts plain pixels to cipher pixels -func (mw *MagickWand) EncipherImage(passphrase string) error { - cspassphrase := C.CString(passphrase) - defer C.free(unsafe.Pointer(cspassphrase)) - ok := C.MagickEncipherImage(mw.mw, cspassphrase) - return mw.getLastErrorIfFailed(ok) -} - -// Applies a digital filter that improves the quality of a noisy image -func (mw *MagickWand) EnhanceImage() error { - ok := C.MagickEnhanceImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Equalizes the image histogram. -func (mw *MagickWand) EqualizeImage() error { - ok := C.MagickEqualizeImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Applys an arithmetic, relational, or logical expression to an image. -// Use these operators to lighten or darken an image, to increase or -// decrease contrast in an image, or to produce the "negative" of an image. -func (mw *MagickWand) EvaluateImage(op EvaluateOperator, value float64) error { - ok := C.MagickEvaluateImage(mw.mw, C.MagickEvaluateOperator(op), C.double(value)) - return mw.getLastErrorIfFailed(ok) -} - -// Applys an arithmetic, relational, or logical expression to an image. -// Use these operators to lighten or darken an image, to increase or -// decrease contrast in an image, or to produce the "negative" of an image. -func (mw *MagickWand) EvaluateImages(op EvaluateOperator) error { - C.MagickEvaluateImages(mw.mw, C.MagickEvaluateOperator(op)) - return mw.GetLastError() -} - -// Extracts pixel data from an image and returns it to you. -// -// x, y, cols, rows: These values define the perimeter of a region of -// pixels you want to extract. -// -// map: This string reflects the expected ordering of the pixel array. It can -// be any combination or order of R = red, G = green, B = blue, A = alpha -// (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, -// M = magenta, K = black, I = intensity (for grayscale), P = pad. -// -// stype: Define the data type of the pixels. Float and double types are -// expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose from -// these types: CharPixel, DoublePixel, FloatPixel, IntegerPixel, LongPixel, -// QuantumPixel, or ShortPixel. -// -// -// StorageType defines the underlying slice type of the returned interface{}: -// PIXEL_CHAR => []byte -// PIXEL_DOUBLE => []float64 -// PIXEL_FLOAT => []float32 -// PIXEL_SHORT => []int16 -// PIXEL_LONG => []int32 -// PIXEL_LONGLONG => []int64 -// PIXEL_QUANTUM => []int64 -// -// Example: -// -// val, err := wand.ExportImagePixels(0, 0, 512, 512, "RGB", PIXEL_FLOAT) -// if err != nil { -// panic(err.Error()) -// } -// floatPixels := val.([]float32) -// -func (mw *MagickWand) ExportImagePixels(x, y int, cols, rows uint, - pmap string, stype StorageType) (interface{}, error) { - if len(pmap) == 0 { - return nil, errors.New("zero-length pmap not permitted") - } - - if x < 0 || uint(x) > mw.GetImageWidth() || - y < 0 || uint(y) > mw.GetImageHeight() || - cols == 0 || rows == 0 { - - return nil, errors.New("Args x, y, cols, and rows produces an invalid region <= 0") - } - - maplen := int(cols) * int(rows) * len(pmap) - if maplen <= 0 { - return nil, errors.New("Args cols and rows produces an invalid region <= 0") - } - - var ( - pixel_iface interface{} - ptr unsafe.Pointer - ) - - switch stype { - - case PIXEL_CHAR: - pixels := make([]byte, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - case PIXEL_DOUBLE: - pixels := make([]float64, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - case PIXEL_FLOAT: - pixels := make([]float32, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - case PIXEL_SHORT: - pixels := make([]int16, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - case PIXEL_LONG: - pixels := make([]int32, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - case PIXEL_LONGLONG, PIXEL_QUANTUM: - pixels := make([]int64, maplen) - pixel_iface = reflect.ValueOf(pixels).Interface() - ptr = unsafe.Pointer(&pixels[0]) - - default: - return nil, errors.New("StorageType is not valid for this operation") - - } - - cspmap := C.CString(pmap) - defer C.free(unsafe.Pointer(cspmap)) - - ok := C.MagickExportImagePixels(mw.mw, - C.ssize_t(x), C.ssize_t(y), - C.size_t(cols), C.size_t(rows), - cspmap, - C.StorageType(stype), - ptr) - - return pixel_iface, mw.getLastErrorIfFailed(ok) -} - -// Extends the image as defined by the geometry, gravitt, and wand background -// color. Set the (x,y) offset of the geometry to move the original wand -// relative to the extended wand. -// -// width: the region width. -// -// height: the region height. -// -// x: the region x offset. -// -// y: the region y offset. -// -func (mw *MagickWand) ExtentImage(width, height uint, x, y int) error { - ok := C.MagickExtentImage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a vertical mirror image by reflecting the pixels around the central -// x-axis. -func (mw *MagickWand) FlipImage() error { - ok := C.MagickFlipImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Changes the color value of any pixel that matches target and is an immediate -// neighbor. If the method FillToBorderMethod is specified, the color value is -// changed for any neighbor pixel that does not match the bordercolor member -// of image. -// -// fill: the floodfill color pixel wand. -// -// fuzz: By default target must match a particular pixel color exactly. -// -// However, in many cases two colors may differ by a small amount. The fuzz -// member of image defines how much tolerance is acceptable to consider two -// colors as the same. For example, set fuzz to 10 and the color red at -// intensities of 100 and 102 respectively are now interpreted as the same -// color for the purposes of the floodfill. -// -// bordercolor: the border color pixel wand. -// -// x, y: the starting location of the operation. -// -// invert: paint any pixel that does not match the target color. -// -func (mw *MagickWand) FloodfillPaintImage(fill *PixelWand, fuzz float64, borderColor *PixelWand, x, y int, invert bool) error { - ok := C.MagickFloodfillPaintImage(mw.mw, fill.pw, C.double(fuzz), borderColor.pw, C.ssize_t(x), C.ssize_t(y), b2i(invert)) - runtime.KeepAlive(fill) - runtime.KeepAlive(borderColor) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a horizontal mirror image by reflecting the pixels around the -// central y-axis. -func (mw *MagickWand) FlopImage() error { - ok := C.MagickFlopImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Implements the discrete Fourier transform (DFT) of the image either as a -// magnitude/phase or real/imaginary image pair. -// -// magnitude: if true, return as magnitude/phase pair otherwise a -// -// real/imaginary image pair. -func (mw *MagickWand) ForwardFourierTransformImage(magnitude bool) error { - ok := C.MagickForwardFourierTransformImage(mw.mw, b2i(magnitude)) - return mw.getLastErrorIfFailed(ok) -} - -// Adds a simulated three-dimensional border around the image. The width and -// height specify the border width of the vertical and horizontal sides of the -// frame. The inner and outer bevels indicate the width of the inner and outer -// shadows of the frame. -// -// matteColor: the frame color pixel wand. -// -// width: the border width. -// -// height: the border height. -// -// innerBevel: the inner bevel width. -// -// outerBevel: the outer bevel width. -// -// compose: the composite operator. -// -func (mw *MagickWand) FrameImage(matteColor *PixelWand, width, height uint, - innerBevel, outerBevel int, compose CompositeOperator) error { - - ok := C.MagickFrameImage(mw.mw, matteColor.pw, - C.size_t(width), C.size_t(height), - C.ssize_t(innerBevel), C.ssize_t(outerBevel), - C.CompositeOperator(compose)) - - runtime.KeepAlive(matteColor) - return mw.getLastErrorIfFailed(ok) -} - -// Applys an arithmetic, relational, or logical expression to an image. Use -// these operators to lighten or darken an image, to increase or decrease -// contrast in an image, or to produce the "negative" of an image. -func (mw *MagickWand) FunctionImage(function MagickFunction, args []float64) error { - ok := C.MagickFunctionImage(mw.mw, C.MagickFunction(function), C.size_t(len(args)), (*C.double)(&args[0])) - return mw.getLastErrorIfFailed(ok) -} - -// Evaluate expression for each pixel in the image. -func (mw *MagickWand) FxImage(expression string) (fxmw *MagickWand, err error) { - csexpression := C.CString(expression) - defer C.free(unsafe.Pointer(csexpression)) - fxmw = newMagickWand(C.MagickFxImage(mw.mw, csexpression)) - err = mw.GetLastError() - return -} - -// Gamma-corrects an image. The same image viewed on different devices will -// have perceptual differences in the way the image's intensities are -// represented on the screen. Specify individual gamma levels for the red, -// green, and blue channels, or adjust all three with the gamma parameter. -// Values typically range from 0.8 to 2.3. You can also reduce the influence -// of a particular channel with a gamma value of 0. -func (mw *MagickWand) GammaImage(gamma float64) error { - ok := C.MagickGammaImage(mw.mw, C.double(gamma)) - return mw.getLastErrorIfFailed(ok) -} - -// Blurs an image. We convolve the image with a Gaussian operator of the given -// radius and standard deviation (sigma). For reasonable results, the radius -// should be larger than sigma. Use a radius of 0 and GaussianBlurImage() -// selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -func (mw *MagickWand) GaussianBlurImage(radius, sigma float64) error { - ok := C.MagickGaussianBlurImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Gets the image at the current image index. -func (mw *MagickWand) GetImage() *MagickWand { - ret := newMagickWand(C.MagickGetImage(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// GetImageAlphaChannel returns MagickFalse if the image alpha channel is not -// activated. That is, the image is RGB rather than RGBA or CMYK rather than CMYKA. -func (mw *MagickWand) GetImageAlphaChannel() bool { - ret := 1 == C.MagickGetImageAlphaChannel(mw.mw) - runtime.KeepAlive(mw) - return ret -} - -// Returns the image background color. -func (mw *MagickWand) GetImageBackgroundColor() (bgColor *PixelWand, err error) { - cbgcolor := NewPixelWand() - ok := C.MagickGetImageBackgroundColor(mw.mw, cbgcolor.pw) - return cbgcolor, mw.getLastErrorIfFailed(ok) -} - -// Implements direct to memory image formats. It returns the image as a blob -// (a formatted "file" in memory) and its length, starting from the current -// position in the image sequence. Use SetImageFormat() to set the format to -// write to the blob (GIF, JPEG, PNG, etc.). Utilize ResetIterator() to ensure -// the write is from the beginning of the image sequence. -func (mw *MagickWand) GetImageBlob() []byte { - clen := C.size_t(0) - csblob := C.MagickGetImageBlob(mw.mw, &clen) - defer relinquishMemory(unsafe.Pointer(csblob)) - ret := C.GoBytes(unsafe.Pointer(csblob), C.int(clen)) - runtime.KeepAlive(mw) - return ret -} - -// Implements direct to memory image formats. It returns the image sequence -// as a blob and its length. The format of the image determines the format of -// the returned blob (GIF, JPEG, PNG, etc.). To return a different image -// format, use SetImageFormat(). Note, some image formats do not permit -// multiple images to the same image stream (e.g. JPEG). in this instance, -// just the first image of the sequence is returned as a blob. -func (mw *MagickWand) GetImagesBlob() []byte { - clen := C.size_t(0) - csblob := C.MagickGetImagesBlob(mw.mw, &clen) - defer relinquishMemory(unsafe.Pointer(csblob)) - runtime.KeepAlive(mw) - return C.GoBytes(unsafe.Pointer(csblob), C.int(clen)) -} - -// Returns the chromaticy blue primary point for the image. -// -// x: the chromaticity blue primary x-point. -// -// y: the chromaticity blue primary y-point. -// -// z: the chromaticity blue primary z-point. -// -func (mw *MagickWand) GetImageBluePrimary() (x, y, z float64, err error) { - ok := C.MagickGetImageBluePrimary(mw.mw, - (*C.double)(&x), (*C.double)(&y), (*C.double)(&z)) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Returns the image border color. -func (mw *MagickWand) GetImageBorderColor() (borderColor *PixelWand, err error) { - cbc := NewPixelWand() - ok := C.MagickGetImageBorderColor(mw.mw, cbc.pw) - return cbc, mw.getLastErrorIfFailed(ok) -} - -// Returns the color of the specified colormap index. -func (mw *MagickWand) GetImageColormapColor(index uint) (color *PixelWand, err error) { - cpw := NewPixelWand() - ok := C.MagickGetImageColormapColor(mw.mw, C.size_t(index), cpw.pw) - return cpw, mw.getLastErrorIfFailed(ok) -} - -// Gets the number of unique colors in the image. -func (mw *MagickWand) GetImageColors() uint { - ret := uint(C.MagickGetImageColors(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image colorspace. -func (mw *MagickWand) GetImageColorspace() ColorspaceType { - ret := ColorspaceType(C.MagickGetImageColorspace(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the composite operator associated with the image. -func (mw *MagickWand) GetImageCompose() CompositeOperator { - ret := CompositeOperator(C.MagickGetImageCompose(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image compression. -func (mw *MagickWand) GetImageCompression() CompressionType { - ret := CompressionType(C.MagickGetImageCompression(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image compression quality. -func (mw *MagickWand) GetImageCompressionQuality() uint { - ret := uint(C.MagickGetImageCompressionQuality(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image delay. -func (mw *MagickWand) GetImageDelay() uint { - ret := uint(C.MagickGetImageDelay(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image depth. -func (mw *MagickWand) GetImageDepth() uint { - ret := uint(C.MagickGetImageDepth(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Compares an image to a reconstructed image and returns the specified -// distortion metric. -func (mw *MagickWand) GetImageDistortion(reference *MagickWand, metric MetricType) (distortion float64, err error) { - ok := C.MagickGetImageDistortion(mw.mw, reference.mw, C.MetricType(metric), (*C.double)(&distortion)) - runtime.KeepAlive(reference) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Gets the image disposal method. -func (mw *MagickWand) GetImageDispose() DisposeType { - ret := DisposeType(C.MagickGetImageDispose(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image endian. -func (mw *MagickWand) GetImageEndian() EndianType { - ret := EndianType(C.MagickGetImageEndian(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the filename of a particular image in a sequence. -func (mw *MagickWand) GetImageFilename() string { - p := C.MagickGetImageFilename(mw.mw) - defer relinquishMemory(unsafe.Pointer(p)) - return C.GoString(p) -} - -// Returns the format of a particular image in a sequence. -func (mw *MagickWand) GetImageFormat() string { - p := C.MagickGetImageFormat(mw.mw) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(p)) - return C.GoString(p) -} - -// Gets the image fuzz. -func (mw *MagickWand) GetImageFuzz() float64 { - ret := float64(C.MagickGetImageFuzz(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image gamma. -func (mw *MagickWand) GetImageGamma() float64 { - ret := float64(C.MagickGetImageGamma(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image gravity. -func (mw *MagickWand) GetImageGravity() GravityType { - ret := GravityType(C.MagickGetImageGravity(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the chromaticy green primary point. -// -// x: the chromaticity green primary x-point. -// -// y: the chromaticity green primary y-point. -// -// z: the chromaticity green primary z-point. -// -func (mw *MagickWand) GetImageGreenPrimary() (x, y, z float64, err error) { - ok := C.MagickGetImageGreenPrimary(mw.mw, - (*C.double)(&x), (*C.double)(&y), (*C.double)(&z)) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Returns the image height. -func (mw *MagickWand) GetImageHeight() uint { - ret := uint(C.MagickGetImageHeight(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the image histogram as an array of PixelWand wands. -// -// numberColors: the number of unique colors in the image and the number of -// pixel wands returned. -func (mw *MagickWand) GetImageHistogram() (numberColors uint, pws []*PixelWand) { - cnc := C.size_t(0) - p := C.MagickGetImageHistogram(mw.mw, &cnc) - defer relinquishMemory(unsafe.Pointer(p)) - q := uintptr(unsafe.Pointer(p)) - numberColors = uint(cnc) - for i := 0; i < int(numberColors); i++ { - p = (**C.PixelWand)(unsafe.Pointer(q)) - if *p == nil { - break - } - pws = append(pws, newPixelWand(*p)) - q += unsafe.Sizeof(q) - } - runtime.KeepAlive(mw) - return -} - -// Gets the image interlace scheme. -func (mw *MagickWand) GetImageInterlaceScheme() InterlaceType { - ret := InterlaceType(C.MagickGetImageInterlaceScheme(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the interpolation method for the sepcified image. -func (mw *MagickWand) GetImageInterpolateMethod() PixelInterpolateMethod { - ret := PixelInterpolateMethod(C.MagickGetImageInterpolateMethod(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image iterations. -func (mw *MagickWand) GetImageIterations() uint { - ret := uint(C.MagickGetImageIterations(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the image length in bytes. -func (mw *MagickWand) GetImageLength() (length uint, err error) { - cl := C.MagickSizeType(0) - ok := C.MagickGetImageLength(mw.mw, &cl) - return uint(cl), mw.getLastErrorIfFailed(ok) -} - -// Returns the image orientation. -func (mw *MagickWand) GetImageOrientation() OrientationType { - ret := OrientationType(C.MagickGetImageOrientation(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the page geometry associated with the image. -// -// w, h: the page width and height -// -// x, h: the page x-offset and y-offset. -// -func (mw *MagickWand) GetImagePage() (w, h uint, x, y int, err error) { - var cw, ch C.size_t - var cx, cy C.ssize_t - ok := C.MagickGetImagePage(mw.mw, &cw, &ch, &cx, &cy) - return uint(cw), uint(ch), int(cx), int(cy), mw.getLastErrorIfFailed(ok) -} - -// Returns the color of the specified pixel. -func (mw *MagickWand) GetImagePixelColor(x, y int) (color *PixelWand, err error) { - pw := NewPixelWand() - ok := C.MagickGetImagePixelColor(mw.mw, C.ssize_t(x), C.ssize_t(y), pw.pw) - return pw, mw.getLastErrorIfFailed(ok) -} - -// Returns the chromaticy red primary point. -// -// x, y, z: the chromaticity red primary x/y/z-point. -// -func (mw *MagickWand) GetImageRedPrimary() (x, y, z float64, err error) { - var cdx, cdy, cdz C.double - ok := C.MagickGetImageRedPrimary(mw.mw, &cdx, &cdy, &cdz) - return float64(cdx), float64(cdy), float64(cdz), mw.getLastErrorIfFailed(ok) -} - -// Extracts a region of the image and returns it as a a new wand. -func (mw *MagickWand) GetImageRegion(width uint, height uint, x int, y int) *MagickWand { - ret := newMagickWand(C.MagickGetImageRegion(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y))) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image rendering intent. -func (mw *MagickWand) GetImageRenderingIntent() RenderingIntent { - ret := RenderingIntent(C.MagickGetImageRenderingIntent(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image X and Y resolution. -func (mw *MagickWand) GetImageResolution() (x, y float64, err error) { - var dx, dy C.double - ok := C.MagickGetImageResolution(mw.mw, &dx, &dy) - return float64(dx), float64(dy), mw.getLastErrorIfFailed(ok) -} - -// Gets the image scene. -func (mw *MagickWand) GetImageScene() uint { - ret := uint(C.MagickGetImageScene(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Generates an SHA-256 message digest for the image pixel stream. -func (mw *MagickWand) GetImageSignature() string { - p := C.MagickGetImageSignature(mw.mw) - defer relinquishMemory(unsafe.Pointer(p)) - runtime.KeepAlive(mw) - return C.GoString(p) -} - -// Gets the image ticks-per-second. -func (mw *MagickWand) GetImageTicksPerSecond() uint { - ret := uint(C.MagickGetImageTicksPerSecond(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the potential image type -// To ensure the image type matches its potential, use SetImageType(): -// wand.SetImageType(wand.GetImageType()) -func (mw *MagickWand) GetImageType() ImageType { - ret := ImageType(C.MagickGetImageType(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image units of resolution. -func (mw *MagickWand) GetImageUnits() ResolutionType { - ret := ResolutionType(C.MagickGetImageUnits(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the virtual pixel method for the specified image. -func (mw *MagickWand) GetImageVirtualPixelMethod() VirtualPixelMethod { - ret := VirtualPixelMethod(C.MagickGetImageVirtualPixelMethod(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the chromaticy white point. -// -// x, y, z: the chromaticity white x/y-point. -// -func (mw *MagickWand) GetImageWhitePoint() (x, y, z float64, err error) { - ok := C.MagickGetImageWhitePoint(mw.mw, - (*C.double)(&x), (*C.double)(&y), (*C.double)(&z)) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Returns the image width. -func (mw *MagickWand) GetImageWidth() uint { - ret := uint(C.MagickGetImageWidth(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the number of images associated with a magick wand. -func (mw *MagickWand) GetNumberImages() uint { - ret := uint(C.MagickGetNumberImages(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image total ink density. -func (mw *MagickWand) GetImageTotalInkDensity() float64 { - ret := float64(C.MagickGetImageTotalInkDensity(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Applies a continuously smooth color transition along a vector -// from one color stop to another. -func (mw *MagickWand) GradientImage(gradientType GradientType, spreadMethod SpreadMethod, - colorStops []StopInfo) error { - - stops := make([]C.StopInfo, len(colorStops)) - for i, colorStop := range colorStops { - stops[i] = colorStop.info - } - - var exc *C.ExceptionInfo = C.AcquireExceptionInfo() - defer C.DestroyExceptionInfo(exc) - - img := mw.GetImageFromMagickWand() - - ok := C.GradientImage( - img.img, - C.GradientType(gradientType), - C.SpreadMethod(spreadMethod), - (*C.StopInfo)(unsafe.Pointer(&stops[0])), - C.size_t(len(stops)), - exc) - - runtime.KeepAlive(mw) - runtime.KeepAlive(img) - runtime.KeepAlive(colorStops) - - if C.int(ok) == 0 { - return checkExceptionInfo(exc) - } - return nil -} - -// Replaces colors in the image from a Hald color lookup table. A Hald color -// lookup table is a 3-dimensional color cube mapped to 2 dimensions. Create -// it with the HALD coder. You can apply any color transformation to the Hald -// image and then use this method to apply the transform to the image. -func (mw *MagickWand) HaldClutImage(hald *MagickWand) error { - ok := C.MagickHaldClutImage(mw.mw, hald.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Returns true if the wand has more images when traversing the list in the -// forward direction -func (mw *MagickWand) HasNextImage() bool { - ret := 1 == C.MagickHasNextImage(mw.mw) - runtime.KeepAlive(mw) - return ret -} - -// Returns true if the wand has more images when traversing the list in the -// reverse direction -func (mw *MagickWand) HasPreviousImage() bool { - ret := 1 == C.MagickHasPreviousImage(mw.mw) - runtime.KeepAlive(mw) - return ret -} - -// Identifies an image by printing its attributes to the file. Attributes -// include the image width, height, size, and others. -func (mw *MagickWand) IdentifyImage() string { - p := C.MagickIdentifyImage(mw.mw) - defer relinquishMemory(unsafe.Pointer(p)) - runtime.KeepAlive(mw) - return C.GoString(p) -} - -// Creates a new image that is a copy of an existing one with the image pixels -// "implode" by the specified percentage. -// -// radius: Define the extent of the implosion. -// -// method: the pixel interpolation method. -// -func (mw *MagickWand) ImplodeImage(radius float64, method PixelInterpolateMethod) error { - ok := C.MagickImplodeImage(mw.mw, C.double(radius), C.PixelInterpolateMethod(method)) - return mw.getLastErrorIfFailed(ok) -} - -// Identifies the type of pixels and returns the storage type and an -// unsafe pointer to the data. -func pixelInterfaceToPtr(pixels interface{}) (unsafe.Pointer, StorageType, error) { - var ptr unsafe.Pointer - var stype StorageType - - switch t := pixels.(type) { - - case []byte: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_CHAR - - case []float64: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_DOUBLE - - case []float32: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_FLOAT - - case []int16: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_SHORT - - case []int32: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_LONG - - case []int64: - v := &t[0] - ptr = unsafe.Pointer(v) - stype = PIXEL_LONGLONG - - default: - return ptr, PIXEL_UNDEFINED, fmt.Errorf("Type %T is not valid for this operation", t) - } - - return ptr, stype, nil -} - -// Accepts pixel data and stores it in the image at the location you specify. -// The pixel data can be either byte, int16, int32, int64, float32, or float64 -// in the order specified by map. Suppose your want to upload the first -// scanline of a 640x480 image from character data in red-green-blue order: -// -// wand.ImportImagePixels(0, 0, 640, 1, "RGB", PIXEL_CHAR, pixels) -// -// x, y, cols, rows: These values define the perimeter of a region of pixels -// you want to define. -// -// pmap: This string reflects the expected ordering of the pixel array. It can -// be any combination or order of R = red, G = green, B = blue, A = alpha (0 -// is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, -// M = magenta, K = black, I = intensity (for grayscale), P = pad. -// -// stype: Define the data type of the pixels. Float and double types are -// expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose from -// these types: -// -// PIXEL_CHAR -// PIXEL_SHORT -// PIXEL_INTEGER -// PIXEL_LONG -// PIXEL_FLOAT -// PIXEL_DOUBLE -// -// pixels: This slice of values contain the pixel components as defined by map -// and type. You must pre-allocate this slice where the expected length varies -// depending on the values of width, height, map, and type. -// -func (mw *MagickWand) ImportImagePixels(x, y int, cols, rows uint, pmap string, - stype StorageType, pixels interface{}) error { - - if err := checkColsRows(cols, rows); err != nil { - return err - } - - cspmap := C.CString(pmap) - defer C.free(unsafe.Pointer(cspmap)) - - var ptr unsafe.Pointer - - ptr, calculatedStype, err := pixelInterfaceToPtr(pixels) - if err != nil { - return err - } - if stype == PIXEL_UNDEFINED { - stype = calculatedStype - } - - ok := C.MagickImportImagePixels(mw.mw, C.ssize_t(x), C.ssize_t(y), C.size_t(cols), - C.size_t(rows), cspmap, C.StorageType(stype), ptr) - - return mw.getLastErrorIfFailed(ok) -} - -// Implements the inverse discrete Fourier transform (DFT) of the image either -// as a magnitude/phase or real/imaginary image pair. -// -// magnitudeWand: the magnitude or real wand. -// -// phaseWand: the phase or imaginary wand. -// -// magnitude: if true, return as magnitude/phase pair otherwise a -// real/imaginary image pair. -// -func (mw *MagickWand) InverseFourierTransformImage(phaseWand *MagickWand, magnitude bool) error { - ok := C.MagickInverseFourierTransformImage(mw.mw, phaseWand.mw, b2i(magnitude)) - return mw.getLastErrorIfFailed(ok) -} - -// Adds a label to your image. -func (mw *MagickWand) LabelImage(label string) error { - cslabel := C.CString(label) - defer C.free(unsafe.Pointer(cslabel)) - ok := C.MagickLabelImage(mw.mw, cslabel) - return mw.getLastErrorIfFailed(ok) -} - -// Adjusts the levels of an image by scaling the colors falling between -// specified white and black points to the full available quantum range. The -// parameters provided represent the black, mid, and white points. The black -// point specifies the darkest color in the image. Colors darker than the -// black point are set to zero. Mid point specifies a gamma correction to -// apply to the image. White point specifies the lightest color in the image. -// Colors brighter than the white point are set to the maximum quantum value. -func (mw *MagickWand) LevelImage(blackPoint, gamma, whitePoint float64) error { - ok := C.MagickLevelImage(mw.mw, C.double(blackPoint), C.double(gamma), C.double(whitePoint)) - return mw.getLastErrorIfFailed(ok) -} - -// Stretches with saturation the image intensity. You can also reduce the -// influence of a particular channel with a gamma value of 0. -func (mw *MagickWand) LinearStretchImage(blackPoint, whitePoint float64) error { - ok := C.MagickLinearStretchImage(mw.mw, C.double(blackPoint), C.double(whitePoint)) - return mw.getLastErrorIfFailed(ok) -} - -// Rescales image with seam carving. -// -// cols, rows: the number of cols and rows in the scaled image. -// -// deltaX: maximum seam transversal step (0 means straight seams). -// -// rigidity: introduce a bias for non-straight seams (typically 0). -// -func (mw *MagickWand) LiquidRescaleImage(cols, rows uint, deltaX, rigidity float64) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickLiquidRescaleImage(mw.mw, C.size_t(cols), C.size_t(rows), C.double(deltaX), C.double(rigidity)) - return mw.getLastErrorIfFailed(ok) -} - -// This is a convenience method that scales an image proportionally to twice -// its original size. -func (mw *MagickWand) MagnifyImage() error { - ok := C.MagickMagnifyImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Composes all the image layers from the current given image onward to -// produce a single image of the merged layers. The inital canvas's size -// depends on the given ImageLayerMethod, and is initialized using the first -// images background color. The images are then compositied onto that image in -// sequence using the given composition that has been assigned to each -// individual image. -// -// method: the method of selecting the size of the initial canvas. MergeLayer: -// Merge all layers onto a canvas just large enough to hold all the actual -// images. The virtual canvas of the first image is preserved but otherwise -// ignored. FlattenLayer: Use the virtual canvas size of first image. Images -// which fall outside this canvas is clipped. This can be used to 'fill out' -// a given virtual canvas. MosaicLayer: Start with the virtual canvas of the -// first image, enlarging left and right edges to contain all images. Images -// with negative offsets will be clipped. -func (mw *MagickWand) MergeImageLayers(method LayerMethod) *MagickWand { - ret := newMagickWand(C.MagickMergeImageLayers(mw.mw, C.LayerMethod(method))) - runtime.KeepAlive(mw) - return ret -} - -// This is a convenience method that scales an image proportionally to -// one-half its original size -func (mw *MagickWand) MinifyImage() error { - ok := C.MagickMinifyImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Lets you control the brightness, saturation, and hue of an image. Hue is -// the percentage of absolute rotation from the current position. For example -// 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a -// clockwise rotation of 90 degrees, with 0 and 200 both resulting in a -// rotation of 180 degrees. To increase the color brightness by 20 and -// decrease the color saturation by 10 and leave the hue unchanged, use: 120, -// 90, 100. -// -// brightness: the percent change in brighness. -// -// saturation: the percent change in saturation. -// -// hue: the percent change in hue. -// -func (mw *MagickWand) ModulateImage(brightness, saturation, hue float64) error { - ok := C.MagickModulateImage(mw.mw, C.double(brightness), C.double(saturation), C.double(hue)) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a composite image by combining several separate images. The images -// are tiled on the composite image with the name of the image optionally -// appearing just below the individual tile. -// -// dw: the drawing wand. The font name, size, and color are obtained from this -// wand. -// -// tileGeo: the number of tiles per row and page (e.g. 6x4+0+0). -// -// thumbGeo: Preferred image size and border size of each thumbnail (e.g. -// 120x120+4+3>). -// -// mode: Thumbnail framing mode: Frame, Unframe, or Concatenate. -// -// frame: Surround the image with an ornamental border (e.g. 15x15+3+3). The -// frame color is that of the thumbnail's matte color. -// -func (mw *MagickWand) MontageImage(dw *DrawingWand, tileGeo string, thumbGeo string, mode MontageMode, frame string) *MagickWand { - cstile := C.CString(tileGeo) - defer C.free(unsafe.Pointer(cstile)) - csthumb := C.CString(thumbGeo) - defer C.free(unsafe.Pointer(csthumb)) - csframe := C.CString(frame) - defer C.free(unsafe.Pointer(csframe)) - - ret := newMagickWand(C.MagickMontageImage(mw.mw, dw.dw, cstile, csthumb, C.MontageMode(mode), csframe)) - runtime.KeepAlive(mw) - runtime.KeepAlive(dw) - return ret -} - -// Method morphs a set of images. Both the image pixels and size are linearly -// interpolated to give the appearance of a meta-morphosis from one image to -// the next. -// -// numFrames: the number of in-between images to generate. -func (mw *MagickWand) MorphImages(numFrames uint) *MagickWand { - ret := newMagickWand(C.MagickMorphImages(mw.mw, C.size_t(numFrames))) - runtime.KeepAlive(mw) - return ret -} - -// Applies a user supplied kernel to the image according to the given mophology -// method. -// -// channel: the image channel(s). -// -// method: the morphology method to be applied. -// -// iterations: apply the operation this many times (or no change). A value of -// -1 means loop until no change found. How this is applied may depend on the -// morphology method. Typically this is a value of 1. -// -// kernel: An array of doubles representing the morphology kernel. -func (mw *MagickWand) MorphologyImage(method MorphologyMethod, iterations int, kernel *KernelInfo) error { - ok := C.MagickMorphologyImage(mw.mw, C.MorphologyMethod(method), C.ssize_t(iterations), kernel.info) - return mw.getLastErrorIfFailed(ok) -} - -// Simulates motion blur. We convolve the image with a Gaussian operator of -// the given radius and standard deviation (sigma). For reasonable results, -// radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() -// selects a suitable radius for you. Angle gives the angle of the blurring -// motion. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -// angle: apply the effect along this angle. -// -func (mw *MagickWand) MotionBlurImage(radius, sigma, angle float64) error { - ok := C.MagickMotionBlurImage(mw.mw, C.double(radius), C.double(sigma), C.double(angle)) - return mw.getLastErrorIfFailed(ok) -} - -// Negates the colors in the reference image. The Grayscale option means that -// only grayscale values within the image are negated. You can also reduce the -// influence of a particular channel with a gamma value of 0. -// -// gray: If true, only negate grayscale pixels within the image. -// -func (mw *MagickWand) NegateImage(gray bool) error { - ok := C.MagickNegateImage(mw.mw, b2i(gray)) - return mw.getLastErrorIfFailed(ok) -} - -// Adds a blank image canvas of the specified size and background color to the -// wand. -func (mw *MagickWand) NewImage(cols uint, rows uint, background *PixelWand) error { - ok := C.MagickNewImage(mw.mw, C.size_t(cols), C.size_t(rows), background.pw) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the next image in the wand as the current image. It is typically used -// after ResetIterator(), after which its first use will set the first image -// as the current image (unless the wand is empty). It will return false when -// no more images are left to be returned which happens when the wand is empty, -// or the current image is the last image. When the above condition (end of -// image list) is reached, the iterator is automaticall set so that you can -// start using PreviousImage() to again/ iterate over the images in the -// reverse direction, starting with the last image (again). You can jump to -// this condition immeditally using SetLastIterator(). -func (mw *MagickWand) NextImage() bool { - ret := 1 == C.MagickNextImage(mw.mw) - runtime.KeepAlive(mw) - return ret -} - -// Enhances the contrast of a color image by adjusting the pixels color to -// span the entire range of colors available. You can also reduce the -// influence of a particular channel with a gamma value of 0. -func (mw *MagickWand) NormalizeImage() error { - ok := C.MagickNormalizeImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Applies a special effect filter that simulates an oil painting. Each pixel -// is replaced by the most frequent color occurring in a circular region -// defined by radius. -// -// radius: the radius of the circular neighborhood. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -func (mw *MagickWand) OilPaintImage(radius, sigma float64) error { - ok := C.MagickOilPaintImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Changes any pixel that matches color with the color defined by fill. -// -// target: Change this target color to the fill color within the image. -// -// fill: the fill pixel wand. -// -// fuzz: By default target must match a particular pixel color exactly. -// However, in many cases two colors may differ by a small amount. The fuzz -// member of image defines how much tolerance is acceptable to consider two -// colors as the same. For example, set fuzz to 10 and the color red at -// intensities of 100 and 102 respectively are now interpreted as the same -// color for the purposes of the floodfill. -// -// invert: paint any pixel that does not match the target color. -// -func (mw *MagickWand) OpaquePaintImage(target, fill *PixelWand, fuzz float64, invert bool) error { - ok := C.MagickOpaquePaintImage(mw.mw, target.pw, fill.pw, C.double(fuzz), b2i(invert)) - return mw.getLastErrorIfFailed(ok) -} - -// Compares each image the GIF disposed forms of the previous image in the -// sequence. From this it attempts to select the smallest cropped image to -// replace each frame, while preserving the results of the animation. -func (mw *MagickWand) OptimizeImageLayers() *MagickWand { - ret := newMagickWand(C.MagickOptimizeImageLayers(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Unsupported in ImageMagick 6.7.7 -// Takes a frame optimized GIF animation, and compares the overlayed pixels -// against the disposal image resulting from all the previous frames in the -// animation. Any pixel that does not change the disposal image (and thus does -// not effect the outcome of an overlay) is made transparent. -// WARNING: This modifies the current images directly, rather than generate a -// new image sequence. -func (mw *MagickWand) OptimizeImageTransparency() error { - ok := C.MagickOptimizeImageTransparency(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// This is like ReadImage() except the only valid information returned is the -// image width, height, size, and format. It is designed to efficiently obtain -// this information from a file without reading the entire image sequence into -// memory. -func (mw *MagickWand) PingImage(filename string) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickPingImage(mw.mw, csfilename) - return mw.getLastErrorIfFailed(ok) -} - -// Pings an image or image sequence from a blob. -func (mw *MagickWand) PingImageBlob(blob []byte) error { - if len(blob) == 0 { - return errors.New("zero-length blob not permitted") - } - ok := C.MagickPingImageBlob(mw.mw, unsafe.Pointer(&blob[0]), C.size_t(len(blob))) - return mw.getLastErrorIfFailed(ok) -} - -// Pings an image or image sequence from an open file descriptor. -func (mw *MagickWand) PingImageFile(img *os.File) error { - file, err := cfdopen(img, "rb") - if err != nil { - return err - } - defer C.fclose(file) - ok := C.MagickPingImageFile(mw.mw, file) - return mw.getLastErrorIfFailed(ok) -} - -// Simulates a Polaroid picture. -// -// caption: the Polaroid caption. -// -// angle: Apply the effect along this angle. -// -// method: the pixel interpolation method. -// -func (mw *MagickWand) PolaroidImage(dw *DrawingWand, caption string, - angle float64, method PixelInterpolateMethod) error { - - ccaption := C.CString(caption) - defer C.free(unsafe.Pointer(ccaption)) - - ok := C.MagickPolaroidImage(mw.mw, dw.dw, - ccaption, - C.double(angle), - C.PixelInterpolateMethod(method)) - - runtime.KeepAlive(dw) - return mw.getLastErrorIfFailed(ok) -} - -// Reduces the image to a limited number of color level. -// -// levels: Number of color levels allowed in each channel. Very low values -// (2, 3, or 4) have the most visible effect. -// -// dither: choose the dither method: UndefinedDitherMethod, NoDitherMethod, -// RiemersmaDitherMethod, or FloydSteinbergDitherMethod. -// -func (mw *MagickWand) PosterizeImage(levels uint, dither DitherMethod) error { - ok := C.MagickPosterizeImage(mw.mw, C.size_t(levels), C.DitherMethod(dither)) - return mw.getLastErrorIfFailed(ok) -} - -// Tiles 9 thumbnails of the specified image with an image processing -// operation applied at varying strengths. This helpful to quickly pin-point -// an appropriate parameter for an image processing operation. -func (mw *MagickWand) PreviewImages(preview PreviewType) *MagickWand { - ret := newMagickWand(C.MagickPreviewImages(mw.mw, C.PreviewType(preview))) - runtime.KeepAlive(mw) - return ret -} - -// Sets the previous image in the wand as the current image. It is typically -// used after SetLastIterator(), after which its first use will set the last -// image as the current image (unless the wand is empty). It will return false -// when no more images are left to be returned which happens when the wand is -// empty, or the current image is the first image. At that point the iterator -// is than reset to again process images in the forward direction, again -// starting with the first image in list. Images added at this point are -// prepended. Also at that point any images added to the wand using AddImages() -// or ReadImages() will be prepended before the first image. In this sense the -// condition is not quite exactly the same as ResetIterator(). -func (mw *MagickWand) PreviousImage() bool { - ret := 1 == C.MagickPreviousImage(mw.mw) - runtime.KeepAlive(mw) - return ret -} - -// Analyzes the colors within a reference image and chooses a fixed number of -// colors to represent the image. The goal of the algorithm is to minimize the -// color difference between the input and output image while minimizing the -// processing time. -// -// numColors: the number of colors. -// -// colorspace: Perform color reduction in this colorspace, typically -// RGBColorspace. -// -// treedepth: Normally, this integer value is zero or one. A zero or one tells -// Quantize to choose a optimal tree depth of Log4(number_colors). A tree of -// this depth generally allows the best representation of the reference image -// with the least amount of memory and the fastest computational speed. In -// some cases, such as an image with low color dispersion (a few number of -// colors), a value other than Log4(number_colors) is required. To expand the -// color tree completely, use a value of 8. -// -// dither: choose from UndefinedDitherMethod, NoDitherMethod, -// RiemersmaDitherMethod, FloydSteinbergDitherMethod. -// -// measureError: A value other than zero measures the difference between the -// original and quantized images. This difference is the total quantization -// error. The error is computed by summing over all pixels in an image the -// distance squared in RGB space between each reference pixel value and its -// quantized value. -// -func (mw *MagickWand) QuantizeImage(numColors uint, colorspace ColorspaceType, - treedepth uint, dither DitherMethod, measureError bool) error { - - ok := C.MagickQuantizeImage(mw.mw, C.size_t(numColors), - C.ColorspaceType(colorspace), C.size_t(treedepth), - C.DitherMethod(dither), b2i(measureError)) - - return mw.getLastErrorIfFailed(ok) -} - -// Analyzes the colors within a sequence of images and chooses a fixed number -// of colors to represent the image. The goal of the algorithm is to minimize -// the color difference between the input and output image while minimizing the -// processing time. -// -// numColors: the number of colors. -// -// colorspace: Perform color reduction in this colorspace, typically -// RGBColorspace. -// -// treedepth: Normally, this integer value is zero or one. A zero or one tells -// Quantize to choose a optimal tree depth of Log4(number_colors). A tree of -// this depth generally allows the best representation of the reference image -// with the least amount of memory and the fastest computational speed. In -// some cases, such as an image with low color dispersion (a few number of -// colors), a value other than Log4(number_colors) is required. To expand the -// color tree completely, use a value of 8. -// -// dither: choose from these dither methods: NoDitherMethod, -// RiemersmaDitherMethod, or FloydSteinbergDitherMethod. -// -// measureError: A value other than zero measures the difference between the -// original and quantized images. This difference is the total quantization -// error. The error is computed by summing over all pixels in an image the -// distance squared in RGB space between each reference pixel value and its -// quantized value. -// -func (mw *MagickWand) QuantizeImages(numColors uint, colorspace ColorspaceType, - treedepth uint, dither DitherMethod, measureError bool) error { - - ok := C.MagickQuantizeImages(mw.mw, C.size_t(numColors), - C.ColorspaceType(colorspace), C.size_t(treedepth), - C.DitherMethod(dither), b2i(measureError)) - - return mw.getLastErrorIfFailed(ok) -} - -// Radial blurs an image. -// -// angle: the angle of the blur in degrees. -// -func (mw *MagickWand) RadialBlurImage(angle float64) error { - ok := C.MagickRotationalBlurImage(mw.mw, C.double(angle)) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a simulated three-dimensional button-like effect by lightening and -// darkening the edges of the image. Members width and height of raise_info -// define the width of the vertical and horizontal edge of the effect. width, -// -// height, x, y: Define the dimensions of the area to raise. -// -// raise: A value other than zero creates a 3-D raise effect, otherwise it has -// a lowered effect. -// -func (mw *MagickWand) RaiseImage(width uint, height uint, x int, y int, raise bool) error { - ok := C.MagickRaiseImage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y), b2i(raise)) - return mw.getLastErrorIfFailed(ok) -} - -// Changes the value of individual pixels based on the intensity of each pixel -// compared to threshold. The result is a high-contrast, two color image. -// -// low, high: Specify the high and low thresholds. These values range from 0 -// to QuantumRange. -// -func (mw *MagickWand) RandomThresholdImage(low, high float64) error { - ok := C.MagickRandomThresholdImage(mw.mw, C.double(low), C.double(high)) - return mw.getLastErrorIfFailed(ok) -} - -// Reads an image or image sequence. The images are inserted at the current -// image pointer position. Use SetFirstIterator(), SetLastIterator, or -// SetImageIndex() to specify the current image pointer position at the -// beginning of the image list, the end, or anywhere in-between respectively. -func (mw *MagickWand) ReadImage(filename string) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickReadImage(mw.mw, csfilename) - return mw.getLastErrorIfFailed(ok) -} - -// Reads an image or image sequence from a blob. -func (mw *MagickWand) ReadImageBlob(blob []byte) error { - if len(blob) == 0 { - return errors.New("zero-length blob not permitted") - } - ok := C.MagickReadImageBlob(mw.mw, unsafe.Pointer(&blob[0]), C.size_t(len(blob))) - return mw.getLastErrorIfFailed(ok) -} - -// Reads an image or image sequence from an open file descriptor. -func (mw *MagickWand) ReadImageFile(img *os.File) error { - file, err := cfdopen(img, "rb") - if err != nil { - return err - } - defer C.fclose(file) - ok := C.MagickReadImageFile(mw.mw, file) - return mw.getLastErrorIfFailed(ok) -} - -// Replaces the colors of an image with the closest color from a reference image. -// -// method: choose from these dither methods: NoDitherMethod, RiemersmaDitherMethod, or FloydSteinbergDitherMethod. -// -func (mw *MagickWand) RemapImage(remap *MagickWand, method DitherMethod) error { - ok := C.MagickRemapImage(mw.mw, remap.mw, C.DitherMethod(method)) - runtime.KeepAlive(remap) - return mw.getLastErrorIfFailed(ok) -} - -// Removes an image from the image list. -func (mw *MagickWand) RemoveImage() error { - ok := C.MagickRemoveImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Resample image to desired resolution. -// -// xRes/yRes: the new image x/y resolution. -// -// filter: Image filter to use. -// -func (mw *MagickWand) ResampleImage(xRes, yRes float64, filter FilterType) error { - ok := C.MagickResampleImage(mw.mw, C.double(xRes), C.double(yRes), C.FilterType(filter)) - return mw.getLastErrorIfFailed(ok) -} - -// Resets the Wand page canvas and position. -// page: the relative page specification. -func (mw *MagickWand) ResetImagePage(page string) error { - cspage := C.CString(page) - defer C.free(unsafe.Pointer(cspage)) - ok := C.MagickResetImagePage(mw.mw, cspage) - return mw.getLastErrorIfFailed(ok) -} - -// Scales an image to the desired dimensions -// -// cols: the number of cols in the scaled image. -// -// rows: the number of rows in the scaled image. -// -// filter: Image filter to use. -// -func (mw *MagickWand) ResizeImage(cols, rows uint, filter FilterType) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickResizeImage(mw.mw, C.size_t(cols), C.size_t(rows), C.FilterType(filter)) - return mw.getLastErrorIfFailed(ok) -} - -// Offsets an image as defined by x and y. -// -// x: the x offset. -// -// y: the y offset. -// -func (mw *MagickWand) RollImage(x, y int) error { - ok := C.MagickRollImage(mw.mw, C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Rotates an image the specified number of degrees. Empty triangles left over -// from rotating the image are filled with the background color. -// -// background: the background pixel wand. -// -// degrees: the number of degrees to rotate the image. -// -func (mw *MagickWand) RotateImage(background *PixelWand, degrees float64) error { - ok := C.MagickRotateImage(mw.mw, background.pw, C.double(degrees)) - runtime.KeepAlive(background) - return mw.getLastErrorIfFailed(ok) -} - -// Scales an image to the desired dimensions with pixel sampling. Unlike other -// scaling methods, this method does not introduce any additional color into -// the scaled image. -func (mw *MagickWand) SampleImage(cols, rows uint) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickSampleImage(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Scales the size of an image to the given dimensions. -func (mw *MagickWand) ScaleImage(cols, rows uint) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickScaleImage(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Segments an image by analyzing the histograms of the color components and -// identifying units that are homogeneous with the fuzzy C-means technique. -// -// verbose: set to true to print detailed information about the identified -// classes. -// -// clusterThreshold: this represents the minimum number of pixels contained in -// a hexahedra before it can be considered valid (expressed as a percentage). -// -// smoothThreshold: the smoothing threshold eliminates noise in the second -// derivative of the histogram. As the value is increased, you can expect a -// smoother second derivative. -// -func (mw *MagickWand) SegmentImage(colorspace ColorspaceType, verbose bool, clusterThreshold, smoothThreshold float64) error { - ok := C.MagickSegmentImage(mw.mw, C.ColorspaceType(colorspace), b2i(verbose), C.double(clusterThreshold), C.double(smoothThreshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Selectively blur an image within a contrast threshold. It is similar to the -// unsharpen mask that sharpens everything with contrast above a certain -// threshold. -// -// radius: the radius of the gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the gaussian, in pixels. -// -// threshold: only pixels within this contrast threshold are included in the -// blur operation. -// -func (mw *MagickWand) SelectiveBlurImage(radius, sigma, threshold float64) error { - ok := C.MagickSelectiveBlurImage(mw.mw, C.double(radius), C.double(sigma), C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Applies a special effect to the image, similar to the effect achieved in a -// photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and -// is a measure of the extent of the sepia toning. A threshold of 80 is a good -// starting point for a reasonable tone. -// -// threshold: Define the extent of the sepia toning. -// -func (mw *MagickWand) SepiaToneImage(threshold float64) error { - ok := C.MagickSepiaToneImage(mw.mw, C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Replaces the last image returned by SetImageIndex(), NextImage(), -// PreviousImage() with the images from the specified wand. -func (mw *MagickWand) SetImage(source *MagickWand) error { - ok := C.MagickSetImage(mw.mw, source.mw) - runtime.KeepAlive(source) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image to the specified alpha level. -// -// alpha: the level of transparency: 1.0 is fully opaque and 0.0 is fully -// transparent. -// -func (mw *MagickWand) SetImageAlpha(alpha float64) error { - ok := C.MagickSetImageAlpha(mw.mw, C.double(alpha)) - runtime.KeepAlive(mw) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image background color. -func (mw *MagickWand) SetImageBackgroundColor(background *PixelWand) error { - ok := C.MagickSetImageBackgroundColor(mw.mw, background.pw) - runtime.KeepAlive(background) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image chromaticity blue primary point. -func (mw *MagickWand) SetImageBluePrimary(x, y, z float64) error { - ok := C.MagickSetImageBluePrimary(mw.mw, - C.double(x), C.double(y), C.double(z)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image border color. -func (mw *MagickWand) SetImageBorderColor(border *PixelWand) error { - ok := C.MagickSetImageBorderColor(mw.mw, border.pw) - runtime.KeepAlive(border) - return mw.getLastErrorIfFailed(ok) -} - -// SetImageChannelMask sets image channel mask, and returns -// the previous channel type setting. -// Setting the channel mask impacts the effect of image operations, -// to limit the operation to the given channel. -func (mw *MagickWand) SetImageChannelMask(channel ChannelType) ChannelType { - prevChannel := C.MagickSetImageChannelMask(mw.mw, C.ChannelType(channel)) - return ChannelType(prevChannel) -} - -// Set the entire wand canvas to the specified color. -func (mw *MagickWand) SetImageColor(color *PixelWand) error { - ok := C.MagickSetImageColor(mw.mw, color.pw) - runtime.KeepAlive(color) - return mw.getLastErrorIfFailed(ok) -} - -// SetImageAlphaChannel activates, deactivates, resets, or sets the alpha channel. -func (mw *MagickWand) SetImageAlphaChannel(operation AlphaChannelType) error { - ok := C.MagickSetImageAlphaChannel(mw.mw, C.AlphaChannelOption(operation)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the color of the specified colormap index. -// -// index: the offset into the image colormap. -// -// color: return the colormap color in this wand. -// -func (mw *MagickWand) SetImageColormapColor(index uint, color *PixelWand) error { - ok := C.MagickSetImageColormapColor(mw.mw, C.size_t(index), color.pw) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image colorspace. -func (mw *MagickWand) SetImageColorspace(colorspace ColorspaceType) error { - ok := C.MagickSetImageColorspace(mw.mw, C.ColorspaceType(colorspace)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image composite operator, useful for specifying how to composite -/// the image thumbnail when using the MontageImage() method. -func (mw *MagickWand) SetImageCompose(compose CompositeOperator) error { - ok := C.MagickSetImageCompose(mw.mw, C.CompositeOperator(compose)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image compression. -func (mw *MagickWand) SetImageCompression(compression CompressionType) error { - ok := C.MagickSetImageCompression(mw.mw, C.CompressionType(compression)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image compression quality. -func (mw *MagickWand) SetImageCompressionQuality(quality uint) error { - ok := C.MagickSetImageCompressionQuality(mw.mw, C.size_t(quality)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image delay. -// -// delay: the image delay in ticks-per-second units. -// -func (mw *MagickWand) SetImageDelay(delay uint) error { - ok := C.MagickSetImageDelay(mw.mw, C.size_t(delay)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image depth. -// -// depth: the image depth in bits: 8, 16, or 32. -// -func (mw *MagickWand) SetImageDepth(depth uint) error { - ok := C.MagickSetImageDepth(mw.mw, C.size_t(depth)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image disposal method. -func (mw *MagickWand) SetImageDispose(dispose DisposeType) error { - ok := C.MagickSetImageDispose(mw.mw, C.DisposeType(dispose)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image endian method. -func (mw *MagickWand) SetImageEndian(endian EndianType) error { - ok := C.MagickSetImageEndian(mw.mw, C.EndianType(endian)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image size (i.e. cols & rows). -// -// cols: The image width in pixels. -// -// rows: The image height in pixels. -// -func (mw *MagickWand) SetImageExtent(cols, rows uint) error { - ok := C.MagickSetImageExtent(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the filename of a particular image in a sequence. -func (mw *MagickWand) SetImageFilename(filename string) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickSetImageFilename(mw.mw, csfilename) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the format of a particular image in a sequence. -// -// format: the image format. -// -func (mw *MagickWand) SetImageFormat(format string) error { - csformat := C.CString(format) - defer C.free(unsafe.Pointer(csformat)) - ok := C.MagickSetImageFormat(mw.mw, csformat) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image fuzz. -func (mw *MagickWand) SetImageFuzz(fuzz float64) error { - ok := C.MagickSetImageFuzz(mw.mw, C.double(fuzz)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image gamma. -func (mw *MagickWand) SetImageGamma(gamma float64) error { - ok := C.MagickSetImageGamma(mw.mw, C.double(gamma)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image gravity type. -func (mw *MagickWand) SetImageGravity(gravity GravityType) error { - ok := C.MagickSetImageGravity(mw.mw, C.GravityType(gravity)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image chromaticity green primary point. -func (mw *MagickWand) SetImageGreenPrimary(x, y, z float64) error { - ok := C.MagickSetImageGreenPrimary(mw.mw, C.double(x), C.double(y), C.double(z)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image interlace scheme. -func (mw *MagickWand) SetImageInterlaceScheme(interlace InterlaceType) error { - ok := C.MagickSetImageInterlaceScheme(mw.mw, C.InterlaceType(interlace)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image interpolate pixel method. -func (mw *MagickWand) SetImageInterpolateMethod(method PixelInterpolateMethod) error { - ok := C.MagickSetImageInterpolateMethod(mw.mw, C.PixelInterpolateMethod(method)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image iterations. -func (mw *MagickWand) SetImageIterations(iterations uint) error { - ok := C.MagickSetImageIterations(mw.mw, C.size_t(iterations)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image matte channel. -func (mw *MagickWand) SetImageMatte(matte bool) error { - ok := C.MagickSetImageMatte(mw.mw, b2i(matte)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets image clip mask. -// PixelMaskType can be one of: PIXEL_MASK_READ, PIXEL_MASK_WRITE -func (mw *MagickWand) SetImageMask(typ PixelMaskType, clipMask *MagickWand) error { - ok := C.MagickSetImageMask(mw.mw, C.PixelMask(typ), clipMask.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image orientation. -func (mw *MagickWand) SetImageOrientation(orientation OrientationType) error { - ok := C.MagickSetImageOrientation(mw.mw, C.OrientationType(orientation)) - return mw.getLastErrorIfFailed(ok) -} - -// Auto orient the image -func (mw *MagickWand) AutoOrientImage() error { - ok := C.MagickAutoOrientImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the page geometry of the image. -func (mw *MagickWand) SetImagePage(width, height uint, x, y int) error { - ok := C.MagickSetImagePage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image chromaticity red primary point. -func (mw *MagickWand) SetImageRedPrimary(x, y, z float64) error { - ok := C.MagickSetImageRedPrimary(mw.mw, - C.double(x), C.double(y), C.double(z)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image rendering intent. -func (mw *MagickWand) SetImageRenderingIntent(ri RenderingIntent) error { - ok := C.MagickSetImageRenderingIntent(mw.mw, C.RenderingIntent(ri)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image resolution. -func (mw *MagickWand) SetImageResolution(xRes, yRes float64) error { - ok := C.MagickSetImageResolution(mw.mw, C.double(xRes), C.double(yRes)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image scene. -func (mw *MagickWand) SetImageScene(scene uint) error { - ok := C.MagickSetImageScene(mw.mw, C.size_t(scene)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image ticks-per-second. -func (mw *MagickWand) SetImageTicksPerSecond(tps int) error { - ok := C.MagickSetImageTicksPerSecond(mw.mw, C.ssize_t(tps)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image type. -func (mw *MagickWand) SetImageType(imgtype ImageType) error { - ok := C.MagickSetImageType(mw.mw, C.ImageType(imgtype)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image units of resolution. -func (mw *MagickWand) SetImageUnits(units ResolutionType) error { - ok := C.MagickSetImageUnits(mw.mw, C.ResolutionType(units)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image virtual pixel method. -func (mw *MagickWand) SetImageVirtualPixelMethod(method VirtualPixelMethod) VirtualPixelMethod { - return VirtualPixelMethod(C.MagickSetImageVirtualPixelMethod(mw.mw, C.VirtualPixelMethod(method))) -} - -// Sets the image chromaticity white point. -func (mw *MagickWand) SetImageWhitePoint(x, y, z float64) error { - ok := C.MagickSetImageWhitePoint(mw.mw, C.double(x), C.double(y), C.double(z)) - return mw.getLastErrorIfFailed(ok) -} - -// Shines a distant light on an image to create a three-dimensional effect. -// You control the positioning of the light with azimuth and elevation; -// azimuth is measured in degrees off the x axis and elevation is measured in -// pixels above the Z axis. -// -// gray: if true, shades the intensity of each pixel. -// -// azimuth, elevation: define the light source direction. -// -func (mw *MagickWand) ShadeImage(gray bool, azimuth, elevation float64) error { - ok := C.MagickShadeImage(mw.mw, b2i(gray), C.double(azimuth), C.double(elevation)) - return mw.getLastErrorIfFailed(ok) -} - -// Simulates an image shadow. -// -// opacity: percentage transparency. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -// x: the shadow x-offset. -// -// y: the shadow y-offset. -// -func (mw *MagickWand) ShadowImage(opacity, sigma float64, x, y int) error { - ok := C.MagickShadowImage(mw.mw, C.double(opacity), C.double(sigma), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Sharpens an image. We convolve the image with a Gaussian operator of the -// given radius and standard deviation (sigma). For reasonable results, the -// radius should be larger than sigma. Use a radius of 0 and SharpenImage() -// selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -func (mw *MagickWand) SharpenImage(radius, sigma float64) error { - ok := C.MagickSharpenImage(mw.mw, C.double(radius), C.double(sigma)) - return mw.getLastErrorIfFailed(ok) -} - -// Shaves pixels from the image edges. It allocates the memory necessary for -// the new Image structure and returns a pointer to the new image. -func (mw *MagickWand) ShaveImage(cols, rows uint) error { - ok := C.MagickShaveImage(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Slides one edge of an image along the X or Y axis, creating a parallelogram. -// An X direction shear slides an edge along the X axis, while a Y direction -// shear slides an edge along the Y axis. The amount of the shear is controlled -// by a shear angle. For X direction shears, xShear is measured relative to the -// Y axis, and similarly, for Y direction shears yShear is measured relative to -// the X axis. Empty triangles left over from shearing the image are filled -// with the background color. -func (mw *MagickWand) ShearImage(background *PixelWand, xShear, yShear float64) error { - ok := C.MagickShearImage(mw.mw, background.pw, C.double(xShear), C.double(yShear)) - runtime.KeepAlive(background) - return mw.getLastErrorIfFailed(ok) -} - -// Adjusts the contrast of an image with a non-linear sigmoidal contrast -// algorithm. Increase the contrast of the image using a sigmoidal transfer -// function without saturating highlights or shadows. Contrast indicates how -// much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); -// mid-point indicates where midtones fall in the resultant image (0 is white; -// 50 is middle-gray; 100 is black). Set sharpen to true to increase the image -// contrast otherwise the contrast is reduced. -// -// sharpen: Increase or decrease image contrast. -// -// alpha: strength of the contrast, the larger the number the more -// 'threshold-like' it becomes. -// -// beta: midpoint of the function as a color value 0 to QuantumRange. -// -func (mw *MagickWand) SigmoidalContrastImage(sharpen bool, alpha, beta float64) error { - ok := C.MagickSigmoidalContrastImage(mw.mw, b2i(sharpen), C.double(alpha), C.double(beta)) - return mw.getLastErrorIfFailed(ok) -} - -// Compares the reference image of the image and returns the best match offset. -// In addition, it returns a similarity image such that an exact match location -// is completely white and if none of the pixels match, black, otherwise some -// gray level in-between. -// -// reference: the reference wand. -// -// offset: the best match offset of the reference image within the image. -// -// metric: the metric. -// -// threshold: similarity; minimum distortion for (sub)image match. -// -func (mw *MagickWand) SimilarityImage(reference *MagickWand, metric MetricType, - threshold float64) (offset *RectangleInfo, similarity float64, area *MagickWand) { - - var rectInfo C.RectangleInfo - - mwarea := C.MagickSimilarityImage(mw.mw, reference.mw, - C.MetricType(metric), C.double(similarity), - &rectInfo, (*C.double)(&similarity)) - - runtime.KeepAlive(reference) - return &RectangleInfo{&rectInfo}, similarity, newMagickWand(mwarea) -} - -// Simulates a pencil sketch. We convolve the image with a Gaussian operator -// of the given radius and standard deviation (sigma). For reasonable results, -// radius should be larger than sigma. Use a radius of 0 and SketchImage() -// selects a suitable radius for you. Angle gives the angle of the blurring -// motion. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -// angle: Apply the effect along this angle. -// -func (mw *MagickWand) SketchImage(radius, sigma, angle float64) error { - ok := C.MagickSketchImage(mw.mw, C.double(radius), C.double(sigma), C.double(angle)) - return mw.getLastErrorIfFailed(ok) -} - -// Takes all images from the current image pointer to the end of the image -// list and smushs them to each other top-to-bottom if the stack parameter is -// true, otherwise left-to-right. -// -// stack: by default, images are stacked left-to-right. Set stack to true to -// stack them top-to-bottom. -// -// offset: minimum distance in pixels between images. -// -func (mw *MagickWand) SmushImages(stack bool, offset int) *MagickWand { - ret := newMagickWand(C.MagickSmushImages(mw.mw, b2i(stack), C.ssize_t(offset))) - runtime.KeepAlive(mw) - return ret -} - -// Applies a special effect to the image, similar to the effect achieved in a -// photo darkroom by selectively exposing areas of photo sensitive paper to -// light. Threshold ranges from 0 to QuantumRange and is a measure of the -// extent of the solarization. -// -// threshold: define the extent of the solarization. -// -func (mw *MagickWand) SolarizeImage(threshold float64) error { - ok := C.MagickSolarizeImage(mw.mw, C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Unsupported in ImageMagick 6.7.7 -// Applies a special effect to the image's channel, similar to the effect -// achieved in a photo darkroom by selectively exposing areas of photo -// sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a -// measure of the extent of the solarization. -// -// threshold: define the extent of the solarization. -// -//func (mw *MagickWand) SolarizeImageChannel(channel ChannelType, threshold float64) error { -// ok := C.MagickSolarizeImageChannel(mw.mw, C.ChannelType(channel), C.double(threshold)) -// return mw.getLastErrorIfFailed(ok) -//} - -// Given a set of coordinates, interpolates the colors found at those -// coordinates, across the whole image, using various methods. -// -// method: the method of image sparseion. ArcSparseColorion will always ignore -// source image offset, and always 'bestfit' the destination image with the top -// left corner offset relative to the polar mapping center. Bilinear has no -// simple inverse mapping so will not allow 'bestfit' style of image sparseion. -// Affine, Perspective, and Bilinear, will do least squares fitting of the -// distortion when more than the minimum number of control point pairs are -// provided. Perspective, and Bilinear, will fall back to a Affine sparseion -// when less than 4 control point pairs are provided. While Affine sparseions -// will let you use any number of control point pairs, that is Zero pairs is a -// No-Op (viewport only) distortion, one pair is a translation and two pairs -// of control points will do a scale-rotate-translate, without any shearing. -// -// arguments: the arguments for this sparseion method. -// -func (mw *MagickWand) SparseColorImage(channel ChannelType, method SparseColorMethod, - arguments []float64) error { - - ok := C.MagickSparseColorImage(mw.mw, C.SparseColorMethod(method), - C.size_t(len(arguments)), (*C.double)(&arguments[0])) - - return mw.getLastErrorIfFailed(ok) -} - -// Splices a solid color into the image. -func (mw *MagickWand) SpliceImage(width, height uint, x, y int) error { - ok := C.MagickSpliceImage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Is a special effects method that randomly displaces each pixel in a block -// defined by the radius parameter. -// -// method: intepolation method. -// -// radius: Choose a random pixel in a neighborhood of this extent. -// -func (mw *MagickWand) SpreadImage(method PixelInterpolateMethod, radius float64) error { - ok := C.MagickSpreadImage(mw.mw, C.PixelInterpolateMethod(method), C.double(radius)) - return mw.getLastErrorIfFailed(ok) -} - -// Replace each pixel with corresponding statistic from the neighborhood of -// the specified width and height. -// -// type: the statistic type (e.g. median, mode, etc.). -// -// width: the width of the pixel neighborhood. -// -// height: the height of the pixel neighborhood. -// -func (mw *MagickWand) StatisticImage(stype StatisticType, width, height uint) error { - ok := C.MagickStatisticImage(mw.mw, C.StatisticType(stype), C.size_t(width), C.size_t(height)) - return mw.getLastErrorIfFailed(ok) -} - -// Hides a digital watermark within the image. Recover the hidden watermark -// later to prove that the authenticity of an image. Offset defines the start -// position within the image to hide the watermark. -// -// offset: start hiding at this offset into the image. -// -func (mw *MagickWand) SteganoImage(watermark *MagickWand, offset int) *MagickWand { - ret := newMagickWand(C.MagickSteganoImage(mw.mw, watermark.mw, C.ssize_t(offset))) - runtime.KeepAlive(mw) - runtime.KeepAlive(watermark) - return ret -} - -// Composites two images and produces a single image that is the composite of -// a left and right image of a stereo pair. -func (mw *MagickWand) StereoImage(offset *MagickWand) *MagickWand { - ret := newMagickWand(C.MagickStereoImage(mw.mw, offset.mw)) - runtime.KeepAlive(mw) - runtime.KeepAlive(offset) - return ret -} - -// Strips an image of all profiles and comments. -func (mw *MagickWand) StripImage() error { - ok := C.MagickStripImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Swirls the pixels about the center of the image, where degrees indicates the -// sweep of the arc through which each pixel is moved. You get a more dramatic -// effect as the degrees move from 1 to 360. -// -// degrees: define the tightness of the swirling effect. -// -// method: the pixel interpolation method. -// -func (mw *MagickWand) SwirlImage(degrees float64, method PixelInterpolateMethod) error { - ok := C.MagickSwirlImage(mw.mw, C.double(degrees), C.PixelInterpolateMethod(method)) - return mw.getLastErrorIfFailed(ok) -} - -// Repeatedly tiles the texture image across and down the image canvas. -func (mw *MagickWand) TextureImage(texture *MagickWand) *MagickWand { - ret := newMagickWand(C.MagickTextureImage(mw.mw, texture.mw)) - runtime.KeepAlive(mw) - runtime.KeepAlive(texture) - return ret -} - -// Changes the value of individual pixels based on the intensity of each pixel -// compared to threshold. The result is a high-contrast, two color image. -// -// threshold: define the threshold value. -// -func (mw *MagickWand) ThresholdImage(threshold float64) error { - ok := C.MagickThresholdImage(mw.mw, C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Changes the value of individual pixels based on the intensity of each pixel -// compared to threshold. The result is a high-contrast, two color image. -// -// threshold: define the threshold value. -// -func (mw *MagickWand) ThresholdImageChannel(channel ChannelType, threshold float64) error { - ok := C.MagickThresholdImageChannel(mw.mw, C.ChannelType(channel), C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Changes the size of an image to the given dimensions and removes any -// associated profiles. The goal is to produce small low cost thumbnail images -// suited for display on the Web. -func (mw *MagickWand) ThumbnailImage(cols, rows uint) error { - if err := checkColsRows(cols, rows); err != nil { - return err - } - ok := C.MagickThumbnailImage(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Applies a color vector to each pixel in the image. The length of the vector -// is 0 for black and white and at its maximum for the midtones. The vector -// weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))). -// -// tint: the tint pixel wand. -// -// opacity: the opacity pixel wand. -// -func (mw *MagickWand) TintImage(tint, opacity *PixelWand) error { - ok := C.MagickTintImage(mw.mw, tint.pw, opacity.pw) - runtime.KeepAlive(tint) - runtime.KeepAlive(opacity) - return mw.getLastErrorIfFailed(ok) -} - -// Transform the image colorspace, setting the images colorspace while -// transforming the images data to that colorspace. -func (mw *MagickWand) TransformImageColorspace(colorspace ColorspaceType) error { - ok := C.MagickTransformImageColorspace(mw.mw, C.ColorspaceType(colorspace)) - return mw.getLastErrorIfFailed(ok) -} - -// Changes any pixel that matches color with the color defined by fill. -// -// alpha: the level of transparency: 1.0 is fully opaque and 0.0 is fully -// transparent. -// -// fuzz: by default target must match a particular pixel color exactly. -// However, in many cases two colors may differ by a small amount. The fuzz -// member of image defines how much tolerance is acceptable to consider two -// colors as the same. For example, set fuzz to 10 and the color red at -// intensities of 100 and 102 respectively are now interpreted as the same -// color for the purposes of the floodfill. -// -// invert: paint any pixel that does not match the target color. -// -func (mw *MagickWand) TransparentPaintImage(target *PixelWand, alpha, fuzz float64, invert bool) error { - ok := C.MagickTransparentPaintImage(mw.mw, target.pw, C.double(alpha), C.double(fuzz), b2i(invert)) - runtime.KeepAlive(target) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a vertical mirror image by reflecting the pixels around the central -// x-axis while rotating them 90-degrees. -func (mw *MagickWand) TransposeImage() error { - ok := C.MagickTransposeImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a horizontal mirror image by reflecting the pixels around the -// central y-axis while rotating them 270-degrees. -func (mw *MagickWand) TransverseImage() error { - ok := C.MagickTransverseImage(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Remove edges that are the background color from the image. -// -// fuzz: by default target must match a particular pixel color exactly. -// However, in many cases two colors may differ by a small amount. The fuzz -// member of image defines how much tolerance is acceptable to consider two -// colors as the same. For example, set fuzz to 10 and the color red at -// intensities of 100 and 102 respectively are now interpreted as the same -// color for the purposes of the floodfill. -func (mw *MagickWand) TrimImage(fuzz float64) error { - ok := C.MagickTrimImage(mw.mw, C.double(fuzz)) - return mw.getLastErrorIfFailed(ok) -} - -// Discards all but one of any pixel color. -func (mw *MagickWand) UniqueImageColors() error { - ok := C.MagickUniqueImageColors(mw.mw) - return mw.getLastErrorIfFailed(ok) -} - -// Unsharpens an image. We convolve the image with a Gaussian operator of the -// given radius and standard deviation (sigma). For reasonable results, radius -// should be larger than sigma. Use a radius of 0 and UnsharpMaskImage() -// selects a suitable radius for you. -// -// radius: the radius of the Gaussian, in pixels, not counting the center pixel. -// -// sigma: the standard deviation of the Gaussian, in pixels. -// -// amount: the percentage of the difference between the original and the blur -// image that is added back into the original. -// -// threshold: the threshold in pixels needed to apply the diffence amount. -// -func (mw *MagickWand) UnsharpMaskImage(radius, sigma, amount, threshold float64) error { - ok := C.MagickUnsharpMaskImage(mw.mw, C.double(radius), C.double(sigma), C.double(amount), C.double(threshold)) - return mw.getLastErrorIfFailed(ok) -} - -// Softens the edges of the image in vignette style. -// -// x, y: define the x and y ellipse offset. -// -func (mw *MagickWand) VignetteImage(blackPoint, whitePoint float64, x, y int) error { - ok := C.MagickVignetteImage(mw.mw, C.double(blackPoint), C.double(whitePoint), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Creates a "ripple" effect in the image by shifting the pixels vertically -// along a sine wave whose amplitude and wavelength is specified by the given -// parameters. -// -// amplitude, wavelength: Define the amplitude and wave length of the sine wave. -// -// method: the pixel interpolation method -// -func (mw *MagickWand) WaveImage(amplitude, wavelength float64, - method PixelInterpolateMethod) error { - - ok := C.MagickWaveImage(mw.mw, C.double(amplitude), - C.double(wavelength), C.PixelInterpolateMethod(method)) - - return mw.getLastErrorIfFailed(ok) -} - -// Is like ThresholdImage() but force all pixels above the threshold into white -// while leaving all pixels below the threshold unchanged. -func (mw *MagickWand) WhiteThresholdImage(threshold *PixelWand) error { - ok := C.MagickWhiteThresholdImage(mw.mw, threshold.pw) - runtime.KeepAlive(threshold) - return mw.getLastErrorIfFailed(ok) -} - -// Writes an image to the specified filename. -func (mw *MagickWand) WriteImage(filename string) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickWriteImage(mw.mw, csfilename) - return mw.getLastErrorIfFailed(ok) -} - -// Writes an image to an open file descriptor. -func (mw *MagickWand) WriteImageFile(out *os.File) error { - file, err := cfdopen(out, "w") - if err != nil { - return err - } - defer C.fclose(file) - ok := C.MagickWriteImageFile(mw.mw, file) - return mw.getLastErrorIfFailed(ok) -} - -// Writes an image or image sequence. -func (mw *MagickWand) WriteImages(filename string, adjoin bool) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickWriteImages(mw.mw, csfilename, b2i(adjoin)) - return mw.getLastErrorIfFailed(ok) -} - -// Writes an image sequence to an open file descriptor. -func (mw *MagickWand) WriteImagesFile(out *os.File) error { - file, err := cfdopen(out, "w") - if err != nil { - return err - } - defer C.fclose(file) - ok := C.MagickWriteImagesFile(mw.mw, file) - return mw.getLastErrorIfFailed(ok) -} - -// cfdopen returns a C-level FILE*. mode should be as described in fdopen(3). -// Caller is responsible for closing the file when successfully returned, -// via C.fclose() -func cfdopen(file *os.File, mode string) (*C.FILE, error) { - cmode := C.CString(mode) - defer C.free(unsafe.Pointer(cmode)) - - cfile, err := C.fdopen(C.dup(C.int(file.Fd())), cmode) - if err != nil { - return nil, err - } - if cfile == nil { - return nil, syscall.EINVAL - } - - return cfile, nil -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_prop.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_prop.go deleted file mode 100644 index 9b1d02af..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/magick_wand_prop.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" -import ( - //"fmt" - "errors" - "runtime" - "unsafe" -) - -// This method deletes a wand artifact -func (mw *MagickWand) DeleteImageArtifact(artifact string) error { - csartifact := C.CString(artifact) - defer C.free(unsafe.Pointer(csartifact)) - ok := C.MagickDeleteImageArtifact(mw.mw, csartifact) - return mw.getLastErrorIfFailed(ok) -} - -// This method deletes a image property -func (mw *MagickWand) DeleteImageProperty(property string) error { - csproperty := C.CString(property) - defer C.free(unsafe.Pointer(csproperty)) - ok := C.MagickDeleteImageProperty(mw.mw, csproperty) - return mw.getLastErrorIfFailed(ok) -} - -// This method deletes a wand option -func (mw *MagickWand) DeleteOption(option string) error { - csoption := C.CString(option) - defer C.free(unsafe.Pointer(csoption)) - ok := C.MagickDeleteOption(mw.mw, csoption) - return mw.getLastErrorIfFailed(ok) -} - -// Returns the antialias property associated with the wand -func (mw *MagickWand) GetAntialias() bool { - ret := 1 == C.int(C.MagickGetAntialias(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the wand background color -func (mw *MagickWand) GetBackgroundColor() *PixelWand { - ret := newPixelWand(C.MagickGetBackgroundColor(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the wand colorspace type -func (mw *MagickWand) GetColorspace() ColorspaceType { - ccst := C.MagickGetColorspace(mw.mw) - runtime.KeepAlive(mw) - return ColorspaceType(ccst) -} - -// Gets the wand compression type. -func (mw *MagickWand) GetCompression() CompressionType { - ret := CompressionType(C.MagickGetCompression(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the wand compression quality. -func (mw *MagickWand) GetCompressionQuality() uint { - ret := uint(C.MagickGetCompressionQuality(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the filename associated with an image sequence. -func (mw *MagickWand) GetFilename() string { - cstr := C.MagickGetFilename(mw.mw) - runtime.KeepAlive(mw) - defer C.free(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Returns the font associated with the MagickWand. -func (mw *MagickWand) GetFont() string { - cstr := C.MagickGetFont(mw.mw) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Returns the format of the magick wand. -func (mw *MagickWand) GetFormat() string { - cstr := C.MagickGetFormat(mw.mw) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Gets the wand gravity. -func (mw *MagickWand) GetGravity() GravityType { - ret := GravityType(C.MagickGetGravity(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns a value associated with the specified artifact. -func (mw *MagickWand) GetImageArtifact(artifact string) string { - csartifact := C.CString(artifact) - defer C.free(unsafe.Pointer(csartifact)) - cstr := C.MagickGetImageArtifact(mw.mw, csartifact) - runtime.KeepAlive(mw) - defer C.free(unsafe.Pointer(cstr)) - return C.GoString(cstr) -} - -// Returns all the artifact names that match the specified pattern associated -// with a wand. Use GetImageProperty() to return the value of a particular -// artifact. -func (mw *MagickWand) GetImageArtifacts(pattern string) (artifacts []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - num := C.size_t(0) - p := C.MagickGetImageArtifacts(mw.mw, cspattern, &num) - runtime.KeepAlive(mw) - defer relinquishMemoryCStringArray(p) - artifacts = sizedCStringArrayToStringSlice(p, num) - return -} - -// Returns the named image profile. -// -// name: Name of profile to return: ICC, IPTC, or generic profile. -func (mw *MagickWand) GetImageProfile(name string) string { - csname := C.CString(name) - defer C.free(unsafe.Pointer(csname)) - szlen := C.size_t(0) - csprofile := C.MagickGetImageProfile(mw.mw, csname, &szlen) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(csprofile)) - return C.GoStringN((*C.char)((unsafe.Pointer)(csprofile)), C.int(szlen)) -} - -// Returns all the profile names that match the specified pattern associated -// with a wand. Use GetImageProfile() to return the value of a particular -// property. -func (mw *MagickWand) GetImageProfiles(pattern string) (profiles []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - np := C.size_t(0) - ps := C.MagickGetImageProfiles(mw.mw, cspattern, &np) - runtime.KeepAlive(mw) - defer relinquishMemoryCStringArray(ps) - profiles = sizedCStringArrayToStringSlice(ps, np) - return -} - -// Returns a value associated with the specified property. -func (mw *MagickWand) GetImageProperty(property string) string { - csproperty := C.CString(property) - defer C.free(unsafe.Pointer(csproperty)) - cspv := C.MagickGetImageProperty(mw.mw, csproperty) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(cspv)) - return C.GoString(cspv) -} - -// Returns all the property names that match the specified pattern associated -// with a wand. Use GetImageProperty() to return the value of a particular -// property. -func (mw *MagickWand) GetImageProperties(pattern string) (properties []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - np := C.size_t(0) - ps := C.MagickGetImageProperties(mw.mw, cspattern, &np) - runtime.KeepAlive(mw) - defer relinquishMemoryCStringArray(ps) - properties = sizedCStringArrayToStringSlice(ps, np) - return -} - -// Gets the wand interlace scheme. -func (mw *MagickWand) GetInterlaceScheme() InterlaceType { - ret := InterlaceType(C.MagickGetInterlaceScheme(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the wand compression. -func (mw *MagickWand) GetInterpolateMethod() PixelInterpolateMethod { - ret := PixelInterpolateMethod(C.MagickGetInterpolateMethod(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns a value associated with a wand and the specified key. -func (mw *MagickWand) GetOption(key string) string { - cskey := C.CString(key) - defer C.free(unsafe.Pointer(cskey)) - csval := C.MagickGetOption(mw.mw, cskey) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(csval)) - return C.GoString(csval) -} - -// Returns all the option names that match the specified pattern associated -// with a wand. Use GetOption() to return the value of a particular option. -func (mw *MagickWand) GetOptions(pattern string) (options []string) { - cspattern := C.CString(pattern) - defer C.free(unsafe.Pointer(cspattern)) - np := C.size_t(0) - ps := C.MagickGetOptions(mw.mw, cspattern, &np) - runtime.KeepAlive(mw) - defer relinquishMemoryCStringArray(ps) - options = sizedCStringArrayToStringSlice(ps, np) - return -} - -// Gets the wand orientation type. -func (mw *MagickWand) GetOrientation() OrientationType { - ret := OrientationType(C.MagickGetOrientation(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns the page geometry associated with the magick wand. -func (mw *MagickWand) GetPage() (width, height uint, x, y int, err error) { - var cw, ch C.size_t - var cx, cy C.ssize_t - ok := C.MagickGetPage(mw.mw, &cw, &ch, &cx, &cy) - width, height, x, y = uint(cw), uint(ch), int(cx), int(cy) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Returns the font pointsize associated with the MagickWand. -func (mw *MagickWand) GetPointsize() float64 { - ret := float64(C.MagickGetPointsize(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Gets the image X and Y resolution. -func (mw *MagickWand) GetResolution() (x, y float64, err error) { - ok := C.MagickGetResolution(mw.mw, (*C.double)(&x), (*C.double)(&y)) - err = mw.getLastErrorIfFailed(ok) - return -} - -// Gets the horizontal and vertical sampling factor. -func (mw *MagickWand) GetSamplingFactors() (factors []float64) { - num := C.size_t(0) - pd := C.MagickGetSamplingFactors(mw.mw, &num) - runtime.KeepAlive(mw) - factors = sizedDoubleArrayToFloat64Slice(pd, num) - return -} - -// Returns the size associated with the magick wand. -func (mw *MagickWand) GetSize() (cols, rows uint, err error) { - var cc, cr C.size_t - ok := C.MagickGetSize(mw.mw, &cc, &cr) - cols, rows, err = uint(cc), uint(cr), mw.getLastErrorIfFailed(ok) - return -} - -// Returns the size offset associated with the magick wand. -func (mw *MagickWand) GetSizeOffset() (offset int, err error) { - var co C.ssize_t - ok := C.MagickGetSizeOffset(mw.mw, &co) - offset, err = int(co), mw.getLastErrorIfFailed(ok) - return -} - -// Returns the wand type. -func (mw *MagickWand) GetType() ImageType { - ret := ImageType(C.MagickGetType(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Adds or removes a ICC, IPTC, or generic profile from an image. If the -// profile is empty, it is removed from the image otherwise added. Use a name -// of '*' and an empty profile to remove all profiles from the image. -// -// name: Name of profile to add or remove: ICC, IPTC, or generic profile. -// -func (mw *MagickWand) ProfileImage(name string, profile []byte) error { - if len(profile) == 0 { - return errors.New("zero-length profile not permitted") - } - csname := C.CString(name) - defer C.free(unsafe.Pointer(csname)) - ok := C.MagickProfileImage(mw.mw, csname, unsafe.Pointer(&profile[0]), C.size_t(len(profile))) - return mw.getLastErrorIfFailed(ok) -} - -// Removes the named image profile and returns it. -// -// name: name of profile to return: ICC, IPTC, or generic profile. -// -func (mw *MagickWand) RemoveImageProfile(name string) []byte { - csname := C.CString(name) - defer C.free(unsafe.Pointer(csname)) - clen := C.size_t(0) - profile := C.MagickRemoveImageProfile(mw.mw, csname, &clen) - runtime.KeepAlive(mw) - defer relinquishMemory(unsafe.Pointer(profile)) - return C.GoBytes(unsafe.Pointer(profile), C.int(clen)) -} - -// Sets the antialias propery of the wand. -func (mw *MagickWand) SetAntialias(antialias bool) error { - ok := C.MagickSetAntialias(mw.mw, b2i(antialias)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand background color. -func (mw *MagickWand) SetBackgroundColor(background *PixelWand) error { - ok := C.MagickSetBackgroundColor(mw.mw, background.pw) - runtime.KeepAlive(background) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand colorspace type. -func (mw *MagickWand) SetColorspace(colorspace ColorspaceType) error { - ok := C.MagickSetColorspace(mw.mw, C.ColorspaceType(colorspace)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand compression type. -func (mw *MagickWand) SetCompression(compression CompressionType) error { - ok := C.MagickSetCompression(mw.mw, C.CompressionType(compression)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand compression quality. -func (mw *MagickWand) SetCompressionQuality(quality uint) error { - ok := C.MagickSetCompressionQuality(mw.mw, C.size_t(quality)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand pixel depth. -func (mw *MagickWand) SetDepth(depth uint) error { - ok := C.MagickSetDepth(mw.mw, C.size_t(depth)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the extract geometry before you read or write an image file. Use it for -// inline cropping (e.g. 200x200+0+0) or resizing (e.g.200x200). -func (mw *MagickWand) SetExtract(geometry string) error { - csgeometry := C.CString(geometry) - defer C.free(unsafe.Pointer(csgeometry)) - ok := C.MagickSetExtract(mw.mw, csgeometry) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the filename before you read or write an image file. -func (mw *MagickWand) SetFilename(filename string) error { - csfilename := C.CString(filename) - defer C.free(unsafe.Pointer(csfilename)) - ok := C.MagickSetFilename(mw.mw, csfilename) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the font associated with the MagickWand. -func (mw *MagickWand) SetFont(font string) error { - csfont := C.CString(font) - defer C.free(unsafe.Pointer(csfont)) - ok := C.MagickSetFont(mw.mw, csfont) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the format of the magick wand. -func (mw *MagickWand) SetFormat(format string) error { - csformat := C.CString(format) - defer C.free(unsafe.Pointer(csformat)) - ok := C.MagickSetFormat(mw.mw, csformat) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the gravity type. -func (mw *MagickWand) SetGravity(gtype GravityType) error { - ok := C.MagickSetGravity(mw.mw, C.GravityType(gtype)) - return mw.getLastErrorIfFailed(ok) -} - -// Associates a artifact with an image. -func (mw *MagickWand) SetImageArtifact(artifact, value string) error { - csartifact := C.CString(artifact) - defer C.free(unsafe.Pointer(csartifact)) - csvalue := C.CString(value) - defer C.free(unsafe.Pointer(csvalue)) - ok := C.MagickSetImageArtifact(mw.mw, csartifact, csvalue) - return mw.getLastErrorIfFailed(ok) -} - -// Adds a named profile to the magick wand. If a profile with the same name -// already exists, it is replaced. This method differs from the ProfileImage() -// method in that it does not apply any CMS color profiles. -// -// name: Name of profile to add or remove: ICC, IPTC, or generic profile. -func (mw *MagickWand) SetImageProfile(name string, profile []byte) error { - if len(profile) == 0 { - return errors.New("zero-length profile not permitted") - } - csname := C.CString(name) - defer C.free(unsafe.Pointer(csname)) - ok := C.MagickSetImageProfile(mw.mw, csname, unsafe.Pointer(&profile[0]), C.size_t(len(profile))) - return mw.getLastErrorIfFailed(ok) -} - -// Associates a property with an image. -func (mw *MagickWand) SetImageProperty(property, value string) error { - csproperty := C.CString(property) - defer C.free(unsafe.Pointer(csproperty)) - csvalue := C.CString(value) - defer C.free(unsafe.Pointer(csvalue)) - ok := C.MagickSetImageProperty(mw.mw, csproperty, csvalue) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image interlacing scheme -func (mw *MagickWand) SetInterlaceScheme(scheme InterlaceType) error { - ok := C.MagickSetInterlaceScheme(mw.mw, C.InterlaceType(scheme)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the interpolate pixel method. -func (mw *MagickWand) SetInterpolateMethod(method PixelInterpolateMethod) error { - ok := C.MagickSetInterpolateMethod(mw.mw, C.PixelInterpolateMethod(method)) - return mw.getLastErrorIfFailed(ok) -} - -// Associates one or options with the wand (.e.g -// SetOption(wand, "jpeg:perserve", "yes")). -func (mw *MagickWand) SetOption(key, value string) error { - cskey := C.CString(key) - defer C.free(unsafe.Pointer(cskey)) - csvalue := C.CString(value) - defer C.free(unsafe.Pointer(csvalue)) - ok := C.MagickSetOption(mw.mw, cskey, csvalue) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the wand orientation type. -func (mw *MagickWand) SetOrientation(orientation OrientationType) error { - ok := C.MagickSetOrientation(mw.mw, C.OrientationType(orientation)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the page geometry of the magick wand. -func (mw *MagickWand) SetPage(width, height uint, x, y int) error { - ok := C.MagickSetPage(mw.mw, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the passphrase. -func (mw *MagickWand) SetPassphrase(passphrase string) error { - cspassphrase := C.CString(passphrase) - defer C.free(unsafe.Pointer(cspassphrase)) - ok := C.MagickSetPassphrase(mw.mw, cspassphrase) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the font pointsize associated with the MagickWand. -func (mw *MagickWand) SetPointsize(pointSize float64) error { - ok := C.MagickSetPointsize(mw.mw, C.double(pointSize)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the limit for a particular resource in megabytes. -func (mw *MagickWand) SetResourceLimit(rtype ResourceType, limit int64) error { - ok := C.MagickSetResourceLimit(C.ResourceType(rtype), C.MagickSizeType(limit)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image resolution. -func (mw *MagickWand) SetResolution(xRes, yRes float64) error { - ok := C.MagickSetResolution(mw.mw, C.double(xRes), C.double(yRes)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image sampling factors. -// -// samplingFactors: An array of floats representing the sampling factor for -// each color component (in RGB order). -func (mw *MagickWand) SetSamplingFactors(samplingFactors []float64) error { - ok := C.MagickSetSamplingFactors(mw.mw, C.size_t(len(samplingFactors)), (*C.double)(&samplingFactors[0])) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the size of the magick wand. Set it before you read a raw image format -// such as RGB, GRAY, or CMYK. -func (mw *MagickWand) SetSize(cols, rows uint) error { - ok := C.MagickSetSize(mw.mw, C.size_t(cols), C.size_t(rows)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the size and offset of the magick wand. Set it before you read a raw -// image format such as RGB, GRAY, or CMYK. -func (mw *MagickWand) SetSizeOffset(cols, rows uint, offset int) error { - ok := C.MagickSetSizeOffset(mw.mw, C.size_t(cols), C.size_t(rows), C.ssize_t(offset)) - return mw.getLastErrorIfFailed(ok) -} - -// Sets the image type attribute. -func (mw *MagickWand) SetType(itype ImageType) error { - ok := C.MagickSetType(mw.mw, C.ImageType(itype)) - return mw.getLastErrorIfFailed(ok) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/memory.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/memory.go deleted file mode 100644 index fc9f0149..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/memory.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#cgo !no_pkgconfig pkg-config: MagickWand MagickCore -#include -*/ -import "C" - -import ( - "unsafe" -) - -// relinquishes memory resources returned by such methods as MagickIdentifyImage(), MagickGetException(), etc -func relinquishMemory(ptr unsafe.Pointer) { - if ptr != nil { - C.MagickRelinquishMemory(ptr) - } -} - -// relinquishes memory resources, null terminated array of strings -func relinquishMemoryCStringArray(p **C.char) { - defer relinquishMemory(unsafe.Pointer(p)) - for *p != nil { - relinquishMemory(unsafe.Pointer(*p)) - q := uintptr(unsafe.Pointer(p)) - q += unsafe.Sizeof(q) - p = (**C.char)(unsafe.Pointer(q)) - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/metric_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/metric_type.go deleted file mode 100644 index 5498e6e6..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/metric_type.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type MetricType int - -const ( - METRIC_UNDEFINED MetricType = C.UndefinedErrorMetric - METRIC_ABSOLUTE_ERROR MetricType = C.AbsoluteErrorMetric - METRIC_FUZZ_ERROR MetricType = C.FuzzErrorMetric - METRIC_MEAN_ABSOLUTE_ERROR MetricType = C.MeanAbsoluteErrorMetric - METRIC_MEAN_ERROR_PER_PIXEL MetricType = C.MeanErrorPerPixelErrorMetric - METRIC_MEAN_SQUARED_ERROR MetricType = C.MeanSquaredErrorMetric - METRIC_NORMALIZED_CROSS_CORRELATION_ERROR MetricType = C.NormalizedCrossCorrelationErrorMetric - METRIC_PEAK_ABSOLUTE_ERROR MetricType = C.PeakAbsoluteErrorMetric - METRIC_PEAK_SIGNAL_TO_NOISE_RATIO MetricType = C.PeakSignalToNoiseRatioErrorMetric - METRIC_PERCEPTUAL_HASH_ERROR MetricType = C.PerceptualHashErrorMetric - METRIC_ROOT_MEAN_SQUARED_ERROR MetricType = C.RootMeanSquaredErrorMetric - METRIC_STRUCTURAL_SIMILARITY_ERROR MetricType = C.StructuralSimilarityErrorMetric - METRIC_STRUCTURAL_DISSIMILARITY_ERROR MetricType = C.StructuralDissimilarityErrorMetric -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/montage_mode.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/montage_mode.go deleted file mode 100644 index 4fc66a16..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/montage_mode.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type MontageMode int - -const ( - MONTAGE_MODE_UNDEFINED MontageMode = C.UndefinedMode - MONTAGE_MODE_FRAME MontageMode = C.FrameMode - MONTAGE_MODE_UNFRAME MontageMode = C.UnframeMode - MONTAGE_MODE_CONCATENATE MontageMode = C.ConcatenateMode -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/morphology_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/morphology_method.go deleted file mode 100644 index 3a84cc0b..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/morphology_method.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type MorphologyMethod int - -const ( - MORPHOLOGY_UNDEFINED MorphologyMethod = C.UndefinedMorphology - MORPHOLOGY_CONVOLVE MorphologyMethod = C.ConvolveMorphology /* Weighted Sum with reflected kernel */ - MORPHOLOGY_CORRELATE MorphologyMethod = C.CorrelateMorphology /* Weighted Sum using a sliding window */ - MORPHOLOGY_ERODE MorphologyMethod = C.ErodeMorphology /* Minimum Value in Neighbourhood */ - MORPHOLOGY_DILATE MorphologyMethod = C.DilateMorphology /* Maximum Value in Neighbourhood */ - MORPHOLOGY_ERODE_INTENSITY MorphologyMethod = C.ErodeIntensityMorphology /* Pixel Pick using GreyScale Erode */ - MORPHOLOGY_DILATE_INTENSITY MorphologyMethod = C.DilateIntensityMorphology /* Pixel Pick using GreyScale Dialate */ - MORPHOLOGY_DISTANCE MorphologyMethod = C.DistanceMorphology /* Add Kernel Value, take Minimum */ - MORPHOLOGY_OPEN MorphologyMethod = C.OpenMorphology /* Dilate then Erode */ - MORPHOLOGY_CLOSE MorphologyMethod = C.CloseMorphology /* Erode then Dilate */ - MORPHOLOGY_OPEN_INTENSITY MorphologyMethod = C.OpenIntensityMorphology /* Pixel Pick using GreyScale Open */ - MORPHOLOGY_CLOSE_INTENSITY MorphologyMethod = C.CloseIntensityMorphology /* Pixel Pick using GreyScale Close */ - MORPHOLOGY_SMOOTH MorphologyMethod = C.SmoothMorphology /* Open then Close */ - MORPHOLOGY_EDGE_IN MorphologyMethod = C.EdgeInMorphology /* Dilate difference from Original */ - MORPHOLOGY_EDGE_OUT MorphologyMethod = C.EdgeOutMorphology /* Erode difference from Original */ - MORPHOLOGY_EDGE MorphologyMethod = C.EdgeMorphology /* Dilate difference with Erode */ - MORPHOLOGY_TOP_HAT MorphologyMethod = C.TopHatMorphology /* Close difference from Original */ - MORPHOLOGY_BOTTOM_HAT MorphologyMethod = C.BottomHatMorphology /* Open difference from Original */ - MORPHOLOGY_HIT_AND_MISS MorphologyMethod = C.HitAndMissMorphology /* Foreground/Background pattern matching */ - MORPHOLOGY_THINNING MorphologyMethod = C.ThinningMorphology /* Remove matching pixels from image */ - MORPHOLOGY_THICKEN MorphologyMethod = C.ThickenMorphology /* Add matching pixels from image */ - MORPHOLOGY_VORONOI MorphologyMethod = C.VoronoiMorphology /* distance matte channel copy nearest color */ - MORPHOLOGY_ITERATIVE_DISTANCE MorphologyMethod = C.IterativeDistanceMorphology /* Add Kernel Value, take Minimum */ -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/noise_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/noise_type.go deleted file mode 100644 index 61abde12..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/noise_type.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type NoiseType int - -const ( - NOISE_UNDEFINED NoiseType = C.UndefinedNoise - NOISE_UNIFORM NoiseType = C.UniformNoise - NOISE_GAUSSIAN NoiseType = C.GaussianNoise - NOISE_MULTIPLICATIVE_GAUSSIAN NoiseType = C.MultiplicativeGaussianNoise - NOISE_IMPULSE NoiseType = C.ImpulseNoise - NOISE_LAPLACIAN NoiseType = C.LaplacianNoise - NOISE_POISSON NoiseType = C.PoissonNoise - NOISE_RANDOM NoiseType = C.RandomNoise -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/orientation_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/orientation_type.go deleted file mode 100644 index c7e8052c..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/orientation_type.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type OrientationType int - -const ( - ORIENTATION_UNDEFINED OrientationType = C.UndefinedOrientation - ORIENTATION_TOP_LEFT OrientationType = C.TopLeftOrientation - ORIENTATION_TOP_RIGHT OrientationType = C.TopRightOrientation - ORIENTATION_BOTTOM_RIGHT OrientationType = C.BottomRightOrientation - ORIENTATION_BOTTOM_LEFT OrientationType = C.BottomLeftOrientation - ORIENTATION_LEFT_TOP OrientationType = C.LeftTopOrientation - ORIENTATION_RIGHT_TOP OrientationType = C.RightTopOrientation - ORIENTATION_RIGHT_BOTTOM OrientationType = C.RightBottomOrientation - ORIENTATION_LEFT_BOTTOM OrientationType = C.LeftBottomOrientation -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/paint_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/paint_method.go deleted file mode 100644 index a659a108..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/paint_method.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PaintMethod int - -const ( - PAINT_METHOD_UNDEFINED PaintMethod = C.UndefinedMethod - PAINT_METHOD_POINT PaintMethod = C.PointMethod - PAINT_METHOD_REPLACE PaintMethod = C.ReplaceMethod - PAINT_METHOD_FLOODFILL PaintMethod = C.FloodfillMethod - PAINT_METHOD_FILLTOBORDER PaintMethod = C.FillToBorderMethod - PAINT_METHOD_RESET PaintMethod = C.ResetMethod -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_info.go deleted file mode 100644 index 94b67e96..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_info.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PixelInfo struct { - pi *C.PixelInfo -} - -func newPixelInfoFromCAPI(pi *C.PixelInfo) *PixelInfo { - return &PixelInfo{pi} -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator.go deleted file mode 100644 index 684c37b8..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include - -static PixelWand* get_pw_at(PixelWand** pws, size_t pos) { - return pws[pos]; -} -*/ -import "C" -import ( - "runtime" - "sync" - "sync/atomic" - "unsafe" -) - -type PixelIterator struct { - pi *C.PixelIterator - init sync.Once -} - -func newPixelIterator(cpi *C.PixelIterator) *PixelIterator { - pi := &PixelIterator{pi: cpi} - runtime.SetFinalizer(pi, Destroy) - pi.IncreaseCount() - - return pi -} - -// Returns a new pixel iterator -// -// mw: the magick wand to iterate on -// -func (mw *MagickWand) NewPixelIterator() *PixelIterator { - ret := newPixelIterator(C.NewPixelIterator(mw.mw)) - runtime.KeepAlive(mw) - return ret -} - -// Returns a new pixel iterator -// -// mw: the magick wand to iterate on -// x, y, cols, rows: there values define the perimeter of a region of pixels -// -func (mw *MagickWand) NewPixelRegionIterator(x, y int, width, height uint) *PixelIterator { - ret := newPixelIterator(C.NewPixelRegionIterator(mw.mw, C.ssize_t(x), C.ssize_t(y), C.size_t(width), C.size_t(height))) - runtime.KeepAlive(mw) - return ret -} - -// Clear resources associated with a PixelIterator. -func (pi *PixelIterator) Clear() { - C.ClearPixelIterator(pi.pi) - runtime.KeepAlive(pi) -} - -// Makes an exact copy of the specified iterator. -func (pi *PixelIterator) Clone() *PixelIterator { - ret := newPixelIterator(C.ClonePixelIterator(pi.pi)) - runtime.KeepAlive(pi) - return ret -} - -// Deallocates resources associated with a PixelIterator. -func (pi *PixelIterator) Destroy() { - if pi.pi == nil { - return - } - - pi.init.Do(func() { - pi.pi = C.DestroyPixelIterator(pi.pi) - relinquishMemory(unsafe.Pointer(pi.pi)) - runtime.SetFinalizer(pi, nil) - pi.pi = nil - - pi.DecreaseCount() - }) -} - -// Returns true if the iterator is verified as a pixel iterator. -func (pi *PixelIterator) IsVerified() bool { - if pi.pi == nil { - return false - } - ret := 1 == C.IsPixelIterator(pi.pi) - runtime.KeepAlive(pi) - return ret -} - -// Increase PixelIterator ref counter and set according "can`t be terminated status" -func (pi *PixelIterator) IncreaseCount() { - atomic.AddInt64(&pixelIteratorCounter, int64(1)) - unsetCanTerminate() -} - -// Decrease DrawingWand ref counter and set according "can be terminated status" -func (pi *PixelIterator) DecreaseCount() { - atomic.AddInt64(&pixelIteratorCounter, int64(-1)) - setCanTerminate() -} - -// Returns the current row as an array of pixel wands from the pixel iterator. -func (pi *PixelIterator) GetCurrentIteratorRow() (pws []*PixelWand) { - num := C.size_t(0) - pp := C.PixelGetCurrentIteratorRow(pi.pi, &num) - if pp == nil { - return - } - for i := 0; i < int(num); i++ { - cpw := C.get_pw_at(pp, C.size_t(i)) - // PixelWand is a private pointer, borrowed from the pixel - // iterator. We don't want to reference count it. It will - // get destroyed by C API when PixelIterator is destroyed. - pws = append(pws, &PixelWand{pw: cpw}) - } - runtime.KeepAlive(pi) - return -} - -// Returns the current pixel iterator row. -func (pi *PixelIterator) GetIteratorRow() int { - ret := int(C.PixelGetIteratorRow(pi.pi)) - runtime.KeepAlive(pi) - return ret -} - -// Returns the next row as an array of pixel wands from the pixel iterator. -func (pi *PixelIterator) GetNextIteratorRow() (pws []*PixelWand) { - num := C.size_t(0) - pp := C.PixelGetNextIteratorRow(pi.pi, &num) - if pp == nil { - return - } - for i := 0; i < int(num); i++ { - cpw := C.get_pw_at(pp, C.size_t(i)) - // PixelWand is a private pointer, borrowed from the pixel - // iterator. We don't want to reference count it. It will - // get destroyed by C API when PixelIterator is destroyed. - pws = append(pws, &PixelWand{pw: cpw}) - } - runtime.KeepAlive(pi) - return -} - -// Returns the previous row as an array of pixel wands from the pixel iterator. -func (pi *PixelIterator) GetPreviousIteratorRow() (pws []*PixelWand) { - num := C.size_t(0) - pp := C.PixelGetPreviousIteratorRow(pi.pi, &num) - if pp == nil { - return - } - for i := 0; i < int(num); i++ { - cpw := C.get_pw_at(pp, C.size_t(i)) - // PixelWand is a private pointer, borrowed from the pixel - // iterator. We don't want to reference count it. It will - // get destroyed by C API when PixelIterator is destroyed. - pws = append(pws, &PixelWand{pw: cpw}) - } - runtime.KeepAlive(pi) - return -} - -// Resets the pixel iterator. Use it in conjunction with GetNextIteratorRow() -// to iterate over all the pixels in a pixel container. -func (pi *PixelIterator) Reset() { - C.PixelResetIterator(pi.pi) - runtime.KeepAlive(pi) -} - -// Sets the pixel iterator to the first pixel row. -func (pi *PixelIterator) SetFirstIteratorRow() { - C.PixelSetFirstIteratorRow(pi.pi) - runtime.KeepAlive(pi) -} - -// Set the pixel iterator row. -func (pi *PixelIterator) SetIteratorRow(row int) error { - ok := C.PixelSetIteratorRow(pi.pi, C.ssize_t(row)) - return pi.getLastErrorIfFailed(ok) -} - -// Sets the pixel iterator to the last pixel row. -func (pi *PixelIterator) SetLastIteratorRow() { - C.PixelSetLastIteratorRow(pi.pi) - runtime.KeepAlive(pi) -} - -// Syncs the pixel iterator. -func (pi *PixelIterator) SyncIterator() error { - ok := C.PixelSyncIterator(pi.pi) - return pi.getLastErrorIfFailed(ok) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator_exception.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator_exception.go deleted file mode 100644 index ebfc0686..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_iterator_exception.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" - "runtime" - "unsafe" -) - -type PixelIteratorException struct { - kind ExceptionType - description string -} - -func (pie *PixelIteratorException) Error() string { - return fmt.Sprintf("%s: %s", pie.kind.String(), pie.description) -} - -// Clears any exceptions associated with the iterator -func (pi *PixelIterator) clearException() bool { - ret := 1 == C.int(C.PixelClearIteratorException(pi.pi)) - runtime.KeepAlive(pi) - return ret -} - -// Returns the kind, reason and description of any error that occurs when using -// other methods in this API -func (pi *PixelIterator) GetLastError() error { - var et C.ExceptionType - csdescription := C.PixelGetIteratorException(pi.pi, &et) - defer relinquishMemory(unsafe.Pointer(csdescription)) - if ExceptionType(et) != EXCEPTION_UNDEFINED { - pi.clearException() - return &PixelIteratorException{ExceptionType(C.int(et)), C.GoString(csdescription)} - } - runtime.KeepAlive(pi) - return nil -} - -func (pi *PixelIterator) getLastErrorIfFailed(ok C.MagickBooleanType) error { - if C.int(ok) == 0 { - return pi.GetLastError() - } else { - return nil - } -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_mask_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_mask_type.go deleted file mode 100644 index 1f09e512..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_mask_type.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PixelMaskType int - -const ( - PIXEL_MASK_UNDEFINED PixelMaskType = C.UndefinedPixelMask - PIXEL_MASK_READ PixelMaskType = C.ReadPixelMask - PIXEL_MASK_WRITE PixelMaskType = C.WritePixelMask - PIXEL_MASK_COMPOSITE PixelMaskType = C.CompositePixelMask -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_packet.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_packet.go deleted file mode 100644 index a0689c53..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_packet.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PixelPacket struct { - pp *C.PixelPacket -} - -func newPixelPacketFromCAPI(mpp *C.PixelPacket) *PixelPacket { - return &PixelPacket{mpp} -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand.go deleted file mode 100644 index b1be1c1d..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand.go +++ /dev/null @@ -1,436 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "runtime" - "sync" - "sync/atomic" - "unsafe" -) - -type PixelWand struct { - pw *C.PixelWand - init sync.Once -} - -// Returns a new pixel wand -func newPixelWand(cpw *C.PixelWand) *PixelWand { - pw := &PixelWand{pw: cpw} - runtime.SetFinalizer(pw, Destroy) - pw.IncreaseCount() - - return pw -} - -// Returns a new pixel wand -func NewPixelWand() *PixelWand { - return newPixelWand(C.NewPixelWand()) -} - -// Clears resources associated with the wand -func (pw *PixelWand) Clear() { - C.ClearPixelWand(pw.pw) - runtime.KeepAlive(pw) -} - -// Makes an exact copy of the wand -func (pw *PixelWand) Clone() *PixelWand { - ret := newPixelWand(C.ClonePixelWand(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Deallocates resources associated with a pixel wand -func (pw *PixelWand) Destroy() { - if pw.pw == nil { - return - } - - pw.init.Do(func() { - pw.pw = C.DestroyPixelWand(pw.pw) - relinquishMemory(unsafe.Pointer(pw.pw)) - runtime.SetFinalizer(pw, nil) - pw.pw = nil - - pw.DecreaseCount() - }) -} - -// Returns true if the distance between two colors is less than the specified distance -func (pw *PixelWand) IsSimilar(pixelWand *PixelWand, fuzz float64) bool { - ret := 1 == C.int(C.IsPixelWandSimilar(pw.pw, pixelWand.pw, C.double(fuzz))) - runtime.KeepAlive(pw) - runtime.KeepAlive(pixelWand) - return ret -} - -// Returns true if the wand is verified as a pixel wand -func (pw *PixelWand) IsVerified() bool { - if pw.pw != nil { - return 1 == C.int(C.IsPixelWand(pw.pw)) - } - runtime.KeepAlive(pw) - return false -} - -// Increase PixelWand ref counter and set according "can`t be terminated status" -func (pw *PixelWand) IncreaseCount() { - atomic.AddInt64(&pixelWandCounter, int64(1)) - unsetCanTerminate() -} - -// Decrease PixelWand ref counter and set according "can be terminated status" -func (pw *PixelWand) DecreaseCount() { - atomic.AddInt64(&pixelWandCounter, int64(-1)) - setCanTerminate() -} - -// Returns the normalized alpha color of the pixel wand -func (pw *PixelWand) GetAlpha() float64 { - ret := float64(C.PixelGetAlpha(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the alpha value of the pixel wand -func (pw *PixelWand) GetAlphaQuantum() Quantum { - ret := Quantum(C.PixelGetAlphaQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized black color of the pixel wand -func (pw *PixelWand) GetBlack() float64 { - ret := float64(C.PixelGetBlack(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the black color of the pixel wand -func (pw *PixelWand) GetBlackQuantum() Quantum { - ret := Quantum(C.PixelGetBlackQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized blue color of the pixel wand -func (pw *PixelWand) GetBlue() float64 { - ret := float64(C.PixelGetBlue(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the blue color of the pixel wand -func (pw *PixelWand) GetBlueQuantum() Quantum { - ret := Quantum(C.PixelGetBlueQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the color of the pixel wand as a string -func (pw *PixelWand) GetColorAsString() string { - p := C.PixelGetColorAsString(pw.pw) - runtime.KeepAlive(pw) - defer relinquishMemory(unsafe.Pointer(p)) - return C.GoString(p) -} - -// Returns the normalized color of the pixel wand as string -func (pw *PixelWand) GetColorAsNormalizedString() string { - p := C.PixelGetColorAsNormalizedString(pw.pw) - runtime.KeepAlive(pw) - defer relinquishMemory(unsafe.Pointer(p)) - return C.GoString(p) -} - -// Returns the color count associated with this color -func (pw *PixelWand) GetColorCount() uint { - ret := uint(C.PixelGetColorCount(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized cyan color of the pixel wand -func (pw *PixelWand) GetCyan() float64 { - ret := float64(C.PixelGetCyan(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the cyan color of the pixel wand -func (pw *PixelWand) GetCyanQuantum() Quantum { - ret := Quantum(C.PixelGetCyanQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized fuzz value of the pixel wand -func (pw *PixelWand) GetFuzz() float64 { - ret := float64(C.PixelGetFuzz(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized green color of the pixel wand -func (pw *PixelWand) GetGreen() float64 { - ret := float64(C.PixelGetGreen(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the green color of the pixel wand -func (pw *PixelWand) GetGreenQuantum() Quantum { - ret := Quantum(C.PixelGetGreenQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized HSL color of the pixel wand -func (pw *PixelWand) GetHSL() (hue, saturation, brightness float64) { - var cdhue, cdsaturation, cdbrightness C.double - C.PixelGetHSL(pw.pw, &cdhue, &cdsaturation, &cdbrightness) - runtime.KeepAlive(pw) - hue, saturation, brightness = float64(cdhue), float64(cdsaturation), float64(cdbrightness) - return -} - -// Returns the colormap index from the pixel wand -func (pw *PixelWand) GetIndex() IndexPacket { - cip := C.PixelGetIndex(pw.pw) - runtime.KeepAlive(pw) - return IndexPacket(cip) -} - -// Returns the normalized magenta color of the pixel wand -func (pw *PixelWand) GetMagenta() float64 { - ret := float64(C.PixelGetMagenta(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the magenta color of the pixel wand -func (pw *PixelWand) GetMagentaQuantum() Quantum { - ret := Quantum(C.PixelGetMagentaQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Gets the magick color of the pixel wand -func (pw *PixelWand) GetMagickColor() *PixelInfo { - var pi C.PixelInfo - C.PixelGetMagickColor(pw.pw, &pi) - runtime.KeepAlive(pw) - return newPixelInfoFromCAPI(&pi) -} - -// Deprecated: Use GetAlpha() -func (pw *PixelWand) GetOpacity() float64 { - return pw.GetAlpha() -} - -// Deprecated: Use GetAlphaQuantum() -func (pw *PixelWand) GetOpacityQuantum() Quantum { - return pw.GetAlphaQuantum() -} - -// Gets the color of the pixel wand as a PixelPacket -func (pw *PixelWand) GetQuantumColor() *PixelInfo { - var pi C.PixelInfo - C.PixelGetQuantumPacket(pw.pw, &pi) - runtime.KeepAlive(pw) - return newPixelInfoFromCAPI(&pi) -} - -// Returns the normalized red color of the pixel wand -func (pw *PixelWand) GetRed() float64 { - ret := float64(C.PixelGetRed(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the red color of the pixel wand -func (pw *PixelWand) GetRedQuantum() Quantum { - ret := Quantum(C.PixelGetRedQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the normalized yellow color of the pixel wand -func (pw *PixelWand) GetYellow() float64 { - ret := float64(C.PixelGetYellow(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the yellow color of the pixel wand -func (pw *PixelWand) GetYellowQuantum() Quantum { - ret := Quantum(C.PixelGetYellowQuantum(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Sets the normalized alpha color of the pixel wand. -// 1.0 is fully opaque and 0.0 is fully transparent. -func (pw *PixelWand) SetAlpha(alpha float64) { - C.PixelSetAlpha(pw.pw, C.double(alpha)) - runtime.KeepAlive(pw) -} - -// Sets the alpha color of the pixel wand -func (pw *PixelWand) SetAlphaQuantum(opacity Quantum) { - C.PixelSetAlphaQuantum(pw.pw, C.Quantum(opacity)) - runtime.KeepAlive(pw) -} - -// Sets the normalized black color of the pixel wand -func (pw *PixelWand) SetBlack(black float64) { - C.PixelSetBlack(pw.pw, C.double(black)) - runtime.KeepAlive(pw) -} - -// Sets the black color of the pixel wand -func (pw *PixelWand) SetBlackQuantum(black Quantum) { - C.PixelSetBlackQuantum(pw.pw, C.Quantum(black)) - runtime.KeepAlive(pw) -} - -// Sets the normalized blue color of the pixel wand -func (pw *PixelWand) SetBlue(blue float64) { - C.PixelSetBlue(pw.pw, C.double(blue)) - runtime.KeepAlive(pw) -} - -// Sets the blue color of the pixel wand -func (pw *PixelWand) SetBlueQuantum(blue Quantum) { - C.PixelSetBlueQuantum(pw.pw, C.Quantum(blue)) - runtime.KeepAlive(pw) -} - -// Sets the color of the pixel wand with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.) -func (pw *PixelWand) SetColor(color string) bool { - cscolor := C.CString(color) - defer C.free(unsafe.Pointer(cscolor)) - ret := 1 == int(C.PixelSetColor(pw.pw, cscolor)) - runtime.KeepAlive(pw) - return ret -} - -// Sets the color count of the pixel wand -func (pw *PixelWand) SetColorCount(count uint) { - C.PixelSetColorCount(pw.pw, C.size_t(count)) - runtime.KeepAlive(pw) -} - -// Sets the color of the pixel wand from another one -func (pw *PixelWand) SetColorFromWand(pixelWand *PixelWand) { - C.PixelSetColorFromWand(pw.pw, pixelWand.pw) - runtime.KeepAlive(pw) -} - -// Sets the normalized cyan color of the pixel wand -func (pw *PixelWand) SetCyan(cyan float64) { - C.PixelSetCyan(pw.pw, C.double(cyan)) - runtime.KeepAlive(pw) -} - -// Sets the cyan color of the pixel wand -func (pw *PixelWand) SetCyanQuantum(cyan Quantum) { - C.PixelSetCyanQuantum(pw.pw, C.Quantum(cyan)) - runtime.KeepAlive(pw) -} - -// Sets the fuzz value of the pixel wand -func (pw *PixelWand) SetFuzz(fuzz float64) { - C.PixelSetFuzz(pw.pw, C.double(fuzz)) - runtime.KeepAlive(pw) -} - -// Sets the normalized green color of the pixel wand -func (pw *PixelWand) SetGreen(green float64) { - C.PixelSetGreen(pw.pw, C.double(green)) - runtime.KeepAlive(pw) -} - -// Sets the green color of the pixel wand -func (pw *PixelWand) SetGreenQuantum(green Quantum) { - C.PixelSetGreenQuantum(pw.pw, C.Quantum(green)) - runtime.KeepAlive(pw) -} - -// Sets the normalized HSL color of the pixel wand -func (pw *PixelWand) SetHSL(hue, saturation, brightness float64) { - C.PixelSetHSL(pw.pw, C.double(hue), C.double(saturation), C.double(brightness)) - runtime.KeepAlive(pw) -} - -// Sets the colormap index of the pixel wand -func (pw *PixelWand) SetIndex(quantum Quantum) { - C.PixelSetIndex(pw.pw, C.Quantum(quantum)) - runtime.KeepAlive(pw) -} - -// Sets the normalized magenta color of the pixel wand -func (pw *PixelWand) SetMagenta(magenta float64) { - C.PixelSetMagenta(pw.pw, C.double(magenta)) - runtime.KeepAlive(pw) -} - -// Sets the magenta color of the pixel wand -func (pw *PixelWand) SetMagentaQuantum(magenta Quantum) { - C.PixelSetMagentaQuantum(pw.pw, C.Quantum(magenta)) - runtime.KeepAlive(pw) -} - -// Deprecated: Use SetAlpha() -func (pw *PixelWand) SetOpacity(opacity float64) { - pw.SetAlpha(opacity) -} - -// Deprecared: USe SetAlphaQuantum() -func (pw *PixelWand) SetOpacityQuantum(opacity Quantum) { - pw.SetAlphaQuantum(opacity) -} - -// Deprecared: Use SetPixelColor -func (pw *PixelWand) SetMagickColor(color *PixelInfo) { - C.PixelSetPixelColor(pw.pw, color.pi) - runtime.KeepAlive(pw) -} - -// Sets the color of the pixel wand -func (pw *PixelWand) SetPixelColor(color *PixelInfo) { - C.PixelSetPixelColor(pw.pw, color.pi) - runtime.KeepAlive(pw) -} - -// Sets the normalized red color of the pixel wand -func (pw *PixelWand) SetRed(red float64) { - C.PixelSetRed(pw.pw, C.double(red)) - runtime.KeepAlive(pw) -} - -// Sets the red color of the pixel wand -func (pw *PixelWand) SetRedQuantum(red Quantum) { - C.PixelSetRedQuantum(pw.pw, C.Quantum(red)) - runtime.KeepAlive(pw) -} - -// Sets the normalized yellow color of the pixel wand -func (pw *PixelWand) SetYellow(yellow float64) { - C.PixelSetYellow(pw.pw, C.double(yellow)) - runtime.KeepAlive(pw) -} - -// Sets the yellow color of the pixel wand -func (pw *PixelWand) SetYellowQuantum(yellow Quantum) { - C.PixelSetYellowQuantum(pw.pw, C.Quantum(yellow)) - runtime.KeepAlive(pw) -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand_exception.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand_exception.go deleted file mode 100644 index ec778fdf..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/pixel_wand_exception.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -import ( - "fmt" - "runtime" - "unsafe" -) - -type PixelWandException struct { - kind ExceptionType - description string -} - -func (pwe *PixelWandException) Error() string { - return fmt.Sprintf("%s: %s", pwe.kind.String(), pwe.description) -} - -// Clears any exceptions associated with the wand -func (pw *PixelWand) clearException() bool { - ret := 1 == C.int(C.PixelClearException(pw.pw)) - runtime.KeepAlive(pw) - return ret -} - -// Returns the kind, reason and description of any error that occurs when using other methods in this API -func (pw *PixelWand) GetLastError() error { - var et C.ExceptionType - csdescription := C.PixelGetException(pw.pw, &et) - defer relinquishMemory(unsafe.Pointer(csdescription)) - if ExceptionType(et) != EXCEPTION_UNDEFINED { - pw.clearException() - return &PixelWandException{ExceptionType(C.int(et)), C.GoString(csdescription)} - } - runtime.KeepAlive(pw) - return nil -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/point_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/point_info.go deleted file mode 100644 index 15d3f01e..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/point_info.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PointInfo struct { - X float64 - Y float64 -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/preview_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/preview_type.go deleted file mode 100644 index ba5f3d0a..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/preview_type.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type PreviewType int - -const ( - PREVIEW_UNDEFINED PreviewType = C.UndefinedPreview - PREVIEW_ROTATE PreviewType = C.RotatePreview - PREVIEW_SHEAR PreviewType = C.ShearPreview - PREVIEW_ROLL PreviewType = C.RollPreview - PREVIEW_HUE PreviewType = C.HuePreview - PREVIEW_SATURATION PreviewType = C.SaturationPreview - PREVIEW_BRIGHTNESS PreviewType = C.BrightnessPreview - PREVIEW_GAMMA PreviewType = C.GammaPreview - PREVIEW_SPIFF PreviewType = C.SpiffPreview - PREVIEW_DULL PreviewType = C.DullPreview - PREVIEW_GRAYSCALE PreviewType = C.GrayscalePreview - PREVIEW_QUANTIZE PreviewType = C.QuantizePreview - PREVIEW_DESPECKLE PreviewType = C.DespecklePreview - PREVIEW_REDUCE_NOISE PreviewType = C.ReduceNoisePreview - PREVIEW_ADD_NOISE PreviewType = C.AddNoisePreview - PREVIEW_SHARPEN PreviewType = C.SharpenPreview - PREVIEW_BLUR PreviewType = C.BlurPreview - PREVIEW_THRESHOLD PreviewType = C.ThresholdPreview - PREVIEW_EDGE_DETECT PreviewType = C.EdgeDetectPreview - PREVIEW_SPREAD PreviewType = C.SpreadPreview - PREVIEW_SOLARIZE PreviewType = C.SolarizePreview - PREVIEW_SHADE PreviewType = C.ShadePreview - PREVIEW_RAISE PreviewType = C.RaisePreview - PREVIEW_SEGMENT PreviewType = C.SegmentPreview - PREVIEW_SWIRL PreviewType = C.SwirlPreview - PREVIEW_IMPLODE PreviewType = C.ImplodePreview - PREVIEW_WAVE PreviewType = C.WavePreview - PREVIEW_OIL_PAINT PreviewType = C.OilPaintPreview - PREVIEW_CHARCOAL_DRAWING PreviewType = C.CharcoalDrawingPreview - PREVIEW_JPEG PreviewType = C.JPEGPreview -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/quantum.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/quantum.go deleted file mode 100644 index 7f9e1ce8..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/quantum.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type Quantum C.Quantum - -//const QUANTUM_RANGE = C.QuantumRange diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/rectangle_info.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/rectangle_info.go deleted file mode 100644 index 3edfc97e..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/rectangle_info.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type RectangleInfo struct { - info *C.RectangleInfo -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/rendering_intent.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/rendering_intent.go deleted file mode 100644 index 638abd20..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/rendering_intent.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type RenderingIntent int - -const ( - RENDERING_INTENT_UNDEFINED RenderingIntent = C.UndefinedIntent - RENDERING_INTENT_SATURATION RenderingIntent = C.SaturationIntent - RENDERING_INTENT_PERCEPTUAL RenderingIntent = C.PerceptualIntent - RENDERING_INTENT_ABSOLUTE RenderingIntent = C.AbsoluteIntent - RENDERING_INTENT_RELATIVE RenderingIntent = C.RelativeIntent -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/resolution_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/resolution_type.go deleted file mode 100644 index b9d2b1a9..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/resolution_type.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ResolutionType int - -const ( - RESOLUTION_UNDEFINED ResolutionType = C.UndefinedResolution - RESOLUTION_PIXELS_PER_INCH ResolutionType = C.PixelsPerInchResolution - RESOLUTION_PIXELS_PER_CENTIMETER ResolutionType = C.PixelsPerCentimeterResolution -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/resource_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/resource_type.go deleted file mode 100644 index 68d7ef8b..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/resource_type.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type ResourceType int - -const ( - RESOURCE_UNDEFINED ResourceType = C.UndefinedResource - RESOURCE_AREA ResourceType = C.AreaResource - RESOURCE_DISK ResourceType = C.DiskResource - RESOURCE_FILE ResourceType = C.FileResource - RESOURCE_MAP ResourceType = C.MapResource - RESOURCE_MEMORY ResourceType = C.MemoryResource - RESOURCE_THREAD ResourceType = C.ThreadResource - RESOURCE_TIME ResourceType = C.TimeResource - RESOURCE_THROTTLE ResourceType = C.ThrottleResource -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/sparse_color_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/sparse_color_method.go deleted file mode 100644 index d0f89e89..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/sparse_color_method.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type SparseColorMethod int - -const ( - INTERPOLATE_UNDEFINED_COLOR SparseColorMethod = C.UndefinedColorInterpolate - INTERPOLATE_BARYCENTRIC_COLOR SparseColorMethod = C.BarycentricColorInterpolate - INTERPOLATE_BILINEAR_COLOR SparseColorMethod = C.BilinearColorInterpolate - INTERPOLATE_POLYNOMIAL_COLOR SparseColorMethod = C.PolynomialColorInterpolate - INTERPOLATE_SHEPARDS_COLOR SparseColorMethod = C.ShepardsColorInterpolate - INTERPOLATE_VORONOI_COLOR SparseColorMethod = C.VoronoiColorInterpolate - INTERPOLATE_INVERSE_COLOR SparseColorMethod = C.InverseColorInterpolate -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/spread_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/spread_method.go deleted file mode 100644 index 02ccc5c0..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/spread_method.go +++ /dev/null @@ -1,15 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" - -type SpreadMethod int - -const ( - SPREAD_METHOD_UNDEFINED SpreadMethod = C.UndefinedGradient - SPREAD_METHOD_PAD SpreadMethod = C.PadSpread - SPREAD_METHOD_REFLECT SpreadMethod = C.ReflectSpread - SPREAD_METHOD_REPEAT SpreadMethod = C.RepeatSpread -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic.go deleted file mode 100644 index 74d6982c..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic.go +++ /dev/null @@ -1,25 +0,0 @@ -package imagick - -/* -#include -*/ -import "C" -import "runtime" - -// GetImageEntropy returns the entropy of one or more image channels. -func (mw *MagickWand) GetImageEntropy() (entropy float64, err error) { - img := mw.GetImageFromMagickWand() - - var exc *C.ExceptionInfo = C.AcquireExceptionInfo() - defer C.DestroyExceptionInfo(exc) - - ok := C.GetImageEntropy(img.img, (*C.double)(&entropy), exc) - if C.int(ok) == 0 { - return entropy, newExceptionInfo(exc) - } - - runtime.KeepAlive(mw) - runtime.KeepAlive(img) - - return entropy, nil -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic_type.go deleted file mode 100644 index f0713771..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/statistic_type.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type StatisticType int - -const ( - STATISTIC_UNDEFINED StatisticType = C.UndefinedStatistic - STATISTIC_GRADIENT StatisticType = C.GradientStatistic - STATISTIC_MAXIMUM StatisticType = C.MaximumStatistic - STATISTIC_MEAN StatisticType = C.MeanStatistic - STATISTIC_MEDIAN StatisticType = C.MedianStatistic - STATISTIC_MINIMUM StatisticType = C.MinimumStatistic - STATISTIC_MODE StatisticType = C.ModeStatistic - STATISTIC_NONPEAK StatisticType = C.NonpeakStatistic - STATISTIC_STANDARD_DEVIATION StatisticType = C.StandardDeviationStatistic -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/storage_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/storage_type.go deleted file mode 100644 index 5b8e93f3..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/storage_type.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type StorageType int - -const ( - PIXEL_UNDEFINED StorageType = C.UndefinedPixel - PIXEL_CHAR StorageType = C.CharPixel - PIXEL_DOUBLE StorageType = C.DoublePixel - PIXEL_FLOAT StorageType = C.FloatPixel - PIXEL_LONGLONG StorageType = C.LongLongPixel - PIXEL_LONG StorageType = C.LongPixel - PIXEL_QUANTUM StorageType = C.QuantumPixel - PIXEL_SHORT StorageType = C.ShortPixel -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/stretch_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/stretch_type.go deleted file mode 100644 index c60225e4..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/stretch_type.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type StretchType int - -const ( - STRETCH_UNDEFINED StretchType = C.UndefinedStretch - STRETCH_NORMAL StretchType = C.NormalStretch - STRETCH_ULTRA_CONDENSED StretchType = C.UltraCondensedStretch - STRETCH_EXTRA_CONDENSED StretchType = C.ExtraCondensedStretch - STRETCH_CONDENSED StretchType = C.CondensedStretch - STRETCH_SEMI_CONDENSED StretchType = C.SemiCondensedStretch - STRETCH_SEMI_EXPANDED StretchType = C.SemiExpandedStretch - STRETCH_EXPANDED StretchType = C.ExpandedStretch - STRETCH_EXTRA_EXPANDED StretchType = C.ExtraExpandedStretch - STRETCH_ULTRA_EXPANDED StretchType = C.UltraExpandedStretch - STRETCH_ANY StretchType = C.AnyStretch -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/style_type.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/style_type.go deleted file mode 100644 index 79f38059..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/style_type.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type StyleType int - -const ( - STYLE_UNDEFINED StyleType = C.UndefinedStyle - STYLE_NORMAL StyleType = C.NormalStyle - STYLE_ITALIC StyleType = C.ItalicStyle - STYLE_OBLIQUE StyleType = C.ObliqueStyle - STYLE_ANYSTYLE StyleType = C.AnyStyle -) diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/clearer.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/clearer.go deleted file mode 100644 index 4ea86028..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/clearer.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -type Clearer interface { - Clear() -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/decreaser.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/decreaser.go deleted file mode 100644 index eeed95e3..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/decreaser.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -type Decreaser interface { - DecreaseCount() -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/destroyer.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/destroyer.go deleted file mode 100644 index f8da24fa..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/destroyer.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -// Destroyer represents destroyable types which require manual release of resources -type Destroyer interface { - Destroy() -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/imagick.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/imagick.go deleted file mode 100644 index 99c3f6ed..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/imagick.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -// ImageMagick objects common interface -type IMagick interface { - Clearer - Destroyer - Verifier - Increaser - Decreaser -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/increaser.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/increaser.go deleted file mode 100644 index 99d362ad..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/increaser.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -type Increaser interface { - IncreaseCount() -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/verifier.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/types/verifier.go deleted file mode 100644 index d41733ce..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/types/verifier.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -// Returns true if the object is a verified C object -type Verifier interface { - IsVerified() bool -} diff --git a/vendor/gopkg.in/gographics/imagick.v3/imagick/virtual_pixel_method.go b/vendor/gopkg.in/gographics/imagick.v3/imagick/virtual_pixel_method.go deleted file mode 100644 index 4183961f..00000000 --- a/vendor/gopkg.in/gographics/imagick.v3/imagick/virtual_pixel_method.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2013 Herbert G. Fischer. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package imagick - -/* -#include -*/ -import "C" - -type VirtualPixelMethod int - -const ( - VIRTUAL_PIXEL_UNDEFINED VirtualPixelMethod = C.UndefinedVirtualPixelMethod - VIRTUAL_PIXEL_BACKGROUND VirtualPixelMethod = C.BackgroundVirtualPixelMethod - VIRTUAL_PIXEL_BLACK VirtualPixelMethod = C.BlackVirtualPixelMethod - VIRTUAL_PIXEL_CHECKER_TILE VirtualPixelMethod = C.CheckerTileVirtualPixelMethod - VIRTUAL_PIXEL_DITHER VirtualPixelMethod = C.DitherVirtualPixelMethod - VIRTUAL_PIXEL_EDGE VirtualPixelMethod = C.EdgeVirtualPixelMethod - VIRTUAL_PIXEL_GRAY VirtualPixelMethod = C.GrayVirtualPixelMethod - VIRTUAL_PIXEL_HORIZONTAL_TILE VirtualPixelMethod = C.HorizontalTileVirtualPixelMethod - VIRTUAL_PIXEL_HORIZONTAL_TILE_EDGE VirtualPixelMethod = C.HorizontalTileEdgeVirtualPixelMethod - VIRTUAL_PIXEL_MASK VirtualPixelMethod = C.MaskVirtualPixelMethod - VIRTUAL_PIXEL_MIRROR VirtualPixelMethod = C.MirrorVirtualPixelMethod - VIRTUAL_PIXEL_RANDOM VirtualPixelMethod = C.RandomVirtualPixelMethod - VIRTUAL_PIXEL_TILE VirtualPixelMethod = C.TileVirtualPixelMethod - VIRTUAL_PIXEL_TRANSPARENT VirtualPixelMethod = C.TransparentVirtualPixelMethod - VIRTUAL_PIXEL_VERTICAL_TILE VirtualPixelMethod = C.VerticalTileVirtualPixelMethod - VIRTUAL_PIXEL_VERTICAL_TILE_EDGE VirtualPixelMethod = C.VerticalTileEdgeVirtualPixelMethod - VIRTUAL_PIXEL_WHITE VirtualPixelMethod = C.WhiteVirtualPixelMethod -) diff --git a/vendor/modules.txt b/vendor/modules.txt index 08879907..9adefeb9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -522,10 +522,6 @@ google.golang.org/protobuf/types/descriptorpb google.golang.org/protobuf/types/known/anypb google.golang.org/protobuf/types/known/durationpb google.golang.org/protobuf/types/known/timestamppb -# gopkg.in/gographics/imagick.v3 v3.4.2 -## explicit; go 1.13 -gopkg.in/gographics/imagick.v3/imagick -gopkg.in/gographics/imagick.v3/imagick/types # gopkg.in/ini.v1 v1.67.0 ## explicit gopkg.in/ini.v1 diff --git a/werf.yaml b/werf.yaml index c9019db9..a0dece5c 100644 --- a/werf.yaml +++ b/werf.yaml @@ -38,6 +38,6 @@ import: after: setup - image: builder - add: /go/src/github.com/Digital-Certificates-DL/certificates-svc/staff - to: /usr/local/bin/staff + add: /go/src/github.com/Digital-Certificates-DL/certificates-svc/static + to: /static after: setup \ No newline at end of file