diff --git a/.circleci/config.yml b/.circleci/config.yml index cedd39c1..930c89f6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,21 +4,25 @@ jobs: build: docker: # using custom image, see .circleci/images/primary/Dockerfile - - image: govgo/robotgoci:1.10.3 + # - image: govgo/robotgoci:1.10.3 + - image: golang:1.23.0 working_directory: /gopath/src/github.com/go-vgo/robotgo steps: - checkout # specify any bash command here prefixed with `run: ` - - run: apt-get update - - run: apt-get -y install xvfb + - run: apt update + - run: + apt -y install gcc libc6-dev + libx11-dev xorg-dev libxtst-dev + xsel xclip + # libpng++-dev + # xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev libxkbcommon-dev + - run: apt -y install xvfb # # override: - # './...' is a relative pattern which means all subdirectories - # - run: go get -u github.com/go-vgo/robotgo - # - run: go get -u golang.org/x/sys/unix - # - run: go get -u github.com/shirou/gopsutil - run: go get -v -t -d ./... - run: xvfb-run go test -v ./... + # # codecov.io # - run: xvfb-run go test -v -covermode=count -coverprofile=coverage.out # - run: bash <(curl -s https://codecov.io/bash) diff --git a/.circleci/images/primary/Dockerfile b/.circleci/images/primary/Dockerfile index fc0e4241..ff104e61 100644 --- a/.circleci/images/primary/Dockerfile +++ b/.circleci/images/primary/Dockerfile @@ -1,25 +1,22 @@ # FROM golang:1.10.1 -FROM golang:1.14.4-stretch AS build +FROM golang:1.24.2-stretch AS build # FROM govgo/go:1.11.1 -RUN apt-get update && apt-get install -y --no-install-recommends \ -# customize dependencies +RUN apt update && apt install -y --no-install-recommends \ + # customize dependencies libx11-dev xorg-dev \ - # libgtkglextmm-x11-dev - # libghc6-x11-dev - # libgl1-mesa-swx11-dev - # xorg-dev - libxtst-dev libpng++-dev \ -# Event: + libxtst-dev \ + # Bitmap + libpng++-dev \ + # Event: xcb libxcb-xkb-dev \ x11-xkb-utils libx11-xcb-dev \ libxkbcommon-x11-dev libxkbcommon-dev \ -# Clipboard: + # Clipboard: xsel xclip && \ -# RUN apt-get install -y xclip -# - apt-get remove --purge --auto-remove && \ - apt-get clean && \ + # + apt remove --purge --auto-remove && \ + apt clean && \ rm -rf /var/lib/apt/lists/* RUN go get -u github.com/go-vgo/robotgo \ No newline at end of file diff --git a/.github/issue_template.md b/.github/issue_template.md index 09f368c5..3606506c 100644 --- a/.github/issue_template.md +++ b/.github/issue_template.md @@ -1,11 +1,12 @@ -1. Please **speak English**, this is the language everybody of us can speak and write. +1. Please **speak English (English only)**, this is the language everybody of us can speak and write. 2. Please take a moment to **search** that an issue **doesn't already exist**. 3. Please make sure `Golang, GCC` is installed correctly before installing RobotGo. -4. Please ask questions or config/deploy problems on our Gitter channel: https://gitter.im/go-vgo/robotgo + 5. Please give all relevant information below for bug reports, incomplete details will be handled as an invalid report. **You MUST delete the content above including this line before posting, otherwise your issue will be invalid.** + - Robotgo version (or commit ref): - Go version: - Gcc version: diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b6fa0cfa..cd8ee71f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,10 +5,11 @@ The pull request will be closed without any reasons if it does not satisfy any o 3. Please read contributing guidelines: [CONTRIBUTING](https://github.com/go-vgo/robotgo/blob/master/CONTRIBUTING.md) 4. Describe what your pull request does and which issue you're targeting (if any and **Please use English**) 5. ... if it is not related to any particular issues, explain why we should not reject your pull request. -6. The Commits must use English, must be test and No useless submissions. +6. The Commits must **use English**, must be test and No useless submissions. **You MUST delete the content above including this line before posting, otherwise your pull request will be invalid.** + **Please provide Issues links to:** - Issues: #1 diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 4e5bb5da..aab570a3 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -10,10 +10,10 @@ jobs: runs-on: ${{ matrix.os }} steps: - - name: Set up Go 1.14 + - name: Set up Go 1.24.0 uses: actions/setup-go@v1 with: - go-version: 1.14 + go-version: 1.24.0 id: go - name: Check out code into the Go module directory @@ -22,10 +22,6 @@ jobs: - name: Get dependencies run: | go get -v -t -d ./... - # if [ -f Gopkg.toml ]; then - # curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - # dep ensure - # fi - name: Build run: go build -v . diff --git a/.gitignore b/.gitignore index cbf0a0a7..c00b3573 100644 --- a/.gitignore +++ b/.gitignore @@ -56,8 +56,14 @@ vendor # ## *.a !cdeps/mac/libpng.a +!cdeps/mac/amd/libpng.a +!cdeps/mac/m1/libpng.a +# !cdeps/win32/libpng.a !cdeps/win64/libpng.a +!cdeps/win/amd/win32/libpng.a +!cdeps/win/amd/win64/libpng.a +!cdeps/win/arm/libpng.a # *.la *.lo @@ -78,3 +84,15 @@ vendor # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ + +# +examples/bitmap/test_IMG.png +examples/bitmap/imgToBitmap/test_01.png +examples/bitmap/imgToBitmap/test_002.jpeg +examples/bitmap/imgToBitmap/test_003.jpeg +examples/bitmap/imgToBitmap/test_1.png +examples/bitmap/imgToBitmap/test_2.jpeg +examples/bitmap/imgToBitmap/test.png +examples/bitmap/imgToBitmap/test_7.jpeg +robot_img.png +examples/bitmap/bitmapTobytes/out.jpg diff --git a/.travis.yml b/.travis.yml index c26c52dd..4d2c3fb1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,12 @@ go: # - 1.11.x # - 1.12.x # - 1.13.x - - 1.14.x + # - 1.14.x + # - 1.15.x + # - 1.16.x + # - 1.17.x + # - 1.18.x + - 1.19.x # - tip addons: @@ -28,16 +33,16 @@ addons: # - xvfb # script: -# - sudo apt-get update -# - sudo apt-get install libx11-dev -# - sudo apt-get install xorg-dev -# - sudo apt-get install libxtst-dev libpng++-dev +# - sudo apt update +# - sudo apt install libx11-dev +# - sudo apt install xorg-dev +# - sudo apt install libxtst-dev libpng++-dev # # Event: -# - sudo apt-get install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev -# - sudo apt-get install libxkbcommon-dev +# - sudo apt install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev +# - sudo apt install libxkbcommon-dev # # Clipboard: -# - sudo apt-get install xsel -# - sudo apt-get install xclip +# - sudo apt install xsel +# - sudo apt install xclip # - go test -v . before_install: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e36d624..e136b21d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,26 +24,24 @@ This process gives everyone a chance to validate the design, helps prevent dupli ## Testing redux -Before sending code out for review, run all the tests for the whole tree to make sure the changes don't break other usage and keep the compatibility on upgrade. You must be test on Mac, Windows, Linux and other. You should install the CLI for Circle CI, as we are using the server for continous testing. +Before sending code out for review, run all the tests for the whole tree to make sure the changes don't break other usage and keep the compatibility on upgrade. You must be test on Mac, Windows, Linux and other. You should install the CLI for Circle CI, as we are using the server for continuous testing. ## Code review In addition to the owner, Changes to Robotgo must be reviewed before they are accepted, no matter who makes the change even if it is a maintainer. We use GitHub's pull request workflow to do that and we also use [LGTM](http://lgtm.co) to ensure every PR is reviewed by vz or least 2 maintainers. - ## Sign your work -The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. +The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. ## Maintainers -To make sure every PR is checked, we got team maintainers. A maintainer should be a contributor of Robotgo and contributed at least 4 accepted PRs. +To make sure every PR is checked, we got team maintainers. A maintainer should be a contributor of Robotgo and contributed at least 4 accepted PRs. ## Owners Since Robotgo is a pure community organization without any company support, Copyright 2016 The go-vgo Project Developers. - ## Versions Robotgo has the `master` branch as a tip branch and has version branches such as `v0.30.0`. `v0.40.0` is a release branch and we will tag `v0.40.0` for binary download. If `v0.40.0` has bugs, we will accept pull requests on the `v0.40.0` branch and publish a `v0.40.1` tag, after bringing the bug fix also to the master branch. @@ -60,9 +58,9 @@ Code that you contribute should use the standard copyright header: // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. ``` diff --git a/README.md b/README.md index fb20294a..bcf7478c 100644 --- a/README.md +++ b/README.md @@ -4,31 +4,33 @@ + [![Build Status](https://github.com/go-vgo/robotgo/workflows/Go/badge.svg)](https://github.com/go-vgo/robotgo/commits/master) [![CircleCI Status](https://circleci.com/gh/go-vgo/robotgo.svg?style=shield)](https://circleci.com/gh/go-vgo/robotgo) [![Build Status](https://travis-ci.org/go-vgo/robotgo.svg)](https://travis-ci.org/go-vgo/robotgo) ![Appveyor](https://ci.appveyor.com/api/projects/status/github/go-vgo/robotgo?branch=master&svg=true) [![Go Report Card](https://goreportcard.com/badge/github.com/go-vgo/robotgo)](https://goreportcard.com/report/github.com/go-vgo/robotgo) -[![GoDoc](https://godoc.org/github.com/go-vgo/robotgo?status.svg)](https://godoc.org/github.com/go-vgo/robotgo) +[![GoDoc](https://pkg.go.dev/badge/github.com/go-vgo/robotgo?status.svg)](https://pkg.go.dev/github.com/go-vgo/robotgo?tab=doc) [![GitHub release](https://img.shields.io/github/release/go-vgo/robotgo.svg)](https://github.com/go-vgo/robotgo/releases/latest) [![Join the chat at https://gitter.im/go-vgo/robotgo](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-vgo/robotgo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + - >Golang Desktop Automation. Control the mouse, keyboard, bitmap, read the screen, Window Handle and global event listener. +> Golang Desktop Automation. Control the mouse, keyboard, read the screen, process, Window Handle, image and bitmap and global event listener. -RobotGo supports Mac, Windows, and Linux(X11). - -[Chinese Simplified](https://github.com/go-vgo/robotgo/blob/master/README_zh.md) +RobotGo supports Mac, Windows, and Linux(X11); and robotgo supports arm64 and x86-amd64. ## Contents + - [Docs](#docs) - [Binding](#binding) - [Requirements](#requirements) - [Installation](#installation) - [Update](#update) - [Examples](#examples) -- [Cross-Compiling](#crosscompiling) +- [Type Conversion and keys](https://github.com/go-vgo/robotgo/blob/master/docs/keys.md) +- [Cross-Compiling](https://github.com/go-vgo/robotgo/blob/master/docs/install.md#crosscompiling) - [Authors](#authors) - [Plans](#plans) - [Donate](#donate) @@ -36,12 +38,14 @@ RobotGo supports Mac, Windows, and Linux(X11). - [License](#license) ## Docs - - [GoDoc](https://godoc.org/github.com/go-vgo/robotgo) - - [API Docs](https://github.com/go-vgo/robotgo/blob/master/docs/doc.md)     - - [Chinese Docs](https://github.com/go-vgo/robotgo/blob/master/docs/doc_zh.md) + +- [GoDoc](https://godoc.org/github.com/go-vgo/robotgo)
+- [API Docs](https://github.com/go-vgo/robotgo/blob/master/docs/doc.md) (Deprecated, no updated) ## Binding: +[ADB](https://github.com/vcaesar/adb), packaging android adb API. + [Robotn](https://github.com/vcaesar/robotn), binding JavaScript and other, support more language. ## Requirements: @@ -49,66 +53,118 @@ RobotGo supports Mac, Windows, and Linux(X11). Now, Please make sure `Golang, GCC` is installed correctly before installing RobotGo. ### ALL: + ``` Golang GCC ``` -#### For Mac OS X: +#### For MacOS: + +``` +brew install go +``` + +Xcode Command Line Tools (And Privacy setting: [#277](https://github.com/go-vgo/robotgo/issues/277)) + ``` -Xcode Command Line Tools +xcode-select --install ``` #### For Windows: + ``` -MinGW-w64 (Use recommended) or other GCC +winget install Golang.go ``` +``` +winget install MartinStorsjo.LLVM-MinGW.UCRT +``` + +Or [MinGW-w64](https://sourceforge.net/projects/mingw-w64/files) (Use recommended) or others Mingw [llvm-mingw](https://github.com/mstorsjo/llvm-mingw); + +Download the Mingw, then set system environment variables `C:\mingw64\bin` to the Path. +[Set environment variables to run GCC from command line](https://www.youtube.com/results?search_query=Set+environment+variables+to+run+GCC+from+command+line). + +`Or the other GCC` (But you should compile the "libpng" with yourself when use the [bitmap](https://github.com/vcaesar/bitmap).) + #### For everything else: ``` -GCC, libpng +GCC -X11 with the XTest extension (also known as the Xtst library) +X11 with the XTest extension (the Xtst library) -Event: +"Clipboard": xsel xclip + + +"Bitmap": libpng (Just used by the "bitmap".) + +"Event-Gohook": xcb, xkb, libxkbcommon (Just used by the "hook".) -xcb, xkb, libxkbcommon ``` ##### Ubuntu: ```yml -sudo apt-get install gcc libc6-dev +# sudo apt install golang +sudo snap install go --classic + +# gcc +sudo apt install gcc libc6-dev + +# x11 +sudo apt install libx11-dev xorg-dev libxtst-dev + +# Clipboard +sudo apt install xsel xclip -sudo apt-get install libx11-dev xorg-dev libxtst-dev libpng++-dev +# +# Bitmap +sudo apt install libpng++-dev -sudo apt-get install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev -sudo apt-get install libxkbcommon-dev +# GoHook +sudo apt install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev libxkbcommon-dev -sudo apt-get install xsel xclip ``` -#### Fedora: +##### Fedora: ```yml -sudo dnf install libxkbcommon-devel libXtst-devel libxkbcommon-x11-devel xorg-x11-xkb-utils-devel +# x11 +sudo dnf install libXtst-devel +# Clipboard +sudo dnf install xsel xclip + +# +# Bitmap sudo dnf install libpng-devel -sudo dnf install xsel xclip +# GoHook +sudo dnf install libxkbcommon-devel libxkbcommon-x11-devel xorg-x11-xkb-utils-devel + ``` ## Installation: + +With Go module support (Go 1.11+), just import: + +```go +import "github.com/go-vgo/robotgo" +``` + +Otherwise, to install the robotgo package, run the command: + ``` go get github.com/go-vgo/robotgo ``` - It's that easy! png.h: No such file or directory? Please see [issues/47](https://github.com/go-vgo/robotgo/issues/47). ## Update: + ``` go get -u github.com/go-vgo/robotgo ``` @@ -116,7 +172,6 @@ go get -u github.com/go-vgo/robotgo Note go1.10.x C file compilation cache problem, [golang #24355](https://github.com/golang/go/issues/24355). `go mod vendor` problem, [golang #26366](https://github.com/golang/go/issues/26366). - ## [Examples:](https://github.com/go-vgo/robotgo/blob/master/examples) #### [Mouse](https://github.com/go-vgo/robotgo/blob/master/examples/mouse/main.go) @@ -125,13 +180,39 @@ Note go1.10.x C file compilation cache problem, [golang #24355](https://github.c package main import ( - "github.com/go-vgo/robotgo" + "fmt" + "github.com/go-vgo/robotgo" ) func main() { - robotgo.ScrollMouse(10, "up") - robotgo.MouseClick("left", true) - robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) + robotgo.MouseSleep = 300 + + robotgo.Move(100, 100) + fmt.Println(robotgo.Location()) + robotgo.Move(100, -200) // multi screen supported + robotgo.MoveSmooth(120, -150) + fmt.Println(robotgo.Location()) + + robotgo.ScrollDir(10, "up") + robotgo.ScrollDir(20, "right") + + robotgo.Scroll(0, -10) + robotgo.Scroll(100, 0) + + robotgo.MilliSleep(100) + robotgo.ScrollSmooth(-10, 6) + // robotgo.ScrollRelative(10, -100) + + robotgo.Move(10, 20) + robotgo.MoveRelative(0, -10) + robotgo.DragSmooth(10, 10) + + robotgo.Click("wheelRight") + robotgo.Click("left", true) + robotgo.MoveSmooth(100, 200, 1.0, 10.0) + + robotgo.Toggle("left") + robotgo.Toggle("left", "up") } ``` @@ -148,22 +229,28 @@ import ( func main() { robotgo.TypeStr("Hello World") - robotgo.TypeStr("だんしゃり", 1.0) - // robotgo.TypeString("テストする") + robotgo.TypeStr("だんしゃり", 0, 1) + // robotgo.TypeStr("テストする") - robotgo.TypeStr("Hi galaxy. こんにちは世界.") + robotgo.TypeStr("Hi, Seattle space needle, Golden gate bridge, One world trade center.") + robotgo.TypeStr("Hi galaxy, hi stars, hi MT.Rainier, hi sea. こんにちは世界.") robotgo.Sleep(1) // ustr := uint32(robotgo.CharCodeAt("Test", 0)) // robotgo.UnicodeType(ustr) + robotgo.KeySleep = 100 robotgo.KeyTap("enter") - // robotgo.TypeString("en") - robotgo.KeyTap("i", "alt", "command") + // robotgo.TypeStr("en") + robotgo.KeyTap("i", "alt", "cmd") - arr := []string{"alt", "command"} + arr := []string{"alt", "cmd"} robotgo.KeyTap("i", arr) + robotgo.MilliSleep(100) + robotgo.KeyToggle("a") + robotgo.KeyToggle("a", "up") + robotgo.WriteAll("Test") text, err := robotgo.ReadAll() if err == nil { @@ -178,83 +265,203 @@ func main() { package main import ( - "fmt" + "fmt" + "strconv" - "github.com/go-vgo/robotgo" + "github.com/go-vgo/robotgo" + "github.com/vcaesar/imgo" ) func main() { - x, y := robotgo.GetMousePos() + x, y := robotgo.Location() fmt.Println("pos: ", x, y) color := robotgo.GetPixelColor(100, 200) fmt.Println("color---- ", color) + + sx, sy := robotgo.GetScreenSize() + fmt.Println("get screen size: ", sx, sy) + + bit := robotgo.CaptureScreen(10, 10, 30, 30) + defer robotgo.FreeBitmap(bit) + + img := robotgo.ToImage(bit) + imgo.Save("test.png", img) + + num := robotgo.DisplaysNum() + for i := 0; i < num; i++ { + robotgo.DisplayID = i + img1, _ := robotgo.CaptureImg() + path1 := "save_" + strconv.Itoa(i) + robotgo.Save(img1, path1+".png") + robotgo.SaveJpeg(img1, path1+".jpeg", 50) + + img2, _ := robotgo.CaptureImg(10, 10, 20, 20) + robotgo.Save(img2, "test_"+strconv.Itoa(i)+".png") + + x, y, w, h := robotgo.GetDisplayBounds(i) + img3, err := robotgo.CaptureImg(x, y, w, h) + fmt.Println("Capture error: ", err) + robotgo.Save(img3, path1+"_1.png") + } } ``` -#### [Bitmap](https://github.com/go-vgo/robotgo/blob/master/examples/bitmap/main.go) +#### [Bitmap](https://github.com/vcaesar/bitmap/blob/main/examples/main.go) ```Go package main import ( - "fmt" + "fmt" - "github.com/go-vgo/robotgo" + "github.com/go-vgo/robotgo" + "github.com/vcaesar/bitmap" ) func main() { - bitmap := robotgo.CaptureScreen(10, 20, 30, 40) + bit := robotgo.CaptureScreen(10, 20, 30, 40) // use `defer robotgo.FreeBitmap(bit)` to free the bitmap - defer robotgo.FreeBitmap(bitmap) + defer robotgo.FreeBitmap(bit) - fmt.Println("...", bitmap) + fmt.Println("bitmap...", bit) + img := robotgo.ToImage(bit) + // robotgo.SavePng(img, "test_1.png") + robotgo.Save(img, "test_1.png") - fx, fy := robotgo.FindBitmap(bitmap) + bit2 := robotgo.ToCBitmap(robotgo.ImgToBitmap(img)) + fx, fy := bitmap.Find(bit2) fmt.Println("FindBitmap------ ", fx, fy) + robotgo.Move(fx, fy) + + arr := bitmap.FindAll(bit2) + fmt.Println("Find all bitmap: ", arr) - robotgo.SaveBitmap(bitmap, "test.png") + fx, fy = bitmap.Find(bit) + fmt.Println("FindBitmap------ ", fx, fy) + + bitmap.Save(bit, "test.png") } ``` -#### [Event](https://github.com/go-vgo/robotgo/blob/master/examples/gohook/main.go) +#### [OpenCV](https://github.com/vcaesar/gcv) ```Go package main import ( - "fmt" + "fmt" + "math/rand" "github.com/go-vgo/robotgo" + "github.com/vcaesar/gcv" + "github.com/vcaesar/bitmap" +) + +func main() { + opencv() +} + +func opencv() { + name := "test.png" + name1 := "test_001.png" + robotgo.SaveCapture(name1, 10, 10, 30, 30) + robotgo.SaveCapture(name) + + fmt.Print("gcv find image: ") + fmt.Println(gcv.FindImgFile(name1, name)) + fmt.Println(gcv.FindAllImgFile(name1, name)) + + bit := bitmap.Open(name1) + defer robotgo.FreeBitmap(bit) + fmt.Print("find bitmap: ") + fmt.Println(bitmap.Find(bit)) + + // bit0 := robotgo.CaptureScreen() + // img := robotgo.ToImage(bit0) + // bit1 := robotgo.CaptureScreen(10, 10, 30, 30) + // img1 := robotgo.ToImage(bit1) + // defer robotgo.FreeBitmapArr(bit0, bit1) + img, _ := robotgo.CaptureImg() + img1, _ := robotgo.CaptureImg(10, 10, 30, 30) + + fmt.Print("gcv find image: ") + fmt.Println(gcv.FindImg(img1, img)) + fmt.Println() + + res := gcv.FindAllImg(img1, img) + fmt.Println(res[0].TopLeft.Y, res[0].Rects.TopLeft.X, res) + x, y := res[0].TopLeft.X, res[0].TopLeft.Y + robotgo.Move(x, y-rand.Intn(5)) + robotgo.MilliSleep(100) + robotgo.Click() + + res = gcv.FindAll(img1, img) // use find template and sift + fmt.Println("find all: ", res) + res1 := gcv.Find(img1, img) + fmt.Println("find: ", res1) + + img2, _, _ := robotgo.DecodeImg("test_001.png") + x, y = gcv.FindX(img2, img) + fmt.Println(x, y) +} +``` + +#### [Event](https://github.com/robotn/gohook/blob/master/examples/main.go) + +```Go +package main + +import ( + "fmt" + + // "github.com/go-vgo/robotgo" hook "github.com/robotn/gohook" ) func main() { + add() + low() + event() +} + +func add() { fmt.Println("--- Please press ctrl + shift + q to stop hook ---") - robotgo.EventHook(hook.KeyDown, []string{"q", "ctrl", "shift"}, func(e hook.Event) { + hook.Register(hook.KeyDown, []string{"q", "ctrl", "shift"}, func(e hook.Event) { fmt.Println("ctrl-shift-q") - robotgo.EventEnd() + hook.End() }) fmt.Println("--- Please press w---") - robotgo.EventHook(hook.KeyDown, []string{"w"}, func(e hook.Event) { + hook.Register(hook.KeyDown, []string{"w"}, func(e hook.Event) { fmt.Println("w") }) - s := robotgo.EventStart() - <-robotgo.EventProcess(s) + s := hook.Start() + <-hook.Process(s) +} + +func low() { + evChan := hook.Start() + defer hook.End() - ok := robotgo.AddEvents("q", "ctrl", "shift") + for ev := range evChan { + fmt.Println("hook: ", ev) + } +} + +func event() { + ok := hook.AddEvents("q", "ctrl", "shift") if ok { fmt.Println("add events...") } - keve := robotgo.AddEvent("k") + keve := hook.AddEvent("k") if keve { fmt.Println("you press... ", "k") } - mleft := robotgo.AddEvent("mleft") + mleft := hook.AddEvent("mleft") if mleft { fmt.Println("you press... ", "mouse left button") } @@ -267,9 +474,9 @@ func main() { package main import ( - "fmt" + "fmt" - "github.com/go-vgo/robotgo" + "github.com/go-vgo/robotgo" ) func main() { @@ -278,7 +485,13 @@ func main() { fmt.Println("pids... ", fpid) if len(fpid) > 0 { - robotgo.ActivePID(fpid[0]) + robotgo.TypeStr("Hi galaxy!", fpid[0]) + robotgo.KeyTap("a", fpid[0], "cmd") + + robotgo.KeyToggle("a", fpid[0]) + robotgo.KeyToggle("a", fpid[0], "up") + + robotgo.ActivePid(fpid[0]) robotgo.Kill(fpid[0]) } @@ -293,8 +506,8 @@ func main() { robotgo.Kill(100) } - abool := robotgo.ShowAlert("test", "robotgo") - if abool == 0 { + abool := robotgo.Alert("test", "robotgo") + if abool { fmt.Println("ok@@@ ", "ok") } @@ -303,44 +516,19 @@ func main() { } ``` -## CrossCompiling - -##### Windows64 to win32 -```Go -SET CGO_ENABLED=1 -SET GOARCH=386 -go build main.go -``` - -#### Other to windows -```Go -GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ go build -x ./ -``` -``` -// CC=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\gcc.exe -// CXX=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\g++.exe -``` - -Some discussions and questions, please see [issues/228](https://github.com/go-vgo/robotgo/issues/228), [issues/143](https://github.com/go-vgo/robotgo/issues/143). - ## Authors -* [The author is vz](https://github.com/vcaesar) -* [Maintainers](https://github.com/orgs/go-vgo/people) -* [Contributors](https://github.com/go-vgo/robotgo/graphs/contributors) -## Plans -- Update Find an image on screen, read pixels from an image -- Update Window Handle -- Try support Android, maybe support IOS - -## Donate - -Supporting robotgo, [buy me a coffee](https://github.com/go-vgo/buy-me-a-coffee). +- [The author is vz](https://github.com/vcaesar) +- [Maintainers](https://github.com/orgs/go-vgo/people) +- [Contributors](https://github.com/go-vgo/robotgo/graphs/contributors) -#### Paypal - -Donate money by [paypal](https://www.paypal.me/veni0/25) to my account [vzvway@gmail.com](vzvway@gmail.com) +## Plans +- Refactor some C code to Go (such as x11, windows) +- Better multiscreen support +- Wayland support +- Update Window Handle +- Try to support Android and IOS ## Contributors @@ -349,6 +537,6 @@ Donate money by [paypal](https://www.paypal.me/veni0/25) to my account [vzvway@g ## License -Robotgo is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0), with portions covered by various BSD-like licenses. +Robotgo is primarily distributed under the terms of "the Apache License (Version 2.0)", with portions covered by various BSD-like licenses. -See [LICENSE-APACHE](http://www.apache.org/licenses/LICENSE-2.0), [LICENSE-MIT](https://github.com/go-vgo/robotgo/blob/master/LICENSE). +See [LICENSE-APACHE](http://www.apache.org/licenses/LICENSE-2.0), [LICENSE](https://github.com/go-vgo/robotgo/blob/master/LICENSE). diff --git a/appveyor.yml b/appveyor.yml index 22040456..d82094a2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -34,7 +34,7 @@ environment: PATH: C:\msys64\mingw32\bin\;C:\Program Files (x86)\NSIS\;%PATH% # - COMPILER: MINGW_W64 # ARCHITECTURE: x64 - GOVERSION: 1.14.4 + GOVERSION: 1.23.0 # GOPATH: c:\gopath # scripts that run after cloning repository diff --git a/base/MMBitmap.h b/base/MMBitmap.h index 31b66cf3..85b4a2e2 100644 --- a/base/MMBitmap.h +++ b/base/MMBitmap.h @@ -5,89 +5,32 @@ #include "types.h" #include "rgb.h" #include -// #include -#if defined(_MSC_VER) - #include "ms_stdint.h" -#else - #include -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif +#include struct _MMBitmap { - uint8_t *imageBuffer; /* Pixels stored in Quad I format; i.e., origin is in - * top left. Length should be height * bytewidth. */ - size_t width; /* Never 0, unless image is NULL. */ - size_t height; /* Never 0, unless image is NULL. */ - size_t bytewidth; /* The aligned width (width + padding). */ + uint8_t *imageBuffer; /* Pixels stored in Quad I format; */ + int32_t width; /* Never 0, unless image is NULL. */ + int32_t height; /* Never 0, unless image is NULL. */ + + int32_t bytewidth; /* The aligned width (width + padding). */ uint8_t bitsPerPixel; /* Should be either 24 or 32. */ uint8_t bytesPerPixel; /* For convenience; should be bitsPerPixel / 8. */ }; typedef struct _MMBitmap MMBitmap; typedef MMBitmap *MMBitmapRef; -// MMBitmapRef bitmap; - -/* Creates new MMBitmap with the given values. - * Follows the Create Rule (caller is responsible for destroy()'ing object). */ -MMBitmapRef createMMBitmap(uint8_t *buffer, size_t width, size_t height, - size_t bytewidth, uint8_t bitsPerPixel, - uint8_t bytesPerPixel); - -/* Releases memory occupied by MMBitmap. */ -void destroyMMBitmap(MMBitmapRef bitmap); - -/* Releases memory occupied by MMBitmap. Acts via CallBack method*/ -void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint); - -/* Returns copy of MMBitmap, to be destroy()'d by caller. */ -MMBitmapRef copyMMBitmap(MMBitmapRef bitmap); -/* Returns copy of one MMBitmap juxtaposed in another (to be destroy()'d - * by the caller.), or NULL on error. */ -MMBitmapRef copyMMBitmapFromPortion(MMBitmapRef source, MMRect rect); +#define MMBitmapPointInBounds(image, p) ((p).x < (image)->width && (p).y < (image)->height) -#define MMBitmapPointInBounds(image, p) ((p).x < (image)->width && \ - (p).y < (image)->height) -#define MMBitmapRectInBounds(image, r) \ - (((r).origin.x + (r).size.width <= (image)->width) && \ - ((r).origin.y + (r).size.height <= (image)->height)) - -#define MMBitmapGetBounds(image) MMRectMake(0, 0, image->width, image->height) - -/* Get pointer to pixel of MMBitmapRef. No bounds checking is performed (check - * yourself before calling this with MMBitmapPointInBounds(). */ +/* Get pointer to pixel of MMBitmapRef. No bounds checking is performed */ #define MMRGBColorRefAtPoint(image, x, y) \ - (MMRGBColor *)(assert(MMBitmapPointInBounds(image, MMPointMake(x, y))), \ - ((image)->imageBuffer) + (((image)->bytewidth * (y)) \ - + ((x) * (image)->bytesPerPixel))) + (MMRGBColor *)(assert(MMBitmapPointInBounds(image, MMPointInt32Make(x, y))), \ + ((image)->imageBuffer) + (((image)->bytewidth * (y)) + ((x) * (image)->bytesPerPixel))) /* Dereference pixel of MMBitmapRef. Again, no bounds checking is performed. */ #define MMRGBColorAtPoint(image, x, y) *MMRGBColorRefAtPoint(image, x, y) /* Hex/integer value of color at point. */ -#define MMRGBHexAtPoint(image, x, y) \ - hexFromMMRGB(MMRGBColorAtPoint(image, x, y)) - -/* Increment either point.x or point.y depending on the position of point.x. - * That is, if x + 1 is >= width, increment y and start x at the beginning. - * Otherwise, increment x. - * - * This is used as a convenience macro to scan rows when calling functions such - * as findColorInRectAt() and findBitmapInBitmapAt(). */ -#define ITER_NEXT_POINT(pixel, width, start_x) \ -do { \ - if (++(pixel).x >= (width)) { \ - (pixel).x = start_x; \ - ++(point).y; \ - } \ -} while (0); - -#ifdef __cplusplus -} -#endif +#define MMRGBHexAtPoint(image, x, y) hexFromMMRGB(MMRGBColorAtPoint(image, x, y)) #endif /* MMBITMAP_H */ \ No newline at end of file diff --git a/base/MMBitmap_c.h b/base/MMBitmap_c.h deleted file mode 100644 index e300f2ae..00000000 --- a/base/MMBitmap_c.h +++ /dev/null @@ -1,96 +0,0 @@ -#include "MMBitmap.h" -#include -#include - - -//MMBitmapRef createMMBitmap() -MMBitmapRef createMMBitmap( - uint8_t *buffer, - size_t width, - size_t height, - size_t bytewidth, - uint8_t bitsPerPixel, - uint8_t bytesPerPixel -){ - MMBitmapRef bitmap = malloc(sizeof(MMBitmap)); - if (bitmap == NULL) return NULL; - - bitmap->imageBuffer = buffer; - bitmap->width = width; - bitmap->height = height; - bitmap->bytewidth = bytewidth; - bitmap->bitsPerPixel = bitsPerPixel; - bitmap->bytesPerPixel = bytesPerPixel; - - return bitmap; -} - -void destroyMMBitmap(MMBitmapRef bitmap) -{ - assert(bitmap != NULL); - - if (bitmap->imageBuffer != NULL) { - free(bitmap->imageBuffer); - bitmap->imageBuffer = NULL; - } - - free(bitmap); -} - -void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint) -{ - if (bitmapBuffer != NULL) - { - free(bitmapBuffer); - } -} - -MMBitmapRef copyMMBitmap(MMBitmapRef bitmap) -{ - uint8_t *copiedBuf = NULL; - - assert(bitmap != NULL); - if (bitmap->imageBuffer != NULL) { - const size_t bufsize = bitmap->height * bitmap->bytewidth; - copiedBuf = malloc(bufsize); - if (copiedBuf == NULL) return NULL; - - memcpy(copiedBuf, bitmap->imageBuffer, bufsize); - } - - return createMMBitmap(copiedBuf, - bitmap->width, - bitmap->height, - bitmap->bytewidth, - bitmap->bitsPerPixel, - bitmap->bytesPerPixel); -} - -MMBitmapRef copyMMBitmapFromPortion(MMBitmapRef source, MMRect rect) -{ - assert(source != NULL); - - if (source->imageBuffer == NULL || !MMBitmapRectInBounds(source, rect)) { - return NULL; - } else { - uint8_t *copiedBuf = NULL; - const size_t bufsize = rect.size.height * source->bytewidth; - const size_t offset = (source->bytewidth * rect.origin.y) + - (rect.origin.x * source->bytesPerPixel); - - /* Don't go over the bounds, programmer! */ - assert((bufsize + offset) <= (source->bytewidth * source->height)); - - copiedBuf = malloc(bufsize); - if (copiedBuf == NULL) return NULL; - - memcpy(copiedBuf, source->imageBuffer + offset, bufsize); - - return createMMBitmap(copiedBuf, - rect.size.width, - rect.size.height, - source->bytewidth, - source->bitsPerPixel, - source->bytesPerPixel); - } -} diff --git a/base/MMPointArray.h b/base/MMPointArray.h deleted file mode 100644 index 447fc721..00000000 --- a/base/MMPointArray.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -#ifndef MMARRAY_H -#define MMARRAY_H - -#include "types.h" - -struct _MMPointArray { - MMPoint *array; /* Pointer to actual data. */ - size_t count; /* Number of elements in array. */ - size_t _allocedCount; /* Private; do not use outside of MMPointArray.c. */ -}; - -typedef struct _MMPointArray MMPointArray; -typedef MMPointArray *MMPointArrayRef; - -/* Creates array of an initial size (the maximum size is still limitless). - * This follows the "Create" Rule; i.e., responsibility for "destroying" the - * array is given to the caller. */ -MMPointArrayRef createMMPointArray(size_t initialCount); - -/* Frees memory occupied by |pointArray|. Does not accept NULL. */ -void destroyMMPointArray(MMPointArrayRef pointArray); - -/* Appends a point to an array, increasing the internal size if necessary. */ -void MMPointArrayAppendPoint(MMPointArrayRef pointArray, MMPoint point); - -/* Retrieve point from array. */ -#define MMPointArrayGetItem(a, i) ((a)->array)[i] - -/* Set point in array. */ -#define MMPointArraySetItem(a, i, item) ((a)->array[i] = item) - -#endif /* MMARRAY_H */ diff --git a/base/MMPointArray_c.h b/base/MMPointArray_c.h deleted file mode 100644 index f77f3fc0..00000000 --- a/base/MMPointArray_c.h +++ /dev/null @@ -1,41 +0,0 @@ -#include "MMPointArray.h" -#include - -MMPointArrayRef createMMPointArray(size_t initialCount) -{ - MMPointArrayRef pointArray = calloc(1, sizeof(MMPointArray)); - - if (initialCount == 0) initialCount = 1; - - pointArray->_allocedCount = initialCount; - pointArray->array = malloc(pointArray->_allocedCount * sizeof(MMPoint)); - if (pointArray->array == NULL) return NULL; - - return pointArray; -} - -void destroyMMPointArray(MMPointArrayRef pointArray) -{ - if (pointArray->array != NULL) { - free(pointArray->array); - pointArray->array = NULL; - } - - free(pointArray); -} - -void MMPointArrayAppendPoint(MMPointArrayRef pointArray, MMPoint point) -{ - const size_t newCount = ++(pointArray->count); - if (pointArray->_allocedCount < newCount) { - do { - /* Double size each time to avoid calls to realloc(). */ - pointArray->_allocedCount <<= 1; - } while (pointArray->_allocedCount < newCount); - pointArray->array = realloc(pointArray->array, - sizeof(point) * - pointArray->_allocedCount); - } - - pointArray->array[pointArray->count - 1] = point; -} diff --git a/base/UTHashTable.h b/base/UTHashTable.h deleted file mode 100644 index 54cfbe8d..00000000 --- a/base/UTHashTable.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once -#ifndef UTHASHTABLE_H -#define UTHASHTABLE_H - -#include -#include "uthash.h" - -/* All node structs must begin with this (note that there is NO semicolon). */ -#define UTHashNode_HEAD UT_hash_handle hh; - -/* This file contains convenience macros and a standard struct for working with - * uthash hash tables. - * - * The main purpose of this is for convenience of creating/freeing nodes. */ -struct _UTHashTable { - void *uttable; /* The uthash table -- must start out as NULL. */ - void *nodes; /* Contiguous array of nodes. */ - size_t allocedNodeCount; /* Node count currently allocated for. */ - size_t nodeCount; /* Current node count. */ - size_t nodeSize; /* Size of each node. */ -}; - -typedef struct _UTHashTable UTHashTable; - -/* Initiates a hash table to the default values. |table| should point to an - * already allocated UTHashTable struct. - * - * If the |initialCount| argument in initHashTable is given, |nodes| is - * allocated immediately to the maximum size and new nodes are simply slices of - * that array. This can save calls to malloc if many nodes are to be added, and - * the a reasonable maximum number is known ahead of time. - * - * If the node count goes over this maximum, or if |initialCount| is 0, the - * array is dynamically reallocated to fit the size. - */ -void initHashTable(UTHashTable *table, size_t initialCount, size_t nodeSize); - -/* Frees memory occupied by a UTHashTable's members. - * - * Note that this does NOT free memory for the UTHashTable pointed to by - * |table| itself; if that was allocated on the heap, you must free() it - * yourself after calling this. */ -void destroyHashTable(UTHashTable *table); - -/* Returns memory allocated for a new node. Responsibility for freeing this is - * up to the destroyHashTable() macro; this should NOT be freed by the caller. - * - * This is intended to be used with a HASH_ADD() macro, e.g.: - * {% - * struct myNode *uttable = utHashTable->uttable; - * struct myNode *node = getNewNode(utHashTable); - * node->key = 42; - * node->value = someValue; - * HASH_ADD_INT(uttable, key, node); - * utHashTable->uttable = uttable; - * %} - * - * Or, use the UTHASHTABLE_ADD_INT or UTHASHTABLE_ADD_STR macros - * for convenience (they are exactly equivalent): - * {% - * struct myNode *node = getNewNode(utHashTable); - * node->key = 42; - * node->value = someValue; - * UTHASHTABLE_ADD_INT(utHashTable, key, node, struct myNode); - * %} - */ -void *getNewNode(UTHashTable *table); - -#define UTHASHTABLE_ADD_INT(tablePtr, keyName, node, nodeType) \ -do { \ - nodeType *uttable = (tablePtr)->uttable; \ - HASH_ADD_INT(uttable, keyName, node); \ - (tablePtr)->uttable = uttable; \ -} while (0) - -#define UTHASHTABLE_ADD_STR(tablePtr, keyName, node, nodeType) \ -do { \ - nodeType *uttable = (tablePtr)->uttable; \ - HASH_ADD_STR(uttable, keyName, node); \ - (tablePtr)->uttable = uttable; \ -} while (0) - -#endif /* MMHASHTABLE_H */ diff --git a/base/UTHashTable_c.h b/base/UTHashTable_c.h deleted file mode 100644 index c0c482a8..00000000 --- a/base/UTHashTable_c.h +++ /dev/null @@ -1,56 +0,0 @@ -#include "UTHashTable.h" -#include -#include - -/* Base struct class (all nodes must contain at least the elements in - * this struct). */ -struct _UTHashNode { - UTHashNode_HEAD -}; - -typedef struct _UTHashNode UTHashNode; - -void initHashTable(UTHashTable *table, size_t initialCount, size_t nodeSize) -{ - assert(table != NULL); - assert(nodeSize >= sizeof(UTHashNode)); - - table->uttable = NULL; /* Must be set to NULL for uthash. */ - table->allocedNodeCount = (initialCount == 0) ? 1 : initialCount; - table->nodeCount = 0; - table->nodeSize = nodeSize; - table->nodes = calloc(table->nodeSize, nodeSize * table->allocedNodeCount); -} - -void destroyHashTable(UTHashTable *table) -{ - UTHashNode *uttable = table->uttable; - UTHashNode *node; - - /* Let uthash do its magic. */ - while (uttable != NULL) { - node = uttable; /* Grab pointer to first item. */ - HASH_DEL(uttable, node); /* Delete it (table advances to next). */ - } - - /* Only giant malloc'd block containing each node must be freed. */ - if (table->nodes != NULL) free(table->nodes); - table->uttable = table->nodes = NULL; -} - -void *getNewNode(UTHashTable *table) -{ - /* Increment node count, resizing table if necessary. */ - const size_t newNodeCount = ++(table->nodeCount); - if (table->allocedNodeCount < newNodeCount) { - do { - /* Double size each time to avoid calls to realloc(). */ - table->allocedNodeCount <<= 1; - } while (table->allocedNodeCount < newNodeCount); - - table->nodes = realloc(table->nodes, table->nodeSize * - table->allocedNodeCount); - } - - return (char *)table->nodes + (table->nodeSize * (table->nodeCount - 1)); -} diff --git a/base/base.go b/base/base.go new file mode 100644 index 00000000..8ffa8e92 --- /dev/null +++ b/base/base.go @@ -0,0 +1,2 @@ +// https://github.com/golang/go/issues/26366 +package base diff --git a/base/base64.c b/base/base64.c deleted file mode 100644 index 2befad9d..00000000 --- a/base/base64.c +++ /dev/null @@ -1,109 +0,0 @@ -#include "base64.h" -#include -#include -#include -#include - -/* Encoding table as described in RFC1113. */ -const static uint8_t b64_encode_table[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz0123456789+/"; - -/* Decoding table. */ -const static int8_t b64_decode_table[256] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00-0F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10-1F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 20-2F */ - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 30-3F */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 40-4F */ - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 50-5F */ - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 60-6F */ - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 70-7F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80-8F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90-9F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0-AF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0-BF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0-CF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0-DF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0-EF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 /* F0-FF */ -}; - -uint8_t *base64decode(const uint8_t *src, const size_t buflen, size_t *retlen){ - int8_t digit, lastdigit; - size_t i, j; - uint8_t *decoded; - const size_t maxlen = ((buflen + 3) / 4) * 3; - - /* Sanity check */ - assert(src != NULL); - - digit = lastdigit = j = 0; - decoded = malloc(maxlen + 1); - if (decoded == NULL) return NULL; - for (i = 0; i < buflen; ++i) { - if ((digit = b64_decode_table[src[i]]) != -1) { - /* Decode block */ - switch (i % 4) { - case 1: - decoded[j++] = ((lastdigit << 2) | ((digit & 0x30) >> 4)); - break; - case 2: - decoded[j++] = (((lastdigit & 0xF) << 4) | ((digit & 0x3C) >> 2)); - break; - case 3: - decoded[j++] = (((lastdigit & 0x03) << 6) | digit); - break; - } - lastdigit = digit; - } - } - - if (retlen != NULL) *retlen = j; - decoded[j] = '\0'; - return decoded; /* Must be free()'d by caller */ -} - -uint8_t *base64encode(const uint8_t *src, const size_t buflen, size_t *retlen){ - size_t i, j; - const size_t maxlen = (((buflen + 3) & ~3)) * 4; - uint8_t *encoded = malloc(maxlen + 1); - if (encoded == NULL) return NULL; - - /* Sanity check */ - assert(src != NULL); - assert(buflen > 0); - - j = 0; - for (i = 0; i < buflen + 1; ++i) { - /* Encode block */ - switch (i % 3) { - case 0: - encoded[j++] = b64_encode_table[src[i] >> 2]; - encoded[j++] = b64_encode_table[((src[i] & 0x03) << 4) | - ((src[i + 1] & 0xF0) >> 4)]; - break; - case 1: - encoded[j++] = b64_encode_table[((src[i] & 0x0F) << 2) | - ((src[i + 1] & 0xC0) >> 6)]; - break; - case 2: - encoded[j++] = b64_encode_table[(src[i] & 0x3F)]; - break; - } - } - - /* Add padding if necessary */ - if ((j % 4) != 0) { - const size_t with_padding = ((j + 3) & ~3); /* Align to 4 bytes */ - do { - encoded[j++] = '='; - } while (j < with_padding); - } - - assert(j <= maxlen); - - if (retlen != NULL) *retlen = j; - encoded[j] = '\0'; - return encoded; /* Must be free()'d by caller */ -} diff --git a/base/base64.h b/base/base64.h deleted file mode 100644 index d12700c5..00000000 --- a/base/base64.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#ifndef BASE64_H -#define BASE64_H - -#include - -#if defined(_MSC_VER) - #include "ms_stdint.h" -#else - #include -#endif - -/* Decode a base64 encoded string discarding line breaks and noise. - * - * Returns a new string to be free()'d by caller, or NULL on error. - * Returned string is guaranteed to be NUL-terminated. - * - * If |retlen| is not NULL, it is set to the length of the returned string - * (minus the NUL-terminator) on successful return. */ -uint8_t *base64decode(const uint8_t *buf, const size_t buflen, size_t *retlen); - -/* Encode a base64 encoded string without line breaks or noise. - * - * Returns a new string to be free()'d by caller, or NULL on error. - * Returned string is guaranteed to be NUL-terminated with the correct padding. - * - * If |retlen| is not NULL, it is set to the length of the returned string - * (minus the NUL-terminator) on successful return. */ -uint8_t *base64encode(const uint8_t *buf, const size_t buflen, size_t *retlen); - -#endif /* BASE64_H */ diff --git a/base/base64_c.h b/base/base64_c.h deleted file mode 100644 index 5b384c44..00000000 --- a/base/base64_c.h +++ /dev/null @@ -1,111 +0,0 @@ -#include "base64.h" -#include -#include -#include -#include - -/* Encoding table as described in RFC1113. */ -const static uint8_t b64_encode_table[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz0123456789+/"; - -/* Decoding table. */ -const static int8_t b64_decode_table[256] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00-0F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10-1F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 20-2F */ - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 30-3F */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 40-4F */ - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 50-5F */ - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 60-6F */ - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 70-7F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80-8F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90-9F */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0-AF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0-BF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0-CF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0-DF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0-EF */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 /* F0-FF */ -}; - -uint8_t *base64decode(const uint8_t *src, const size_t buflen, size_t *retlen) -{ - int8_t digit, lastdigit; - size_t i, j; - uint8_t *decoded; - const size_t maxlen = ((buflen + 3) / 4) * 3; - - /* Sanity check */ - assert(src != NULL); - - digit = lastdigit = j = 0; - decoded = malloc(maxlen + 1); - if (decoded == NULL) return NULL; - for (i = 0; i < buflen; ++i) { - if ((digit = b64_decode_table[src[i]]) != -1) { - /* Decode block */ - switch (i % 4) { - case 1: - decoded[j++] = ((lastdigit << 2) | ((digit & 0x30) >> 4)); - break; - case 2: - decoded[j++] = (((lastdigit & 0xF) << 4) | ((digit & 0x3C) >> 2)); - break; - case 3: - decoded[j++] = (((lastdigit & 0x03) << 6) | digit); - break; - } - lastdigit = digit; - } - } - - if (retlen != NULL) *retlen = j; - decoded[j] = '\0'; - return decoded; /* Must be free()'d by caller */ -} - -uint8_t *base64encode(const uint8_t *src, const size_t buflen, size_t *retlen) -{ - size_t i, j; - const size_t maxlen = (((buflen + 3) & ~3)) * 4; - uint8_t *encoded = malloc(maxlen + 1); - if (encoded == NULL) return NULL; - - /* Sanity check */ - assert(src != NULL); - assert(buflen > 0); - - j = 0; - for (i = 0; i < buflen + 1; ++i) { - /* Encode block */ - switch (i % 3) { - case 0: - encoded[j++] = b64_encode_table[src[i] >> 2]; - encoded[j++] = b64_encode_table[((src[i] & 0x03) << 4) | - ((src[i + 1] & 0xF0) >> 4)]; - break; - case 1: - encoded[j++] = b64_encode_table[((src[i] & 0x0F) << 2) | - ((src[i + 1] & 0xC0) >> 6)]; - break; - case 2: - encoded[j++] = b64_encode_table[(src[i] & 0x3F)]; - break; - } - } - - /* Add padding if necessary */ - if ((j % 4) != 0) { - const size_t with_padding = ((j + 3) & ~3); /* Align to 4 bytes */ - do { - encoded[j++] = '='; - } while (j < with_padding); - } - - assert(j <= maxlen); - - if (retlen != NULL) *retlen = j; - encoded[j] = '\0'; - return encoded; /* Must be free()'d by caller */ -} diff --git a/base/bitmap_free_c.h b/base/bitmap_free_c.h new file mode 100644 index 00000000..90e20a30 --- /dev/null +++ b/base/bitmap_free_c.h @@ -0,0 +1,36 @@ +#include "MMBitmap.h" +#include +#include + +MMBitmapRef createMMBitmap_c(uint8_t *buffer, int32_t width, int32_t height, + int32_t bytewidth, uint8_t bitsPerPixel, uint8_t bytesPerPixel +) { + MMBitmapRef bitmap = malloc(sizeof(MMBitmap)); + if (bitmap == NULL) { return NULL; } + + bitmap->imageBuffer = buffer; + bitmap->width = width; + bitmap->height = height; + bitmap->bytewidth = bytewidth; + bitmap->bitsPerPixel = bitsPerPixel; + bitmap->bytesPerPixel = bytesPerPixel; + + return bitmap; +} + +void destroyMMBitmap(MMBitmapRef bitmap) { + assert(bitmap != NULL); + + if (bitmap->imageBuffer != NULL) { + free(bitmap->imageBuffer); + bitmap->imageBuffer = NULL; + } + + free(bitmap); +} + +void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint) { + if (bitmapBuffer != NULL) { + free(bitmapBuffer); + } +} diff --git a/base/bmp_io.h b/base/bmp_io.h deleted file mode 100644 index fb510dbd..00000000 --- a/base/bmp_io.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once -#ifndef BMP_IO_H -#define BMP_IO_H - -#include "MMBitmap.h" -#include "file_io.h" - -enum _BMPReadError { - kBMPGenericError = 0, - kBMPAccessError, - kBMPInvalidKeyError, - kBMPUnsupportedHeaderError, - kBMPInvalidColorPanesError, - kBMPUnsupportedColorDepthError, - kBMPUnsupportedCompressionError, - kBMPInvalidPixelDataError -}; - -typedef MMIOError MMBMPReadError; - -/* Returns description of given MMBMPReadError. - * Returned string is constant and hence should not be freed. */ -const char *MMBMPReadErrorString(MMIOError error); - -/* Attempts to read bitmap file at path; returns new MMBitmap on success, or - * NULL on error. If |error| is non-NULL, it will be set to the error code - * on return. - * - * Currently supports: - * - Uncompressed Windows v3/v4/v5 24-bit or 32-bit BMP. - * - OS/2 v1 or v2 24-bit BMP. - * - Does NOT yet support: 1-bit, 4-bit, 8-bit, 16-bit, compressed bitmaps, - * or PNGs/JPEGs disguised as BMPs (and returns NULL if those are given). - * - * Responsibility for destroy()'ing returned MMBitmap is left up to caller. */ -MMBitmapRef newMMBitmapFromBMP(const char *path, MMBMPReadError *error); - -/* Returns a buffer containing the raw BMP file data in Windows v3 BMP format, - * ready to be saved to a file. If |len| is not NULL, it will be set to the - * number of bytes allocated in the returned buffer. - * - * Responsibility for free()'ing data is left up to the caller. */ -uint8_t *createBitmapData(MMBitmapRef bitmap, size_t *len); - -/* Saves bitmap to file in Windows v3 BMP format. - * Returns 0 on success, -1 on error. */ -int saveMMBitmapAsBMP(MMBitmapRef bitmap, const char *path); - -/* Swaps bitmap from Quadrant 1 to Quadran III format, or vice versa - * (upside-down Cartesian/PostScript/GL <-> right side up QD/CG raster format). - */ -void flipBitmapData(void *data, size_t width, size_t height, size_t bytewidth); - -#endif /* BMP_IO_H */ diff --git a/base/bmp_io_c.h b/base/bmp_io_c.h deleted file mode 100644 index 6812ae8f..00000000 --- a/base/bmp_io_c.h +++ /dev/null @@ -1,441 +0,0 @@ -#include "bmp_io.h" -#include "os.h" -#include "endian.h" -#include /* fopen() */ -#include /* memcpy() */ - -#if defined(_MSC_VER) - #include "ms_stdbool.h" - #include "ms_stdint.h" -#else - #include - #include -#endif - -#pragma pack(push, 1) /* The following structs should be continguous, so we can - * copy them in one read. */ -/* - * Standard, initial BMP Header - */ -struct BITMAP_FILE_HEADER { - uint16_t magic; /* First two byes of the file; should be 0x4D42. */ - uint32_t fileSize; /* Size of the BMP file in bytes (unreliable). */ - uint32_t reserved; /* Application-specific. */ - uint32_t imageOffset; /* Offset to bitmap data. */ -}; - -#define BMP_MAGIC 0x4D42 /* The starting key that marks the file as a BMP. */ - -enum _BMP_COMPRESSION { - kBMP_RGB = 0, /* No compression. */ - kBMP_RLE8 = 1, /* Can only be used with 8-bit bitmaps. */ - kBMP_RLE4 = 2, /* Can only be used with 4-bit bitmaps. */ - kBMP_BITFIELDS = 3, /* Can only be used with 16/32-bit bitmaps. */ - kBMP_JPEG = 4, /* Bitmap contains a JPEG image. */ - kBMP_PNG = 5 /* Bitmap contains a PNG image. */ -}; - -typedef uint32_t BMP_COMPRESSION; - -/* - * Windows 3 Header - */ -struct BITMAP_INFO_HEADER { - uint32_t headerSize; /* The size of this header (40 bytes). */ - int32_t width; /* The bitmap width in pixels. */ - int32_t height; /* The bitmap height in pixels. */ - /* (A negative value denotes that the image - * is flipped.) */ - uint16_t colorPlanes; /* The number of color planes; must be 1. */ - uint16_t bitsPerPixel; /* The color depth of the image (1, 4, 8, 16, - * 24, or 32). */ - BMP_COMPRESSION compression; /* The compression method being used. */ - uint32_t imageSize; /* Size of the bitmap in bytes (unreliable).*/ - int32_t xRes; /* The horizontal resolution (unreliable). */ - int32_t yRes; /* The vertical resolution (unreliable). */ - uint32_t colorsUsed; /* The number of colors in the color table, - * or 0 to default to 2^n. */ - uint32_t colorsImportant; /* Colors important for displaying bitmap, - * or 0 when every color is equally important; - * ignored. */ -}; - -/* - * OS/2 v1 Header - */ -struct BITMAP_CORE_HEADER { - uint32_t headerSize; /* The size of this header (12 bytes). */ - uint16_t width; /* The bitmap width in pixels. */ - uint16_t height; /* The bitmap height in pixels. */ - uint16_t colorPlanes; /* The number of color planes; must be 1. */ - uint16_t bitsPerPixel; /* Color depth of the image (1, 4, 8, or 24). */ -}; - -#pragma pack(pop) /* Let the compiler do what it wants now. */ - -/* BMP files are always saved in little endian format (x86), so we need to - * convert them if we're not on a little endian machine (e.g., ARM & ppc). */ - -#if __BYTE_ORDER == __BIG_ENDIAN - -/* Converts bitmap file header from to and from little endian, if and only if - * host is big endian. */ -static void convertBitmapFileHeader(struct BITMAP_FILE_HEADER *header) -{ - header->magic = swapLittleAndHost16(header->magic); - swapLittleAndHost32(header->fileSize); - swapLittleAndHost32(header->reserved); - swapLittleAndHost32(header->imageOffset); -} - -/* Converts bitmap info header from to and from little endian, if and only if - * host is big endian. */ -static void convertBitmapInfoHeader(struct BITMAP_INFO_HEADER *header) -{ - header->headerSize = swapLittleAndHost32(header->headerSize); - header->width = swapLittleAndHost32(header->width); - header->height = swapLittleAndHost32(header->height); - header->colorPlanes = swapLittleAndHost16(header->colorPlanes); - header->bitsPerPixel = swapLittleAndHost16(header->bitsPerPixel); - header->compression = swapLittleAndHost32(header->compression); - header->imageSize = swapLittleAndHost32(header->imageSize); - header->xRes = swapLittleAndHost32(header->xRes); - header->yRes = swapLittleAndHost32(header->yRes); - header->colorsUsed = swapLittleAndHost32(header->colorsUsed); - header->colorsImportant = swapLittleAndHost32(header->colorsImportant); -} - -#elif __BYTE_ORDER == __LITTLE_ENDIAN - /* No conversion necessary if we are already little endian. */ - #define convertBitmapFileHeader(header) - #define convertBitmapInfoHeader(header) -#endif - -/* Returns newly alloc'd image data from bitmap file. The current position of - * the file must be at the start of the image before calling this. */ -static uint8_t *readImageData(FILE *fp, size_t width, size_t height, - uint8_t bytesPerPixel, size_t bytewidth); - -/* Copys image buffer from |bitmap| to |dest| in BGR format. */ -static void copyBGRDataFromMMBitmap(MMBitmapRef bitmap, uint8_t *dest); - -const char *MMBMPReadErrorString(MMIOError error) -{ - switch (error) { - case kBMPAccessError: - return "Could not open file"; - case kBMPInvalidKeyError: - return "Not a BMP file"; - case kBMPUnsupportedHeaderError: - return "Unsupported BMP header"; - case kBMPInvalidColorPanesError: - return "Invalid number of color panes in BMP file"; - case kBMPUnsupportedColorDepthError: - return "Unsupported color depth in BMP file"; - case kBMPUnsupportedCompressionError: - return "Unsupported file compression in BMP file"; - case kBMPInvalidPixelDataError: - return "Could not read BMP pixel data"; - default: - return NULL; - } -} - -MMBitmapRef newMMBitmapFromBMP(const char *path, MMBMPReadError *err) -{ - FILE *fp; - struct BITMAP_FILE_HEADER fileHeader = {0}; /* Initialize elements to 0. */ - struct BITMAP_INFO_HEADER dibHeader = {0}; - uint32_t headerSize = 0; - uint8_t bytesPerPixel; - size_t bytewidth; - uint8_t *imageBuf; - - if ((fp = fopen(path, "rb")) == NULL) { - if (err != NULL) *err = kBMPAccessError; - return NULL; - } - - /* Initialize error code to generic value. */ - if (err != NULL) *err = kBMPGenericError; - - if (fread(&fileHeader, sizeof(fileHeader), 1, fp) == 0) goto bail; - - /* Convert from little-endian if it's not already. */ - convertBitmapFileHeader(&fileHeader); - - /* First two bytes should always be 0x4D42. */ - if (fileHeader.magic != BMP_MAGIC) { - if (err != NULL) *err = kBMPInvalidKeyError; - goto bail; - } - - /* Get header size. */ - if (fread(&headerSize, sizeof(headerSize), 1, fp) == 0) goto bail; - headerSize = swapLittleAndHost32(headerSize); - - /* Back up before reading header. */ - if (fseek(fp, -(long)sizeof(headerSize), SEEK_CUR) < 0) goto bail; - - if (headerSize == 12) { /* OS/2 v1 header */ - struct BITMAP_CORE_HEADER coreHeader = {0}; - if (fread(&coreHeader, sizeof(coreHeader), 1, fp) == 0) goto bail; - - dibHeader.width = coreHeader.width; - dibHeader.height = coreHeader.height; - dibHeader.colorPlanes = coreHeader.colorPlanes; - dibHeader.bitsPerPixel = coreHeader.bitsPerPixel; - } else if (headerSize == 40 || headerSize == 108 || headerSize == 124) { - /* Windows v3/v4/v5 header */ - /* Read only the common part (v3) and skip over the rest. */ - if (fread(&dibHeader, sizeof(dibHeader), 1, fp) == 0) goto bail; - } else { - if (err != NULL) *err = kBMPUnsupportedHeaderError; - goto bail; - } - - convertBitmapInfoHeader(&dibHeader); - - if (dibHeader.colorPlanes != 1) { - if (err != NULL) *err = kBMPInvalidColorPanesError; - goto bail; - } - - /* Currently only 24-bit and 32-bit are supported. */ - if (dibHeader.bitsPerPixel != 24 && dibHeader.bitsPerPixel != 32) { - if (err != NULL) *err = kBMPUnsupportedColorDepthError; - goto bail; - } - - if (dibHeader.compression != kBMP_RGB) { - if (err != NULL) *err = kBMPUnsupportedCompressionError; - goto bail; - } - - /* This can happen because we don't fully parse Windows v4/v5 headers. */ - if (ftell(fp) != (long)fileHeader.imageOffset) { - fseek(fp, fileHeader.imageOffset, SEEK_SET); - } - - /* Get bytes per row, including padding. */ - bytesPerPixel = dibHeader.bitsPerPixel / 8; - bytewidth = ADD_PADDING(dibHeader.width * bytesPerPixel); - - imageBuf = readImageData(fp, dibHeader.width, abs(dibHeader.height), - bytesPerPixel, bytewidth); - fclose(fp); - - if (imageBuf == NULL) { - if (err != NULL) *err = kBMPInvalidPixelDataError; - return NULL; - } - - /* A negative height indicates that the image is flipped. - * - * We store our bitmaps as "flipped" according to the BMP format; i.e., (0, 0) - * is the top left, not bottom left. So we only need to flip the bitmap if - * the height is NOT negative. */ - if (dibHeader.height < 0) { - dibHeader.height = -dibHeader.height; - } else { - flipBitmapData(imageBuf, dibHeader.width, dibHeader.height, bytewidth); - } - - return createMMBitmap(imageBuf, dibHeader.width, dibHeader.height, - bytewidth, (uint8_t)dibHeader.bitsPerPixel, - bytesPerPixel); - -bail: - fclose(fp); - return NULL; -} - -uint8_t *createBitmapData(MMBitmapRef bitmap, size_t *len) -{ - /* BMP files are always aligned to 4 bytes. */ - const size_t bytewidth = ((bitmap->width * bitmap->bytesPerPixel) + 3) & ~3; - - const size_t imageSize = bytewidth * bitmap->height; - struct BITMAP_FILE_HEADER *fileHeader; - struct BITMAP_INFO_HEADER *dibHeader; - - /* Should always be 54. */ - const size_t imageOffset = sizeof(*fileHeader) + sizeof(*dibHeader); - uint8_t *data; - const size_t dataLen = imageOffset + imageSize; - - data = calloc(1, dataLen); - if (data == NULL) return NULL; - - /* Save top header. */ - fileHeader = (struct BITMAP_FILE_HEADER *)data; - fileHeader->magic = BMP_MAGIC; - fileHeader->fileSize = (uint32_t)(sizeof(*dibHeader) + imageSize); - fileHeader->imageOffset = (uint32_t)imageOffset; - - /* BMP files are always stored as little-endian, so we need to convert back - * if necessary. */ - convertBitmapFileHeader(fileHeader); - - /* Copy Windows v3 header. */ - dibHeader = (struct BITMAP_INFO_HEADER *)(data + sizeof(*fileHeader)); - dibHeader->headerSize = sizeof(*dibHeader); /* Should always be 40. */ - dibHeader->width = (int32_t)bitmap->width; - dibHeader->height = -(int32_t)bitmap->height; /* Our bitmaps are "flipped". */ - dibHeader->colorPlanes = 1; - dibHeader->bitsPerPixel = bitmap->bitsPerPixel; - dibHeader->compression = kBMP_RGB; /* Don't save with compression. */ - dibHeader->imageSize = (uint32_t)imageSize; - - convertBitmapInfoHeader(dibHeader); - - /* Lastly, copy the pixel data. */ - copyBGRDataFromMMBitmap(bitmap, data + imageOffset); - - if (len != NULL) *len = dataLen; - return data; -} - -int saveMMBitmapAsBMP(MMBitmapRef bitmap, const char *path) -{ - FILE *fp; - size_t dataLen; - uint8_t *data; - - if ((fp = fopen(path, "wb")) == NULL) return -1; - - if ((data = createBitmapData(bitmap, &dataLen)) == NULL) { - fclose(fp); - return -1; - } - - if (fwrite(data, dataLen, 1, fp) == 0) { - free(data); - fclose(fp); - return -1; - } - - free(data); - fclose(fp); - return 0; -} - -uint8_t *saveMMBitmapAsBytes(MMBitmapRef bitmap, size_t *dataLen) -{ - uint8_t *data; - if ((data = createBitmapData(bitmap, dataLen)) == NULL) { - *dataLen = -1; - return NULL; - } - return data; -} - -static uint8_t *readImageData(FILE *fp, size_t width, size_t height, - uint8_t bytesPerPixel, size_t bytewidth) -{ - size_t imageSize = bytewidth * height; - uint8_t *imageBuf = calloc(1, imageSize); - - if (MMRGB_IS_BGR && (bytewidth % 4) == 0) { /* No conversion needed. */ - if (fread(imageBuf, imageSize, 1, fp) == 0) { - free(imageBuf); - return NULL; - } - } else { /* Convert from BGR with 4-byte alignment. */ - uint8_t *row = malloc(bytewidth); - size_t y; - const size_t bmp_bytewidth = (width * bytesPerPixel + 3) & ~3; - - if (row == NULL) return NULL; - assert(bmp_bytewidth <= bytewidth); - - /* Read image data row by row. */ - for (y = 0; y < height; ++y) { - const size_t rowOffset = y * bytewidth; - size_t x; - uint8_t *rowptr = row; - if (fread(row, bmp_bytewidth, 1, fp) == 0) { - free(imageBuf); - free(row); - return NULL; - } - - for (x = 0; x < width; ++x) { - const size_t colOffset = x * bytesPerPixel; - MMRGBColor *color = (MMRGBColor *)(imageBuf + - rowOffset + colOffset); - - /* BMP files are stored in BGR format. */ - color->blue = rowptr[0]; - color->green = rowptr[1]; - color->red = rowptr[2]; - rowptr += bytesPerPixel; - } - } - - free(row); - } - - return imageBuf; -} - -static void copyBGRDataFromMMBitmap(MMBitmapRef bitmap, uint8_t *dest) -{ - if (MMRGB_IS_BGR && (bitmap->bytewidth % 4) == 0) { /* No conversion needed. */ - memcpy(dest, bitmap->imageBuffer, bitmap->bytewidth * bitmap->height); - } else { /* Convert to RGB with other-than-4-byte alignment. */ - const size_t bytewidth = (bitmap->width * bitmap->bytesPerPixel + 3) & ~3; - size_t y; - - /* Copy image data row by row. */ - for (y = 0; y < bitmap->height; ++y) { - uint8_t *rowptr = dest + (y * bytewidth); - size_t x; - for (x = 0; x < bitmap->width; ++x) { - MMRGBColor *color = MMRGBColorRefAtPoint(bitmap, x, y); - - /* BMP files are stored in BGR format. */ - rowptr[0] = color->blue; - rowptr[1] = color->green; - rowptr[2] = color->red; - - rowptr += bitmap->bytesPerPixel; - } - } - } -} - -/* Perform an in-place swap from Quadrant 1 to Quadrant III format (upside-down - * PostScript/GL to right side up QD/CG raster format) We do this in-place, - * which requires more copying, but will touch only half the pages. - * - * This is blatantly copied from Apple's glGrab example code. */ -void flipBitmapData(void *data, size_t width, size_t height, size_t bytewidth) -{ - size_t top, bottom; - void *topP; - void *bottomP; - void *tempbuf; - - if (height <= 1) return; /* No flipping necessary if height is <= 1. */ - - top = 0; - bottom = height - 1; - tempbuf = malloc(bytewidth); - if (tempbuf == NULL) return; - - while (top < bottom) { - topP = (void *)((top * bytewidth) + (intptr_t)data); - bottomP = (void *)((bottom * bytewidth) + (intptr_t)data); - - /* Save and swap scanlines. - * Does a simple in-place exchange with a temp buffer. */ - memcpy(tempbuf, topP, bytewidth); - memcpy(topP, bottomP, bytewidth); - memcpy(bottomP, tempbuf, bytewidth); - - ++top; - --bottom; - } - free(tempbuf); -} diff --git a/base/color_find.h b/base/color_find.h deleted file mode 100644 index 3c732f64..00000000 --- a/base/color_find.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#ifndef COLOR_FIND_H -#define COLOR_FIND_H - -#include "MMBitmap.h" -#include "MMPointArray.h" - -/* Convenience wrapper around findColorInRect(), where |rect| is the bounds of - * the image. */ -#define findColorInImage(image, color, pointPtr, tolerance) \ - findColorInRect(image, color, pointPtr, MMBitmapGetBounds(image), tolerance) - -/* Attempt to find a pixel with the given color in |image| inside |rect|. - * Returns 0 on success, non-zero on failure. If the color was found and - * |point| is not NULL, it will be initialized to the (x, y) coordinates the - * RGB color. - * - * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the - * colors need to match, with 0 being exact and 1 being any. */ -int findColorInRect(MMBitmapRef image, MMRGBHex color, MMPoint *point, - MMRect rect, float tolerance); - -/* Convenience wrapper around findAllRGBInRect(), where |rect| is the bounds of - * the image. */ -#define findAllColorInImage(image, color, tolerance) \ - findAllColorInRect(image, color, MMBitmapGetBounds(image), tolerance) - -/* Returns MMPointArray of all pixels of given color in |image| inside of - * |rect|. Note that an array is returned regardless of whether the color was - * found; check array->count to see if it actually was. - * - * Responsibility for freeing the MMPointArray with destroyMMPointArray() is - * given to the caller. - * - * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the - * colors need to match, with 0 being exact and 1 being any. */ -MMPointArrayRef findAllColorInRect(MMBitmapRef image, MMRGBHex color, - MMRect rect, float tolerance); - -/* Convenience wrapper around countOfColorsInRect, where |rect| is the bounds - * of the image. */ -#define countOfColorsInImage(image, color, tolerance) \ - countOfColorsInRect(image, color, MMBitmapGetBounds(image), tolerance) - -/* Returns the count of the given color in |rect| inside of |image|. */ -size_t countOfColorsInRect(MMBitmapRef image, MMRGBHex color, MMRect rect, - float tolerance); - -#endif /* COLOR_FIND_H */ diff --git a/base/color_find_c.h b/base/color_find_c.h deleted file mode 100644 index 9953d82a..00000000 --- a/base/color_find_c.h +++ /dev/null @@ -1,58 +0,0 @@ -#include "color_find.h" -// #include "../screen/screen_init.h" -#include - -/* Abstracted, general function to avoid repeated code. */ -static int findColorInRectAt(MMBitmapRef image, MMRGBHex color, MMPoint *point, - MMRect rect, float tolerance, MMPoint startPoint) -{ - MMPoint scan = startPoint; - if (!MMBitmapRectInBounds(image, rect)) return -1; - - for (; scan.y < rect.size.height; ++scan.y) { - for (; scan.x < rect.size.width; ++scan.x) { - MMRGBHex found = MMRGBHexAtPoint(image, scan.x, scan.y); - if (MMRGBHexSimilarToColor(color, found, tolerance)) { - if (point != NULL) *point = scan; - return 0; - } - } - scan.x = rect.origin.x; - } - - return -1; -} - -int findColorInRect(MMBitmapRef image, MMRGBHex color, - MMPoint *point, MMRect rect, float tolerance) -{ - return findColorInRectAt(image, color, point, rect, tolerance, rect.origin); -} - -MMPointArrayRef findAllColorInRect(MMBitmapRef image, MMRGBHex color, - MMRect rect, float tolerance) -{ - MMPointArrayRef pointArray = createMMPointArray(0); - MMPoint point = MMPointZero; - - while (findColorInRectAt(image, color, &point, rect, tolerance, point) == 0) { - MMPointArrayAppendPoint(pointArray, point); - ITER_NEXT_POINT(point, rect.size.width, rect.origin.x); - } - - return pointArray; -} - -size_t countOfColorsInRect(MMBitmapRef image, MMRGBHex color, MMRect rect, - float tolerance) -{ - size_t count = 0; - MMPoint point = MMPointZero; - - while (findColorInRectAt(image, color, &point, rect, tolerance, point) == 0) { - ITER_NEXT_POINT(point, rect.size.width, rect.origin.x); - ++count; - } - - return count; -} diff --git a/base/deadbeef_rand.h b/base/deadbeef_rand.h index ec569a24..02e3d4e0 100644 --- a/base/deadbeef_rand.h +++ b/base/deadbeef_rand.h @@ -4,11 +4,7 @@ #include #define DEADBEEF_MAX UINT32_MAX - -/* Dead Beef Random Number Generator - * From: http://inglorion.net/software/deadbeef_rand - * A fast, portable psuedo-random number generator by BJ Amsterdam Zuidoost. - * Stated in license terms: "Feel free to use the code in your own software." */ +/* Dead Beef Random Number Generator From: http://inglorion.net/software/deadbeef_rand */ /* Generates a random number between 0 and DEADBEEF_MAX. */ uint32_t deadbeef_rand(void); @@ -22,14 +18,11 @@ uint32_t deadbeef_generate_seed(void); /* Seeds with the above function. */ #define deadbeef_srand_time() deadbeef_srand(deadbeef_generate_seed()) -/* Returns random double in the range [a, b). - * Taken directly from the rand() man page. */ +/* Returns random double in the range [a, b).*/ #define DEADBEEF_UNIFORM(a, b) \ ((a) + (deadbeef_rand() / (((double)DEADBEEF_MAX / (b - a) + 1)))) -/* Returns random integer in the range [a, b). - * Also taken from the rand() man page. */ -#define DEADBEEF_RANDRANGE(a, b) \ - (uint32_t)DEADBEEF_UNIFORM(a, b) +/* Returns random integer in the range [a, b).*/ +#define DEADBEEF_RANDRANGE(a, b) (uint32_t)DEADBEEF_UNIFORM(a, b) #endif /* DEADBEEF_RAND_H */ diff --git a/base/deadbeef_rand_c.h b/base/deadbeef_rand_c.h index 1de295f8..1a0173fb 100644 --- a/base/deadbeef_rand_c.h +++ b/base/deadbeef_rand_c.h @@ -4,23 +4,19 @@ static uint32_t deadbeef_seed; static uint32_t deadbeef_beef = 0xdeadbeef; -uint32_t deadbeef_rand(void) -{ +uint32_t deadbeef_rand(void) { deadbeef_seed = (deadbeef_seed << 7) ^ ((deadbeef_seed >> 25) + deadbeef_beef); deadbeef_beef = (deadbeef_beef << 7) ^ ((deadbeef_beef >> 25) + 0xdeadbeef); return deadbeef_seed; } -void deadbeef_srand(uint32_t x) -{ +void deadbeef_srand(uint32_t x) { deadbeef_seed = x; deadbeef_beef = 0xdeadbeef; } -/* Taken directly from the documentation: - * http://inglorion.net/software/cstuff/deadbeef_rand/ */ -uint32_t deadbeef_generate_seed(void) -{ +/* Taken directly from the documentation: http://inglorion.net/software/cstuff/deadbeef_rand/ */ +uint32_t deadbeef_generate_seed(void) { uint32_t t = (uint32_t)time(NULL); uint32_t c = (uint32_t)clock(); return (t << 24) ^ (c << 11) ^ t ^ (size_t) &c; diff --git a/base/endian.h b/base/endian.h deleted file mode 100644 index 2bc7c521..00000000 --- a/base/endian.h +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once -#ifndef ENDIAN_H -#define ENDIAN_H - -#include "os.h" - -/* - * (Mostly) cross-platform endian definitions and bit swapping macros. - * Unfortunately, there is no standard C header for this, so we just - * include the most common ones and fallback to our own custom macros. - */ - -#if defined(__linux__) /* Linux */ - #include - #include -#elif (defined(__FreeBSD__) && __FreeBSD_version >= 470000) || \ - defined(__OpenBSD__) || defined(__NetBSD__) /* (Free|Open|Net)BSD */ - #include - #define __BIG_ENDIAN BIG_ENDIAN - #define __LITTLE_ENDIAN LITTLE_ENDIAN - #define __BYTE_ORDER BYTE_ORDER -#elif defined(IS_MACOSX) || (defined(BSD) && (BSD >= 199103)) /* Other BSD */ - #include - #define __BIG_ENDIAN BIG_ENDIAN - #define __LITTLE_ENDIAN LITTLE_ENDIAN - #define __BYTE_ORDER BYTE_ORDER -#elif defined(IS_WINDOWS) /* Windows is assumed to be little endian only. */ - #define __BIG_ENDIAN 4321 - #define __LITTLE_ENDIAN 1234 - #define __BYTE_ORDER __LITTLE_ENDIAN -#endif - -/* Fallback to custom constants. */ -#if !defined(__BIG_ENDIAN) - #define __BIG_ENDIAN 4321 -#endif - -#if !defined(__LITTLE_ENDIAN) - #define __LITTLE_ENDIAN 1234 -#endif - -/* Prefer compiler flag settings if given. */ -#if defined(MM_BIG_ENDIAN) - #undef __BYTE_ORDER /* Avoid redefined macro compiler warning. */ - #define __BYTE_ORDER __BIG_ENDIAN -#elif defined(MM_LITTLE_ENDIAN) - #undef __BYTE_ORDER /* Avoid redefined macro compiler warning. */ - #define __BYTE_ORDER __LITTLE_ENDIAN -#endif - -/* Define default endian-ness. */ -#ifndef __LITTLE_ENDIAN - #define __LITTLE_ENDIAN 1234 -#endif /* __LITTLE_ENDIAN */ - -#ifndef __BIG_ENDIAN - #define __BIG_ENDIAN 4321 -#endif /* __BIG_ENDIAN */ - -#ifndef __BYTE_ORDER - #warning "Byte order not defined on your system; assuming little endian" - #define __BYTE_ORDER __LITTLE_ENDIAN -#endif /* __BYTE_ORDER */ - -#if __BYTE_ORDER != __BIG_ENDIAN && __BYTE_ORDER != __LITTLE_ENDIAN - #error "__BYTE_ORDER set to unknown byte order" -#endif - -#if defined(IS_MACOSX) - #include - - /* OS X system functions. */ - #define bitswap16(i) OSSwapInt16(i) - #define bitswap32(i) OSSwapInt32(i) - #define swapLittleAndHost32(i) OSSwapLittleToHostInt32(i) - #define swapLittleAndHost16(i) OSSwapLittleToHostInt16(i) -#else - #ifndef bitswap16 - #if defined(bswap16) - #define bitswap16(i) bswap16(i) /* FreeBSD system function */ - #elif defined(bswap_16) - #define bitswap16(i) bswap_16(i) /* Linux system function */ - #else /* Default macro */ - #define bitswap16(i) (((uint16_t)(i) & 0xFF00) >> 8) | \ - (((uint16_t)(i) & 0x00FF) << 8) - #endif - #endif /* bitswap16 */ - - #ifndef bitswap32 - #if defined(bswap32) - #define bitswap32(i) bswap32(i) /* FreeBSD system function. */ - #elif defined(bswap_32) - #define bitswap32(i) bswap_32(i) /* Linux system function. */ - #else /* Default macro */ - #define bitswap32(i) (((uint32_t)(i) & 0xFF000000) >> 24) | \ - ((uint32_t)((i) & 0x00FF0000) >> 8) | \ - ((uint32_t)((i) & 0x0000FF00) << 8) | \ - ((uint32_t)((i) & 0x000000FF) << 24) - #endif - #endif /* bitswap32 */ -#endif - -#if __BYTE_ORDER == __BIG_ENDIAN - /* Little endian to/from host byte order (big endian). */ - #ifndef swapLittleAndHost16 - #define swapLittleAndHost16(i) bitswap16(i) - #endif /* swapLittleAndHost16 */ - - #ifndef swapLittleAndHost32 - #define swapLittleAndHost32(i) bitswap32(i) - #endif /* swapLittleAndHost32 */ -#elif __BYTE_ORDER == __LITTLE_ENDIAN - /* We are already little endian, so no conversion is needed. */ - #ifndef swapLittleAndHost16 - #define swapLittleAndHost16(i) i - #endif /* swapLittleAndHost16 */ - - #ifndef swapLittleAndHost32 - #define swapLittleAndHost32(i) i - #endif /* swapLittleAndHost32 */ -#endif - -#endif /* ENDIAN_H */ diff --git a/base/file_io.h b/base/file_io.h deleted file mode 100644 index 427038be..00000000 --- a/base/file_io.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#ifndef FILE_IO_H -#define FILE_IO_H - -#include "MMBitmap.h" -#include -#include - - -enum _MMImageType { - kInvalidImageType = 0, - kPNGImageType, - kBMPImageType /* Currently only PNG and BMP are supported. */ -}; - -typedef uint16_t MMImageType; - -enum _MMIOError { - kMMIOUnsupportedTypeError = 0 -}; - -typedef uint16_t MMIOError; - -const char *getExtension(const char *fname, size_t len); - -/* Returns best guess at the MMImageType based on a file extension, or - * |kInvalidImageType| if no matching type was found. */ -MMImageType imageTypeFromExtension(const char *ext); - -/* Attempts to parse the file of the given type at the given path. - * |filepath| is an ASCII string describing the absolute POSIX path. - * Returns new bitmap (to be destroy()'d by caller) on success, NULL on error. - * If |error| is non-NULL, it will be set to the error code on return. - */ -MMBitmapRef newMMBitmapFromFile(const char *path, MMImageType type, MMIOError *err); - -/* Saves |bitmap| to a file of the given type at the given path. - * |filepath| is an ASCII string describing the absolute POSIX path. - * Returns 0 on success, -1 on error. */ -int saveMMBitmapToFile(MMBitmapRef bitmap, const char *path, MMImageType type); - -/* Returns description of given error code. - * Returned string is constant and hence should not be freed. */ -const char *MMIOErrorString(MMImageType type, MMIOError error); - -#endif /* IO_H */ diff --git a/base/file_io_c.h b/base/file_io_c.h deleted file mode 100644 index e2d71802..00000000 --- a/base/file_io_c.h +++ /dev/null @@ -1,70 +0,0 @@ -#include "file_io.h" -// #include "os.h" -// #include "bmp_io_c.h" -#include "png_io_c.h" -#include /* For fputs() */ -#include /* For strcmp() */ -#include /* For tolower() */ - -const char *getExtension(const char *fname, size_t len){ - if (fname == NULL || len <= 0) return NULL; - - while (--len > 0 && fname[len] != '.' && fname[len] != '\0') - ; - - return fname + len + 1; -} - -MMImageType imageTypeFromExtension(const char *extension){ - char ext[4]; - const size_t maxlen = sizeof(ext) / sizeof(ext[0]); - size_t i; - - for (i = 0; extension[i] != '\0'; ++i) { - if (i >= maxlen) return kInvalidImageType; - ext[i] = tolower(extension[i]); - } - ext[i] = '\0'; - - if (strcmp(ext, "png") == 0) { - return kPNGImageType; - } else if (strcmp(ext, "bmp") == 0) { - return kBMPImageType; - } else { - return kInvalidImageType; - } -} - -MMBitmapRef newMMBitmapFromFile(const char *path, MMImageType type, MMIOError *err){ - switch (type) { - case kBMPImageType: - return newMMBitmapFromBMP(path, err); - case kPNGImageType: - return newMMBitmapFromPNG(path, err); - default: - if (err != NULL) *err = kMMIOUnsupportedTypeError; - return NULL; - } -} - -int saveMMBitmapToFile(MMBitmapRef bitmap, const char *path, MMImageType type){ - switch (type) { - case kBMPImageType: - return saveMMBitmapAsBMP(bitmap, path); - case kPNGImageType: - return saveMMBitmapAsPNG(bitmap, path); - default: - return -1; - } -} - -const char *MMIOErrorString(MMImageType type, MMIOError error){ - switch (type) { - case kBMPImageType: - return MMBMPReadErrorString(error); - case kPNGImageType: - return MMPNGReadErrorString(error); - default: - return "Unsupported image type"; - } -} diff --git a/base/inline_keywords.h b/base/inline_keywords.h index a86b426b..db0cc6dc 100644 --- a/base/inline_keywords.h +++ b/base/inline_keywords.h @@ -1,7 +1,6 @@ #pragma once -/* A complicated, portable model for declaring inline functions in - * header files. */ +/* A complicated, portable model for declaring inline functions in header files. */ #if !defined(H_INLINE) #if defined(__GNUC__) #define H_INLINE static __inline__ __attribute__((always_inline)) diff --git a/base/io.c b/base/io.c deleted file mode 100644 index 1a10dbb3..00000000 --- a/base/io.c +++ /dev/null @@ -1,70 +0,0 @@ -#include "file_io.h" -#include "os.h" -#include "bmp_io.h" -#include "png_io.h" -#include /* For fputs() */ -#include /* For strcmp() */ -#include /* For tolower() */ - -const char *getExtension(const char *fname, size_t len){ - if (fname == NULL || len <= 0) return NULL; - - while (--len > 0 && fname[len] != '.' && fname[len] != '\0') - ; - - return fname + len + 1; -} - -MMImageType imageTypeFromExtension(const char *extension){ - char ext[4]; - const size_t maxlen = sizeof(ext) / sizeof(ext[0]); - size_t i; - - for (i = 0; extension[i] != '\0'; ++i) { - if (i >= maxlen) return kInvalidImageType; - ext[i] = tolower(extension[i]); - } - ext[i] = '\0'; - - if (strcmp(ext, "png") == 0) { - return kPNGImageType; - } else if (strcmp(ext, "bmp") == 0) { - return kBMPImageType; - } else { - return kInvalidImageType; - } -} - -MMBitmapRef newMMBitmapFromFile(const char *path, MMImageType type, MMIOError *err){ - switch (type) { - case kBMPImageType: - return newMMBitmapFromBMP(path, err); - case kPNGImageType: - return newMMBitmapFromPNG(path, err); - default: - if (err != NULL) *err = kMMIOUnsupportedTypeError; - return NULL; - } -} - -int saveMMBitmapToFile(MMBitmapRef bitmap, const char *path, MMImageType type){ - switch (type) { - case kBMPImageType: - return saveMMBitmapAsBMP(bitmap, path); - case kPNGImageType: - return saveMMBitmapAsPNG(bitmap, path); - default: - return -1; - } -} - -const char *MMIOErrorString(MMImageType type, MMIOError error){ - switch (type) { - case kBMPImageType: - return MMBMPReadErrorString(error); - case kPNGImageType: - return MMPNGReadErrorString(error); - default: - return "Unsupported image type"; - } -} diff --git a/base/microsleep.h b/base/microsleep.h index bbb8a4ff..2c08258e 100644 --- a/base/microsleep.h +++ b/base/microsleep.h @@ -5,6 +5,7 @@ #include "os.h" #include "inline_keywords.h" +// todo: removed #if !defined(IS_WINDOWS) /* Make sure nanosleep gets defined even when using C89. */ #if !defined(__USE_POSIX199309) || !__USE_POSIX199309 @@ -14,22 +15,12 @@ #include /* For nanosleep() */ #endif -/* - * A more widely supported alternative to usleep(), based on Sleep() in Windows - * and nanosleep() everywhere else. - * - * Pauses execution for the given amount of milliseconds. - */ -H_INLINE void microsleep(double milliseconds) -{ +/* A more widely supported alternative to usleep(), based on Sleep() in Windows and nanosleep() */ +H_INLINE void microsleep(double milliseconds) { #if defined(IS_WINDOWS) Sleep((DWORD)milliseconds); /* (Unfortunately truncated to a 32-bit integer.) */ #else - /* Technically, nanosleep() is not an ANSI function, but it is the most - * supported precise sleeping function I can find. - * - * If it is really necessary, it may be possible to emulate this with some - * hack using select() in the future if we really have to. */ + /* Technically, nanosleep() is not an ANSI function */ struct timespec sleepytime; sleepytime.tv_sec = milliseconds / 1000; sleepytime.tv_nsec = (milliseconds - (sleepytime.tv_sec * 1000)) * 1000000; diff --git a/base/ms_stdbool.h b/base/ms_stdbool.h deleted file mode 100644 index a6554452..00000000 --- a/base/ms_stdbool.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#if !defined(MS_STDBOOL_H) && \ - (!defined(__bool_true_false_are_defined) || __bool_true_false_are_defined) -#define MS_STDBOOL_H - -#ifndef _MSC_VER - #error "Use this header only with Microsoft Visual C++ compilers!" -#endif /* _MSC_VER */ - -#define __bool_true_false_are_defined 1 - -#ifndef __cplusplus - - #if defined(true) || defined(false) || defined(bool) - #error "Boolean type already defined" - #endif - - enum { - false = 0, - true = 1 - }; - - typedef unsigned char bool; - -#endif /* !__cplusplus */ - -#endif /* MS_STDBOOL_H */ diff --git a/base/ms_stdint.h b/base/ms_stdint.h deleted file mode 100644 index 24c33ef0..00000000 --- a/base/ms_stdint.h +++ /dev/null @@ -1,224 +0,0 @@ -/* ISO C9x compliant stdint.h for Microsoft Visual Studio - * Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 - * - * Copyright (c) 2006-2008 Alexander Chemeris - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _MSC_VER - #error "Use this header only with Microsoft Visual C++ compilers!" -#endif /* _MSC_VER */ - -#ifndef MSC_STDINT_H -#define MSC_STDINT_H - -#if _MSC_VER > 1000 - #pragma once -#endif - -#include - -/* For Visual Studio 6 in C++ mode and for many Visual Studio versions when - * compiling for ARM we should wrap include with 'extern "C++" {}' - * or compiler give many errors like this: */ -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - #include -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/* Define _W64 macros to mark types changing their size, like intptr_t. */ -#ifndef _W64 - #if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 - #define _W64 __w64 - #else - #define _W64 - #endif -#endif - - -/* 7.18.1 Integer types */ - -/* 7.18.1.1 Exact-width integer types */ - -/* Visual Studio 6 and Embedded Visual C++ 4 doesn't - * realize that, e.g. char has the same size as __int8 - * so we give up on __intX for them. */ -#if _MSC_VER < 1300 - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - -/* 7.18.1.2 Minimum-width integer types */ -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -/* 7.18.1.3 Fastest minimum-width integer types */ -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -/* 7.18.1.4 Integer types capable of holding object pointers */ -#if defined(_WIN64) - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif /* _WIN64 ] */ - -/* 7.18.1.5 Greatest-width integer types */ -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - -/* 7.18.2 Limits of specified-width integer types */ - -/* See footnote 220 at page 257 and footnote 221 at page 259 */ -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) - - /* 7.18.2.1 Limits of exact-width integer types */ - #define INT8_MIN ((int8_t)_I8_MIN) - #define INT8_MAX _I8_MAX - #define INT16_MIN ((int16_t)_I16_MIN) - #define INT16_MAX _I16_MAX - #define INT32_MIN ((int32_t)_I32_MIN) - #define INT32_MAX _I32_MAX - #define INT64_MIN ((int64_t)_I64_MIN) - #define INT64_MAX _I64_MAX - #define UINT8_MAX _UI8_MAX - #define UINT16_MAX _UI16_MAX - #define UINT32_MAX _UI32_MAX - #define UINT64_MAX _UI64_MAX - - /* 7.18.2.2 Limits of minimum-width integer types */ - #define INT_LEAST8_MIN INT8_MIN - #define INT_LEAST8_MAX INT8_MAX - #define INT_LEAST16_MIN INT16_MIN - #define INT_LEAST16_MAX INT16_MAX - #define INT_LEAST32_MIN INT32_MIN - #define INT_LEAST32_MAX INT32_MAX - #define INT_LEAST64_MIN INT64_MIN - #define INT_LEAST64_MAX INT64_MAX - #define UINT_LEAST8_MAX UINT8_MAX - #define UINT_LEAST16_MAX UINT16_MAX - #define UINT_LEAST32_MAX UINT32_MAX - #define UINT_LEAST64_MAX UINT64_MAX - - /* 7.18.2.4 Limits of integer types capable of holding object pointers */ - #if defined(_WIN64) - #define INTPTR_MIN INT64_MIN - #define INTPTR_MAX INT64_MAX - #define UINTPTR_MAX UINT64_MAX - #else - #define INTPTR_MIN INT32_MIN - #define INTPTR_MAX INT32_MAX - #define UINTPTR_MAX UINT32_MAX - #endif - - /* 7.18.3 Limits of other integer types */ - - #if defined(_WIN64) - #define PTRDIFF_MIN _I64_MIN - #define PTRDIFF_MAX _I64_MAX - #else - #define PTRDIFF_MIN _I32_MIN - #define PTRDIFF_MAX _I32_MAX - #endif /* _WIN64 */ - - #define SIG_ATOMIC_MIN INT_MIN - #define SIG_ATOMIC_MAX INT_MAX - - #ifndef SIZE_MAX - #if defined(_WIN64) - #define SIZE_MAX _UI64_MAX - #else - #define SIZE_MAX _UI32_MAX - #endif - #endif - - /* WCHAR_MIN and WCHAR_MAX are also defined in */ - #ifndef WCHAR_MIN - #define WCHAR_MIN 0 - #endif /* WCHAR_MIN */ - - #ifndef WCHAR_MAX - #define WCHAR_MAX _UI16_MAX - #endif /* WCHAR_MAX */ - - #define WINT_MIN 0 - #define WINT_MAX _UI16_MAX -#endif /* __STDC_LIMIT_MACROS */ - - -/* 7.18.4 Limits of other integer types */ - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) /* See footnote 224 at page 260 */ - - /* 7.18.4.1 Macros for minimum-width integer constants */ - - #define INT8_C(val) val##i8 - #define INT16_C(val) val##i16 - #define INT32_C(val) val##i32 - #define INT64_C(val) val##i64 - - #define UINT8_C(val) val##ui8 - #define UINT16_C(val) val##ui16 - #define UINT32_C(val) val##ui32 - #define UINT64_C(val) val##ui64 - - /* 7.18.4.2 Macros for greatest-width integer constants */ - #define INTMAX_C INT64_C - #define UINTMAX_C UINT64_C - -#endif /* __STDC_CONSTANT_MACROS */ - -#endif /* MSC_STDINT_H */ diff --git a/base/os.h b/base/os.h index ab469892..30a063de 100644 --- a/base/os.h +++ b/base/os.h @@ -2,19 +2,12 @@ #ifndef OS_H #define OS_H -/* Python versions under 2.5 don't support this macro, but it's not - * terribly difficult to replicate: */ -#ifndef PyModule_AddIntMacro - #define PyModule_AddIntMacro(module, macro) \ - PyModule_AddIntConstant(module, #macro, macro) -#endif /* PyModule_AddIntMacro */ - #if !defined(IS_MACOSX) && defined(__APPLE__) && defined(__MACH__) #define IS_MACOSX #endif /* IS_MACOSX */ #if !defined(IS_WINDOWS) && (defined(WIN32) || defined(_WIN32) || \ - defined(__WIN32__) || defined(__WINDOWS__) || defined(__CYGWIN__)) + defined(__WIN32__) || defined(__WINDOWS__) || defined(__CYGWIN__)) #define IS_WINDOWS #endif /* IS_WINDOWS */ @@ -30,8 +23,7 @@ #error "Sorry, this platform isn't supported yet!" #endif -/* Interval to align by for large buffers (e.g. bitmaps). */ -/* Must be a power of 2. */ +/* Interval to align by for large buffers (e.g. bitmaps). Must be a power of 2. */ #ifndef BYTE_ALIGN #define BYTE_ALIGN 4 /* Bytes to align pixel buffers to. */ /* #include */ @@ -46,4 +38,18 @@ #define ADD_PADDING(width) (BYTE_ALIGN + (((width) - 1) & ~(BYTE_ALIGN - 1))) #endif +#if defined(IS_WINDOWS) + #if defined (_WIN64) + #define RobotGo_64 + #else + #define RobotGo_32 + #endif +#else + #if defined (__x86_64__) + #define RobotGo_64 + #else + #define RobotGo_32 + #endif +#endif + #endif /* OS_H */ diff --git a/base/pasteboard.h b/base/pasteboard.h deleted file mode 100644 index 7ef55075..00000000 --- a/base/pasteboard.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#ifndef PASTEBOARD_H -#define PASTEBOARD_H - -#include "MMBitmap.h" -#include "file_io.h" - -enum _MMBitmapPasteError { - kMMPasteNoError = 0, - kMMPasteGenericError, - kMMPasteOpenError, - kMMPasteClearError, - kMMPasteDataError, - kMMPastePasteError, - kMMPasteUnsupportedError -}; - -typedef MMIOError MMPasteError; - -/* Copies |bitmap| to the pasteboard as a PNG. - * Returns 0 on success, non-zero on error. */ -MMPasteError copyMMBitmapToPasteboard(MMBitmapRef bitmap); - -/* Returns description of given MMPasteError. - * Returned string is constant and hence should not be freed. */ -const char *MMPasteErrorString(MMPasteError error); - -#endif /* PASTEBOARD_H */ diff --git a/base/pasteboard_c.h b/base/pasteboard_c.h deleted file mode 100644 index c829c1d1..00000000 --- a/base/pasteboard_c.h +++ /dev/null @@ -1,106 +0,0 @@ -#include "pasteboard.h" -#include "os.h" - -#if defined(IS_MACOSX) - #include "png_io.h" - #include -#elif defined(IS_WINDOWS) - #include "bmp_io.h" -#endif - -MMPasteError copyMMBitmapToPasteboard(MMBitmapRef bitmap) -{ -#if defined(IS_MACOSX) - PasteboardRef clipboard; - - size_t len; - uint8_t *pngbuf; - CFDataRef data; - OSStatus err; - - if (PasteboardCreate(kPasteboardClipboard, &clipboard) != noErr) { - return kMMPasteOpenError; - } - - if (PasteboardClear(clipboard) != noErr) { - CFRelease(clipboard); - return kMMPasteClearError; - } - - pngbuf = createPNGData(bitmap, &len); - if (pngbuf == NULL) { - CFRelease(clipboard); - return kMMPasteDataError; - } - - data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, pngbuf, len, - kCFAllocatorNull); - if (data == NULL) { - CFRelease(clipboard); - free(pngbuf); - return kMMPasteDataError; - } - - err = PasteboardPutItemFlavor(clipboard, bitmap, kUTTypePNG, data, 0); - CFRelease(data); - CFRelease(clipboard); - free(pngbuf); - return (err == noErr) ? kMMPasteNoError : kMMPastePasteError; -#elif defined(IS_WINDOWS) - MMPasteError ret = kMMPasteNoError; - uint8_t *bmpData; - size_t len; - HGLOBAL handle; - - if (!OpenClipboard(NULL)) return kMMPasteOpenError; - if (!EmptyClipboard()) return kMMPasteClearError; - - bmpData = createBitmapData(bitmap, &len); - if (bmpData == NULL) return kMMPasteDataError; - - /* CF_DIB does not include the BITMAPFILEHEADER struct (and displays a - * cryptic error if it is included). */ - len -= sizeof(BITMAPFILEHEADER); - - /* SetClipboardData() needs a "handle", not just a buffer, so we have to - * allocate one with GlobalAlloc(). */ - if ((handle = GlobalAlloc(GMEM_MOVEABLE, len)) == NULL) { - CloseClipboard(); - free(bmpData); - return kMMPasteDataError; - } - - memcpy(GlobalLock(handle), bmpData + sizeof(BITMAPFILEHEADER), len); - GlobalUnlock(handle); - free(bmpData); - - if (SetClipboardData(CF_DIB, handle) == NULL) { - ret = kMMPastePasteError; - } - - CloseClipboard(); - GlobalFree(handle); - return ret; -#elif defined(USE_X11) - /* TODO (X11's clipboard is _weird_.) */ - return kMMPasteUnsupportedError; -#endif -} - -const char *MMPasteErrorString(MMPasteError err) -{ - switch (err) { - case kMMPasteOpenError: - return "Could not open pasteboard"; - case kMMPasteClearError: - return "Could not clear pasteboard"; - case kMMPasteDataError: - return "Could not create image data from bitmap"; - case kMMPastePasteError: - return "Could not paste data"; - case kMMPasteUnsupportedError: - return "Unsupported platform"; - default: - return NULL; - } -} diff --git a/base/png_io.h b/base/png_io.h deleted file mode 100644 index 0187ce35..00000000 --- a/base/png_io.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#ifndef PNG_IO_H -#define PNG_IO_H - -// #include "MMBitmap_c.h" -// #include "file_io_c.h" - -enum _PNGReadError { - kPNGGenericError = 0, - kPNGReadError, - kPNGAccessError, - kPNGInvalidHeaderError -}; - -typedef MMIOError MMPNGReadError; - -/* Returns description of given MMPNGReadError. - * Returned string is constant and hence should not be freed. */ -const char *MMPNGReadErrorString(MMIOError error); - -/* Attempts to read PNG file at path; returns new MMBitmap on success, or - * NULL on error. If |error| is non-NULL, it will be set to the error code - * on return. - * Responsibility for destroy()'ing returned MMBitmap is left up to caller. */ -MMBitmapRef newMMBitmapFromPNG(const char *path, MMPNGReadError *error); - -/* Attempts to write PNG at path; returns 0 on success, -1 on error. */ -int saveMMBitmapAsPNG(MMBitmapRef bitmap, const char *path); - -/* Returns a buffer containing the raw PNG file data, ready to be saved to a - * file. |len| will be set to the number of bytes allocated in the returned - * buffer (it cannot be NULL). - * - * Responsibility for free()'ing data is left up to the caller. */ -uint8_t *createPNGData(MMBitmapRef bitmap, size_t *len); - -#endif /* PNG_IO_H */ diff --git a/base/png_io_c.h b/base/png_io_c.h deleted file mode 100644 index 5aab25f2..00000000 --- a/base/png_io_c.h +++ /dev/null @@ -1,350 +0,0 @@ -#include "png_io.h" -#include "os.h" -// #include "libpng/png.c" -#if defined(IS_MACOSX) - #include "../cdeps/mac/png.h" -#elif defined(USE_X11) - #include -#elif defined(IS_WINDOWS) - #if defined (__x86_64__) - #include "../cdeps/win64/png.h" - #else - #include "../cdeps/win32/png.h" - #endif -#endif - -#include /* fopen() */ -#include /* malloc/realloc */ -#include - -#if defined(_MSC_VER) - #include "ms_stdint.h" - #include "ms_stdbool.h" -#else - #include - #include -#endif - -const char *MMPNGReadErrorString(MMIOError error) -{ - switch (error) { - case kPNGAccessError: - return "Could not open file"; - case kPNGReadError: - return "Could not read file"; - case kPNGInvalidHeaderError: - return "Not a PNG file"; - default: - return NULL; - } -} - -MMBitmapRef newMMBitmapFromPNG(const char *path, MMPNGReadError *err) -{ - FILE *fp; - uint8_t header[8]; - png_struct *png_ptr = NULL; - png_info *info_ptr = NULL; - png_byte bit_depth, color_type; - uint8_t *row, *bitmapData; - uint8_t bytesPerPixel; - png_uint_32 width, height, y; - uint32_t bytewidth; - - if ((fp = fopen(path, "rb")) == NULL) { - if (err != NULL) *err = kPNGAccessError; - return NULL; - } - - /* Initialize error code to generic value. */ - if (err != NULL) *err = kPNGGenericError; - - /* Validate the PNG. */ - if (fread(header, 1, sizeof header, fp) == 0) { - if (err != NULL) *err = kPNGReadError; - goto bail; - } else if (png_sig_cmp(header, 0, sizeof(header)) != 0) { - if (err != NULL) *err = kPNGInvalidHeaderError; - goto bail; - } - - png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - if (png_ptr == NULL) goto bail; - - info_ptr = png_create_info_struct(png_ptr); - if (info_ptr == NULL) goto bail; - - /* Set up error handling. */ - if (setjmp(png_jmpbuf(png_ptr))) { - goto bail; - } - - png_init_io(png_ptr, fp); - - /* Skip past the header. */ - png_set_sig_bytes(png_ptr, sizeof header); - - png_read_info(png_ptr, info_ptr); - - /* Convert different image types to common type to be read. */ - bit_depth = png_get_bit_depth(png_ptr, info_ptr); - color_type = png_get_color_type(png_ptr, info_ptr); - - /* Convert color palettes to RGB. */ - if (color_type == PNG_COLOR_TYPE_PALETTE) { - png_set_palette_to_rgb(png_ptr); - } - - /* Convert PNG to bit depth of 8. */ - if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { - png_set_expand_gray_1_2_4_to_8(png_ptr); - } else if (bit_depth == 16) { - png_set_strip_16(png_ptr); - } - - /* Convert transparency chunk to alpha channel. */ - if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { - png_set_tRNS_to_alpha(png_ptr); - } - - /* Convert gray images to RGB. */ - if (color_type == PNG_COLOR_TYPE_GRAY || - color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { - png_set_gray_to_rgb(png_ptr); - } - - /* Ignore alpha for now. */ - if (color_type & PNG_COLOR_MASK_ALPHA) { - png_set_strip_alpha(png_ptr); - } - - /* Get image attributes. */ - width = png_get_image_width(png_ptr, info_ptr); - height = png_get_image_height(png_ptr, info_ptr); - bytesPerPixel = 3; /* All images decompress to this size. */ - bytewidth = ADD_PADDING(width * bytesPerPixel); /* Align width. */ - - /* Decompress the PNG row by row. */ - bitmapData = calloc(1, bytewidth * height); - row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); - if (bitmapData == NULL || row == NULL) goto bail; - for (y = 0; y < height; ++y) { - png_uint_32 x; - const uint32_t rowOffset = y * bytewidth; - uint8_t *rowptr = row; - png_read_row(png_ptr, (png_byte *)row, NULL); - - for (x = 0; x < width; ++x) { - const uint32_t colOffset = x * bytesPerPixel; - MMRGBColor *color = (MMRGBColor *)(bitmapData + rowOffset + colOffset); - color->red = *rowptr++; - color->green = *rowptr++; - color->blue = *rowptr++; - } - } - free(row); - - /* Finish reading. */ - png_read_end(png_ptr, NULL); - png_destroy_read_struct(&png_ptr, &info_ptr, NULL); - fclose(fp); - - return createMMBitmap(bitmapData, width, height, - bytewidth, bytesPerPixel * 8, bytesPerPixel); - -bail: - png_destroy_read_struct(&png_ptr, &info_ptr, NULL); - fclose(fp); - return NULL; -} - -struct _PNGWriteInfo { - png_struct *png_ptr; - png_info *info_ptr; - png_byte **row_pointers; - size_t row_count; - bool free_row_pointers; -}; - -typedef struct _PNGWriteInfo PNGWriteInfo; -typedef PNGWriteInfo *PNGWriteInfoRef; - -/* Returns pointer to PNGWriteInfo struct containing data ready to be used with - * functions such as png_write_png(). - * - * It is the caller's responsibility to destroy() the returned structure with - * destroyPNGWriteInfo(). */ -static PNGWriteInfoRef createPNGWriteInfo(MMBitmapRef bitmap) -{ - PNGWriteInfoRef info = malloc(sizeof(PNGWriteInfo)); - png_uint_32 y; - - if (info == NULL) return NULL; - info->png_ptr = NULL; - info->info_ptr = NULL; - info->row_pointers = NULL; - - assert(bitmap != NULL); - - /* Initialize the write struct. */ - info->png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, - NULL, NULL, NULL); - if (info->png_ptr == NULL) goto bail; - - /* Set up error handling. */ - if (setjmp(png_jmpbuf(info->png_ptr))) { - png_destroy_write_struct(&(info->png_ptr), &(info->info_ptr)); - goto bail; - } - - /* Initialize the info struct. */ - info->info_ptr = png_create_info_struct(info->png_ptr); - if (info->info_ptr == NULL) { - png_destroy_write_struct(&(info->png_ptr), NULL); - goto bail; - } - - /* Set image attributes. */ - png_set_IHDR(info->png_ptr, - info->info_ptr, - (png_uint_32)bitmap->width, - (png_uint_32)bitmap->height, - 8, - PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, - PNG_FILTER_TYPE_DEFAULT); - - info->row_count = bitmap->height; - info->row_pointers = png_malloc(info->png_ptr, - sizeof(png_byte *) * info->row_count); - - if (bitmap->bytesPerPixel == 3) { - /* No alpha channel; image data can be copied directly. */ - for (y = 0; y < info->row_count; ++y) { - info->row_pointers[y] = bitmap->imageBuffer + (bitmap->bytewidth * y); - } - info->free_row_pointers = false; - - /* Convert BGR to RGB if necessary. */ - if (MMRGB_IS_BGR) { - png_set_bgr(info->png_ptr); - } - } else { - /* Ignore alpha channel; copy image data row by row. */ - const size_t bytesPerPixel = 3; - const size_t bytewidth = ADD_PADDING(bitmap->width * bytesPerPixel); - - for (y = 0; y < info->row_count; ++y) { - png_uint_32 x; - png_byte *row_ptr = png_malloc(info->png_ptr, bytewidth); - info->row_pointers[y] = row_ptr; - for (x = 0; x < bitmap->width; ++x) { - MMRGBColor *color = MMRGBColorRefAtPoint(bitmap, x, y); - row_ptr[0] = color->red; - row_ptr[1] = color->green; - row_ptr[2] = color->blue; - - row_ptr += bytesPerPixel; - } - } - info->free_row_pointers = true; - } - - png_set_rows(info->png_ptr, info->info_ptr, info->row_pointers); - return info; - -bail: - if (info != NULL) free(info); - return NULL; -} - -/* Free memory in use by |info|. */ -static void destroyPNGWriteInfo(PNGWriteInfoRef info) -{ - assert(info != NULL); - if (info->row_pointers != NULL) { - if (info->free_row_pointers) { - size_t y; - for (y = 0; y < info->row_count; ++y) { - free(info->row_pointers[y]); - } - } - png_free(info->png_ptr, info->row_pointers); - } - - png_destroy_write_struct(&(info->png_ptr), &(info->info_ptr)); - free(info); -} - -int saveMMBitmapAsPNG(MMBitmapRef bitmap, const char *path) -{ - FILE *fp = fopen(path, "wb"); - PNGWriteInfoRef info; - if (fp == NULL) return -1; - - if ((info = createPNGWriteInfo(bitmap)) == NULL) { - fclose(fp); - return -1; - } - - png_init_io(info->png_ptr, fp); - png_write_png(info->png_ptr, info->info_ptr, PNG_TRANSFORM_IDENTITY, NULL); - fclose(fp); - - destroyPNGWriteInfo(info); - return 0; -} - -/* Structure to store PNG image bytes. */ -struct io_data -{ - uint8_t *buffer; /* Pointer to raw file data. */ - size_t size; /* Number of bytes actually written to buffer. */ - size_t allocedSize; /* Number of bytes allocated for buffer. */ -}; - -/* Called each time libpng attempts to write data in createPNGData(). */ -void png_append_data(png_struct *png_ptr, - png_byte *new_data, - png_size_t length) -{ - struct io_data *data = png_get_io_ptr(png_ptr); - data->size += length; - - /* Allocate or grow buffer. */ - if (data->buffer == NULL) { - data->allocedSize = data->size; - data->buffer = png_malloc(png_ptr, data->allocedSize); - assert(data->buffer != NULL); - } else if (data->allocedSize < data->size) { - do { - /* Double size each time to avoid calls to realloc. */ - data->allocedSize <<= 1; - } while (data->allocedSize < data->size); - - data->buffer = realloc(data->buffer, data->allocedSize); - } - - /* Copy new bytes to end of buffer. */ - memcpy(data->buffer + data->size - length, new_data, length); -} - -uint8_t *createPNGData(MMBitmapRef bitmap, size_t *len) -{ - PNGWriteInfoRef info = NULL; - struct io_data data = {NULL, 0, 0}; - - assert(bitmap != NULL); - assert(len != NULL); - - if ((info = createPNGWriteInfo(bitmap)) == NULL) return NULL; - - png_set_write_fn(info->png_ptr, &data, &png_append_data, NULL); - png_write_png(info->png_ptr, info->info_ptr, PNG_TRANSFORM_IDENTITY, NULL); - - destroyPNGWriteInfo(info); - - *len = data.size; - return data.buffer; -} diff --git a/base/pubs.h b/base/pubs.h new file mode 100644 index 00000000..1ad716ba --- /dev/null +++ b/base/pubs.h @@ -0,0 +1,33 @@ +#if defined(IS_WINDOWS) + BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { + uint32_t *count = (uint32_t*)dwData; + (*count)++; + return TRUE; + } + + typedef struct{ + HWND hWnd; + DWORD dwPid; + }WNDINFO; + + BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam){ + WNDINFO* pInfo = (WNDINFO*)lParam; + DWORD dwProcessId = 0; + GetWindowThreadProcessId(hWnd, &dwProcessId); + + if (dwProcessId == pInfo->dwPid) { + pInfo->hWnd = hWnd; + return FALSE; + } + return TRUE; + } + + HWND GetHwndByPid(DWORD dwProcessId) { + WNDINFO info = {0}; + info.hWnd = NULL; + info.dwPid = dwProcessId; + EnumWindows(EnumWindowsProc, (LPARAM)&info); + + return info.hWnd; + } +#endif \ No newline at end of file diff --git a/base/rgb.h b/base/rgb.h index db0e3f79..4fbe1479 100644 --- a/base/rgb.h +++ b/base/rgb.h @@ -5,21 +5,7 @@ #include /* For abs() */ #include #include "inline_keywords.h" /* For H_INLINE */ -// #include -#if defined(_MSC_VER) - #include "ms_stdint.h" -#else - #include -#endif - - -/* RGB colors in MMBitmaps are stored as BGR for convenience in converting - * to/from certain formats (mainly OpenGL). - * - * It is best not to rely on the order (simply use rgb.{blue,green,red} to - * access values), but some situations (e.g., glReadPixels) require one to - * do so. In that case, check to make sure to use MMRGB_IS_BGR for future - * compatibility. */ +#include /* #define MMRGB_IS_BGR (offsetof(MMRGBColor, red) > offsetof(MMRGBColor, blue)) */ #define MMRGB_IS_BGR 1 @@ -29,25 +15,19 @@ struct _MMRGBColor { uint8_t green; uint8_t red; }; - typedef struct _MMRGBColor MMRGBColor; -/* MMRGBHex is a hexadecimal color value, akin to HTML's, in the form 0xRRGGBB - * where RR is the red value expressed as hexadecimal, GG is the green value, - * and BB is the blue value. */ +/* MMRGBHex is a hexadecimal color value*/ typedef uint32_t MMRGBHex; #define MMRGBHEX_MIN 0x000000 #define MMRGBHEX_MAX 0xFFFFFF -/* Converts rgb color to hexadecimal value. - * |red|, |green|, and |blue| should each be of the type |uint8_t|, where the - * range is 0 - 255. */ +/* Converts rgb color to hexadecimal value. */ #define RGB_TO_HEX(red, green, blue) (((red) << 16) | ((green) << 8) | (blue)) /* Convenience wrapper for MMRGBColors. */ -H_INLINE MMRGBHex hexFromMMRGB(MMRGBColor rgb) -{ +H_INLINE MMRGBHex hexFromMMRGB(MMRGBColor rgb) { return RGB_TO_HEX(rgb.red, rgb.green, rgb.blue); } @@ -56,8 +36,7 @@ H_INLINE MMRGBHex hexFromMMRGB(MMRGBColor rgb) #define BLUE_FROM_HEX(hex) (hex & 0xFF) /* Converts hexadecimal color to MMRGBColor. */ -H_INLINE MMRGBColor MMRGBFromHex(MMRGBHex hex) -{ +H_INLINE MMRGBColor MMRGBFromHex(MMRGBHex hex) { MMRGBColor color; color.red = RED_FROM_HEX(hex); color.green = GREEN_FROM_HEX(hex); @@ -70,12 +49,8 @@ H_INLINE MMRGBColor MMRGBFromHex(MMRGBHex hex) (c1).blue == (c2).blue && \ (c1).green == (c2).green) -/* Returns whether two colors are similar within the given range, |tolerance|. - * Tolerance can be in the range 0.0f - 1.0f, where 0 denotes the exact - * color and 1 denotes any color. */ -H_INLINE int MMRGBColorSimilarToColor(MMRGBColor c1, MMRGBColor c2, - float tolerance) -{ +/* Returns whether two colors are similar within the given range, |tolerance|.*/ +H_INLINE int MMRGBColorSimilarToColor(MMRGBColor c1, MMRGBColor c2, float tolerance) { /* Speedy case */ if (tolerance <= 0.0f) { return MMRGBColorEqualToColor(c1, c2); @@ -83,27 +58,20 @@ H_INLINE int MMRGBColorSimilarToColor(MMRGBColor c1, MMRGBColor c2, uint8_t d1 = c1.red - c2.red; uint8_t d2 = c1.green - c2.green; uint8_t d3 = c1.blue - c2.blue; - return sqrt((double)(d1 * d1) + - (d2 * d2) + + return sqrt((double)(d1 * d1) + (d2 * d2) + (d3 * d3)) <= (tolerance * 442.0f); } - } /* Identical to MMRGBColorSimilarToColor, only for hex values. */ -H_INLINE int MMRGBHexSimilarToColor(MMRGBHex h1, MMRGBHex h2, float tolerance) -{ +H_INLINE int MMRGBHexSimilarToColor(MMRGBHex h1, MMRGBHex h2, float tolerance) { if (tolerance <= 0.0f) { return h1 == h2; } else { - // uint8_t d1 = RED_FROM_HEX(h1) - RED_FROM_HEX(h2); - // uint8_t d2 = GREEN_FROM_HEX(h1) - GREEN_FROM_HEX(h2); - // uint8_t d3 = BLUE_FROM_HEX(h1) - BLUE_FROM_HEX(h2); int d1 = RED_FROM_HEX(h1) - RED_FROM_HEX(h2); int d2 = GREEN_FROM_HEX(h1) - GREEN_FROM_HEX(h2); int d3 = BLUE_FROM_HEX(h1) - BLUE_FROM_HEX(h2); - return sqrt((double)(d1 * d1) + - (d2 * d2) + + return sqrt((double)(d1 * d1) + (d2 * d2) + (d3 * d3)) <= (tolerance * 442.0f); } } diff --git a/base/snprintf.h b/base/snprintf.h deleted file mode 100644 index 60046e56..00000000 --- a/base/snprintf.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef _PORTABLE_SNPRINTF_H_ -#define _PORTABLE_SNPRINTF_H_ - -#define PORTABLE_SNPRINTF_VERSION_MAJOR 2 -#define PORTABLE_SNPRINTF_VERSION_MINOR 2 - -#include "os.h" -#if defined(IS_MACOSX) - #define HAVE_SNPRINTF -#else - #define HAVE_SNPRINTF - #define PREFER_PORTABLE_SNPRINTF -#endif - -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef HAVE_SNPRINTF -#include -#else -extern int snprintf(char *, size_t, const char *, /*args*/ ...); -extern int vsnprintf(char *, size_t, const char *, va_list); -#endif - -#if defined(HAVE_SNPRINTF) && defined(PREFER_PORTABLE_SNPRINTF) -extern int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...); -extern int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap); -#define snprintf portable_snprintf -#define vsnprintf portable_vsnprintf -#endif - -extern int asprintf (char **ptr, const char *fmt, /*args*/ ...); -extern int vasprintf (char **ptr, const char *fmt, va_list ap); -extern int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...); -extern int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap); - -#endif - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/base/snprintf_c.h b/base/snprintf_c.h deleted file mode 100644 index 22ae3677..00000000 --- a/base/snprintf_c.h +++ /dev/null @@ -1,1019 +0,0 @@ -/* - * snprintf.c - a portable implementation of snprintf - * - * AUTHOR - * Mark Martinec , April 1999. - * - * Copyright 1999, Mark Martinec. All rights reserved. - * - * TERMS AND CONDITIONS - * This program is free software; you can redistribute it and/or modify - * it under the terms of the "Frontier Artistic License" which comes - * with this Kit. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty - * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the Frontier Artistic License for more details. - * - * You should have received a copy of the Frontier Artistic License - * with this Kit in the file named LICENSE.txt . - * If not, I'll be glad to provide one. - * - * FEATURES - * - careful adherence to specs regarding flags, field width and precision; - * - good performance for large string handling (large format, large - * argument or large paddings). Performance is similar to system's sprintf - * and in several cases significantly better (make sure you compile with - * optimizations turned on, tell the compiler the code is strict ANSI - * if necessary to give it more freedom for optimizations); - * - return value semantics per ISO/IEC 9899:1999 ("ISO C99"); - * - written in standard ISO/ANSI C - requires an ANSI C compiler. - * - * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES - * - * This snprintf only supports the following conversion specifiers: - * s, c, d, u, o, x, X, p (and synonyms: i, D, U, O - see below) - * with flags: '-', '+', ' ', '0' and '#'. - * An asterisk is supported for field width as well as precision. - * - * Length modifiers 'h' (short int), 'l' (long int), - * and 'll' (long long int) are supported. - * NOTE: - * If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the - * length modifier 'll' is recognized but treated the same as 'l', - * which may cause argument value truncation! Defining - * SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also - * handles length modifier 'll'. long long int is a language extension - * which may not be portable. - * - * Conversion of numeric data (conversion specifiers d, u, o, x, X, p) - * with length modifiers (none or h, l, ll) is left to the system routine - * sprintf, but all handling of flags, field width and precision as well as - * c and s conversions is done very carefully by this portable routine. - * If a string precision (truncation) is specified (e.g. %.8s) it is - * guaranteed the string beyond the specified precision will not be referenced. - * - * Length modifiers h, l and ll are ignored for c and s conversions (data - * types wint_t and wchar_t are not supported). - * - * The following common synonyms for conversion characters are supported: - * - i is a synonym for d - * - D is a synonym for ld, explicit length modifiers are ignored - * - U is a synonym for lu, explicit length modifiers are ignored - * - O is a synonym for lo, explicit length modifiers are ignored - * The D, O and U conversion characters are nonstandard, they are supported - * for backward compatibility only, and should not be used for new code. - * - * The following is specifically NOT supported: - * - flag ' (thousands' grouping character) is recognized but ignored - * - numeric conversion specifiers: f, e, E, g, G and synonym F, - * as well as the new a and A conversion specifiers - * - length modifier 'L' (long double) and 'q' (quad - use 'll' instead) - * - wide character/string conversions: lc, ls, and nonstandard - * synonyms C and S - * - writeback of converted string length: conversion character n - * - the n$ specification for direct reference to n-th argument - * - locales - * - * It is permitted for str_m to be zero, and it is permitted to specify NULL - * pointer for resulting string argument if str_m is zero (as per ISO C99). - * - * The return value is the number of characters which would be generated - * for the given input, excluding the trailing null. If this value - * is greater or equal to str_m, not all characters from the result - * have been stored in str, output bytes beyond the (str_m-1) -th character - * are discarded. If str_m is greater than zero it is guaranteed - * the resulting string will be null-terminated. - * - * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1, - * but is different from some older and vendor implementations, - * and is also different from XPG, XSH5, SUSv2 specifications. - * For historical discussion on changes in the semantics and standards - * of snprintf see printf(3) man page in the Linux programmers manual. - * - * Routines asprintf and vasprintf return a pointer (in the ptr argument) - * to a buffer sufficiently large to hold the resulting string. This pointer - * should be passed to free(3) to release the allocated storage when it is - * no longer needed. If sufficient space cannot be allocated, these functions - * will return -1 and set ptr to be a NULL pointer. These two routines are a - * GNU C library extensions (glibc). - * - * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf, - * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1 - * characters into the allocated output string, the last character in the - * allocated buffer then gets the terminating null. If the formatted string - * length (the return value) is greater than or equal to the str_m argument, - * the resulting string was truncated and some of the formatted characters - * were discarded. These routines present a handy way to limit the amount - * of allocated memory to some sane value. - * - * AVAILABILITY - * http://www.ijs.si/software/snprintf/ - * - * REVISION HISTORY - * 1999-04 V0.9 Mark Martinec - * - initial version, some modifications after comparing printf - * man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10, - * and checking how Perl handles sprintf (differently!); - * 1999-04-09 V1.0 Mark Martinec - * - added main test program, fixed remaining inconsistencies, - * added optional (long long int) support; - * 1999-04-12 V1.1 Mark Martinec - * - support the 'p' conversion (pointer to void); - * - if a string precision is specified - * make sure the string beyond the specified precision - * will not be referenced (e.g. by strlen); - * 1999-04-13 V1.2 Mark Martinec - * - support synonyms %D=%ld, %U=%lu, %O=%lo; - * - speed up the case of long format string with few conversions; - * 1999-06-30 V1.3 Mark Martinec - * - fixed runaway loop (eventually crashing when str_l wraps - * beyond 2^31) while copying format string without - * conversion specifiers to a buffer that is too short - * (thanks to Edwin Young for - * spotting the problem); - * - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR) - * to snprintf.h - * 2000-02-14 V2.0 (never released) Mark Martinec - * - relaxed license terms: The Artistic License now applies. - * You may still apply the GNU GENERAL PUBLIC LICENSE - * as was distributed with previous versions, if you prefer; - * - changed REVISION HISTORY dates to use ISO 8601 date format; - * - added vsnprintf (patch also independently proposed by - * Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01) - * 2000-06-27 V2.1 Mark Martinec - * - removed POSIX check for str_m<1; value 0 for str_m is - * allowed by ISO C99 (and GNU C library 2.1) - (pointed out - * on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie). - * Besides relaxed license this change in standards adherence - * is the main reason to bump up the major version number; - * - added nonstandard routines asnprintf, vasnprintf, asprintf, - * vasprintf that dynamically allocate storage for the - * resulting string; these routines are not compiled by default, - * see comments where NEED_V?ASN?PRINTF macros are defined; - * - autoconf contributed by Caolan McNamara - * 2000-10-06 V2.2 Mark Martinec - * - BUG FIX: the %c conversion used a temporary variable - * that was no longer in scope when referenced, - * possibly causing incorrect resulting character; - * - BUG FIX: make precision and minimal field width unsigned - * to handle huge values (2^31 <= n < 2^32) correctly; - * also be more careful in the use of signed/unsigned/size_t - * internal variables - probably more careful than many - * vendor implementations, but there may still be a case - * where huge values of str_m, precision or minimal field - * could cause incorrect behaviour; - * - use separate variables for signed/unsigned arguments, - * and for short/int, long, and long long argument lengths - * to avoid possible incompatibilities on certain - * computer architectures. Also use separate variable - * arg_sign to hold sign of a numeric argument, - * to make code more transparent; - * - some fiddling with zero padding and "0x" to make it - * Linux compatible; - * - systematically use macros fast_memcpy and fast_memset - * instead of case-by-case hand optimization; determine some - * breakeven string lengths for different architectures; - * - terminology change: 'format' -> 'conversion specifier', - * 'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")', - * 'alternative form' -> 'alternate form', - * 'data type modifier' -> 'length modifier'; - * - several comments rephrased and new ones added; - * - make compiler not complain about 'credits' defined but - * not used; - */ - - -/* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf. - * - * If HAVE_SNPRINTF is defined this module will not produce code for - * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well, - * causing this portable version of snprintf to be called portable_snprintf - * (and portable_vsnprintf). - */ -/* #define HAVE_SNPRINTF */ - -/* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and - * vsnprintf but you would prefer to use the portable routine(s) instead. - * In this case the portable routine is declared as portable_snprintf - * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf') - * is defined to expand to 'portable_v?snprintf' - see file snprintf.h . - * Defining this macro is only useful if HAVE_SNPRINTF is also defined, - * but does does no harm if defined nevertheless. - */ -/* #define PREFER_PORTABLE_SNPRINTF */ - -/* Define SNPRINTF_LONGLONG_SUPPORT if you want to support - * data type (long long int) and length modifier 'll' (e.g. %lld). - * If undefined, 'll' is recognized but treated as a single 'l'. - * - * If the system's sprintf does not handle 'll' - * the SNPRINTF_LONGLONG_SUPPORT must not be defined! - * - * This is off by default as (long long int) is a language extension. - */ -/* #define SNPRINTF_LONGLONG_SUPPORT */ - -/* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf. - * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly, - * otherwise both snprintf and vsnprintf routines will be defined - * and snprintf will be a simple wrapper around vsnprintf, at the expense - * of an extra procedure call. - */ -/* #define NEED_SNPRINTF_ONLY */ - -/* Define NEED_V?ASN?PRINTF macros if you need library extension - * routines asprintf, vasprintf, asnprintf, vasnprintf respectively, - * and your system library does not provide them. They are all small - * wrapper routines around portable_vsnprintf. Defining any of the four - * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY - * and turns on PREFER_PORTABLE_SNPRINTF. - * - * Watch for name conflicts with the system library if these routines - * are already present there. - * - * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as - * specified by C99, to be able to traverse the same list of arguments twice. - * I don't know of any other standard and portable way of achieving the same. - * With some versions of gcc you may use __va_copy(). You might even get away - * with "ap2 = ap", in this case you must not call va_end(ap2) ! - * #define va_copy(ap2,ap) ap2 = ap - */ -/* #define NEED_ASPRINTF */ -/* #define NEED_ASNPRINTF */ -/* #define NEED_VASPRINTF */ -/* #define NEED_VASNPRINTF */ - - -/* Define the following macros if desired: - * SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE, - * HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE, LINUX_COMPATIBLE, - * DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE, - * PERL_COMPATIBLE, PERL_BUG_COMPATIBLE, - * - * - For portable applications it is best not to rely on peculiarities - * of a given implementation so it may be best not to define any - * of the macros that select compatibility and to avoid features - * that vary among the systems. - * - * - Selecting compatibility with more than one operating system - * is not strictly forbidden but is not recommended. - * - * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE . - * - * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is - * documented in a sprintf man page on a given operating system - * and actually adhered to by the system's sprintf (but not on - * most other operating systems). It may also refer to and enable - * a behaviour that is declared 'undefined' or 'implementation specific' - * in the man page but a given implementation behaves predictably - * in a certain way. - * - * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf - * that contradicts the sprintf man page on the same operating system. - * - * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE - * conditionals take into account all idiosyncrasies of a particular - * implementation, there may be other incompatibilities. - */ - - - -/* ============================================= */ -/* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */ -/* ============================================= */ - -#define PORTABLE_SNPRINTF_VERSION_MAJOR 2 -#define PORTABLE_SNPRINTF_VERSION_MINOR 2 - -#if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF) -# if defined(NEED_SNPRINTF_ONLY) -# undef NEED_SNPRINTF_ONLY -# endif -# if !defined(PREFER_PORTABLE_SNPRINTF) -# define PREFER_PORTABLE_SNPRINTF -# endif -#endif - -#if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE) -#define SOLARIS_COMPATIBLE -#endif - -#if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE) -#define HPUX_COMPATIBLE -#endif - -#if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE) -#define DIGITAL_UNIX_COMPATIBLE -#endif - -#if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE) -#define PERL_COMPATIBLE -#endif - -#if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE) -#define LINUX_COMPATIBLE -#endif - -#include "snprintf.h" -#include -#include -#include -#include -#include -#include -#include - -#ifdef isdigit -#undef isdigit -#endif -#define isdigit(c) ((c) >= '0' && (c) <= '9') - -/* For copying strings longer or equal to 'breakeven_point' - * it is more efficient to call memcpy() than to do it inline. - * The value depends mostly on the processor architecture, - * but also on the compiler and its optimization capabilities. - * The value is not critical, some small value greater than zero - * will be just fine if you don't care to squeeze every drop - * of performance out of the code. - * - * Small values favor memcpy, large values favor inline code. - */ -#if defined(__alpha__) || defined(__alpha) -# define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */ -#endif -#if defined(__i386__) || defined(__i386) -# define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */ -#endif -#if defined(__hppa) -# define breakeven_point 10 /* HP-PA - gcc */ -#endif -#if defined(__sparc__) || defined(__sparc) -# define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */ -#endif - -/* some other values of possible interest: */ -/* #define breakeven_point 8 */ /* VAX 4000 - vaxc */ -/* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */ - -#ifndef breakeven_point -# define breakeven_point 6 /* some reasonable one-size-fits-all value */ -#endif - -#define fast_memcpy(d,s,n) \ - { register size_t nn = (size_t)(n); \ - if (nn >= breakeven_point) memcpy((d), (s), nn); \ - else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ - register char *dd; register const char *ss; \ - for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } } - -#define fast_memset(d,c,n) \ - { register size_t nn = (size_t)(n); \ - if (nn >= breakeven_point) memset((d), (int)(c), nn); \ - else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ - register char *dd; register const int cc=(int)(c); \ - for (dd=(d); nn>0; nn--) *dd++ = cc; } } - -/* prototypes */ - -#if defined(NEED_ASPRINTF) -int asprintf (char **ptr, const char *fmt, /*args*/ ...); -#endif -#if defined(NEED_VASPRINTF) -int vasprintf (char **ptr, const char *fmt, va_list ap); -#endif -#if defined(NEED_ASNPRINTF) -int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...); -#endif -#if defined(NEED_VASNPRINTF) -int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap); -#endif - -#if defined(HAVE_SNPRINTF) -/* declare our portable snprintf routine under name portable_snprintf */ -/* declare our portable vsnprintf routine under name portable_vsnprintf */ -#else -/* declare our portable routines under names snprintf and vsnprintf */ -#define portable_snprintf snprintf -#if !defined(NEED_SNPRINTF_ONLY) -#define portable_vsnprintf vsnprintf -#endif -#endif - -#if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF) -int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...); -#if !defined(NEED_SNPRINTF_ONLY) -int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap); -#endif -#endif - -/* declarations */ - -#if defined(NEED_ASPRINTF) -int asprintf(char **ptr, const char *fmt, /*args*/ ...) { - va_list ap; - size_t str_m; - int str_l; - - *ptr = NULL; - va_start(ap, fmt); /* measure the required size */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap); - va_end(ap); - assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ - *ptr = (char *) malloc(str_m = (size_t)str_l + 1); - if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } - else { - int str_l2; - va_start(ap, fmt); - str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); - va_end(ap); - assert(str_l2 == str_l); - } - return str_l; -} -#endif - -#if defined(NEED_VASPRINTF) -int vasprintf(char **ptr, const char *fmt, va_list ap) { - size_t str_m; - int str_l; - - *ptr = NULL; - { va_list ap2; - va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ - va_end(ap2); - } - assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ - *ptr = (char *) malloc(str_m = (size_t)str_l + 1); - if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } - else { - int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); - assert(str_l2 == str_l); - } - return str_l; -} -#endif - -#if defined(NEED_ASNPRINTF) -int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) { - va_list ap; - int str_l; - - *ptr = NULL; - va_start(ap, fmt); /* measure the required size */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap); - va_end(ap); - assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ - if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */ - /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */ - if (str_m == 0) { /* not interested in resulting string, just return size */ - } else { - *ptr = (char *) malloc(str_m); - if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } - else { - int str_l2; - va_start(ap, fmt); - str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); - va_end(ap); - assert(str_l2 == str_l); - } - } - return str_l; -} -#endif - -#if defined(NEED_VASNPRINTF) -int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) { - int str_l; - - *ptr = NULL; - { va_list ap2; - va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ - va_end(ap2); - } - assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ - if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */ - /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */ - if (str_m == 0) { /* not interested in resulting string, just return size */ - } else { - *ptr = (char *) malloc(str_m); - if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } - else { - int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); - assert(str_l2 == str_l); - } - } - return str_l; -} -#endif - -/* - * If the system does have snprintf and the portable routine is not - * specifically required, this module produces no code for snprintf/vsnprintf. - */ -#if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF) - -#if !defined(NEED_SNPRINTF_ONLY) -int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { - va_list ap; - int str_l; - - va_start(ap, fmt); - str_l = portable_vsnprintf(str, str_m, fmt, ap); - va_end(ap); - return str_l; -} -#endif - -#if defined(NEED_SNPRINTF_ONLY) -int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { -#else -int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) { -#endif - -#if defined(NEED_SNPRINTF_ONLY) - va_list ap; -#endif - size_t str_l = 0; - const char *p = fmt; - -/* In contrast with POSIX, the ISO C99 now says - * that str can be NULL and str_m can be 0. - * This is more useful than the old: if (str_m < 1) return -1; */ - -#if defined(NEED_SNPRINTF_ONLY) - va_start(ap, fmt); -#endif - if (!p) p = ""; - while (*p) { - if (*p != '%') { - /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */ - /* but the following code achieves better performance for cases - * where format string is long and contains few conversions */ - const char *q = strchr(p+1,'%'); - size_t n = !q ? strlen(p) : (q-p); - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memcpy(str+str_l, p, (n>avail?avail:n)); - } - p += n; str_l += n; - } else { - const char *starting_p; - size_t min_field_width = 0, precision = 0; - int zero_padding = 0, precision_specified = 0, justify_left = 0; - int alternate_form = 0, force_sign = 0; - int space_for_positive = 1; /* If both the ' ' and '+' flags appear, - the ' ' flag should be ignored. */ - char length_modifier = '\0'; /* allowed values: \0, h, l, L */ - char tmp[32];/* temporary buffer for simple numeric->string conversion */ - - const char *str_arg; /* string address in case of string argument */ - size_t str_arg_l; /* natural field width of arg without padding - and sign */ - unsigned char uchar_arg; - /* unsigned char argument value - only defined for c conversion. - N.B. standard explicitly states the char argument for - the c conversion is unsigned */ - - size_t number_of_zeros_to_pad = 0; - /* number of zeros to be inserted for numeric conversions - as required by the precision or minimal field width */ - - size_t zero_padding_insertion_ind = 0; - /* index into tmp where zero padding is to be inserted */ - - char fmt_spec = '\0'; - /* current conversion specifier character */ - - starting_p = p; p++; /* skip '%' */ - /* parse flags */ - while (*p == '0' || *p == '-' || *p == '+' || - *p == ' ' || *p == '#' || *p == '\'') { - switch (*p) { - case '0': zero_padding = 1; break; - case '-': justify_left = 1; break; - case '+': force_sign = 1; space_for_positive = 0; break; - case ' ': force_sign = 1; - /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */ -#ifdef PERL_COMPATIBLE - /* ... but in Perl the last of ' ' and '+' applies */ - space_for_positive = 1; -#endif - break; - case '#': alternate_form = 1; break; - case '\'': break; - } - p++; - } - /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */ - - /* parse field width */ - if (*p == '*') { - int j; - p++; j = va_arg(ap, int); - if (j >= 0) min_field_width = j; - else { min_field_width = -j; justify_left = 1; } - } else if (isdigit((int)(*p))) { - /* size_t could be wider than unsigned int; - make sure we treat argument like common implementations do */ - unsigned int uj = *p++ - '0'; - while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); - min_field_width = uj; - } - /* parse precision */ - if (*p == '.') { - p++; precision_specified = 1; - if (*p == '*') { - int j = va_arg(ap, int); - p++; - if (j >= 0) precision = j; - else { - precision_specified = 0; precision = 0; - /* NOTE: - * Solaris 2.6 man page claims that in this case the precision - * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page - * claim that this case should be treated as unspecified precision, - * which is what we do here. - */ - } - } else if (isdigit((int)(*p))) { - /* size_t could be wider than unsigned int; - make sure we treat argument like common implementations do */ - unsigned int uj = *p++ - '0'; - while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); - precision = uj; - } - } - /* parse 'h', 'l' and 'll' length modifiers */ - if (*p == 'h' || *p == 'l') { - length_modifier = *p; p++; - if (length_modifier == 'l' && *p == 'l') { /* double l = long long */ -#ifdef SNPRINTF_LONGLONG_SUPPORT - length_modifier = '2'; /* double l encoded as '2' */ -#else - length_modifier = 'l'; /* treat it as a single 'l' */ -#endif - p++; - } - } - fmt_spec = *p; - /* common synonyms: */ - switch (fmt_spec) { - case 'i': fmt_spec = 'd'; break; - case 'D': fmt_spec = 'd'; length_modifier = 'l'; break; - case 'U': fmt_spec = 'u'; length_modifier = 'l'; break; - case 'O': fmt_spec = 'o'; length_modifier = 'l'; break; - default: break; - } - /* get parameter value, do initial processing */ - switch (fmt_spec) { - case '%': /* % behaves similar to 's' regarding flags and field widths */ - case 'c': /* c behaves similar to 's' regarding flags and field widths */ - case 's': - length_modifier = '\0'; /* wint_t and wchar_t not supported */ - /* the result of zero padding flag with non-numeric conversion specifier*/ - /* is undefined. Solaris and HPUX 10 does zero padding in this case, */ - /* Digital Unix and Linux does not. */ -#if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE) - zero_padding = 0; /* turn zero padding off for string conversions */ -#endif - str_arg_l = 1; - switch (fmt_spec) { - case '%': - str_arg = p; break; - case 'c': { - int j = va_arg(ap, int); - uchar_arg = (unsigned char) j; /* standard demands unsigned char */ - str_arg = (const char *) &uchar_arg; - break; - } - case 's': - str_arg = va_arg(ap, const char *); - if (!str_arg) str_arg_l = 0; - /* make sure not to address string beyond the specified precision !!! */ - else if (!precision_specified) str_arg_l = strlen(str_arg); - /* truncate string if necessary as requested by precision */ - else if (precision == 0) str_arg_l = 0; - else { - /* memchr on HP does not like n > 2^31 !!! */ - const char *q = memchr(str_arg, '\0', - precision <= 0x7fffffff ? precision : 0x7fffffff); - str_arg_l = !q ? precision : (q-str_arg); - } - break; - default: break; - } - break; - case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': { - /* NOTE: the u, o, x, X and p conversion specifiers imply - the value is unsigned; d implies a signed value */ - - int arg_sign = 0; - /* 0 if numeric argument is zero (or if pointer is NULL for 'p'), - +1 if greater than zero (or nonzero for unsigned arguments), - -1 if negative (unsigned argument is never negative) */ - - int int_arg = 0; unsigned int uint_arg = 0; - /* only defined for length modifier h, or for no length modifiers */ - - long int long_arg = 0; unsigned long int ulong_arg = 0; - /* only defined for length modifier l */ - - void *ptr_arg = NULL; - /* pointer argument value -only defined for p conversion */ - -#ifdef SNPRINTF_LONGLONG_SUPPORT - long long int long_long_arg = 0; - unsigned long long int ulong_long_arg = 0; - /* only defined for length modifier ll */ -#endif - if (fmt_spec == 'p') { - /* HPUX 10: An l, h, ll or L before any other conversion character - * (other than d, i, u, o, x, or X) is ignored. - * Digital Unix: - * not specified, but seems to behave as HPUX does. - * Solaris: If an h, l, or L appears before any other conversion - * specifier (other than d, i, u, o, x, or X), the behavior - * is undefined. (Actually %hp converts only 16-bits of address - * and %llp treats address as 64-bit data which is incompatible - * with (void *) argument on a 32-bit system). - */ -#ifdef SOLARIS_COMPATIBLE -# ifdef SOLARIS_BUG_COMPATIBLE - /* keep length modifiers even if it represents 'll' */ -# else - if (length_modifier == '2') length_modifier = '\0'; -# endif -#else - length_modifier = '\0'; -#endif - ptr_arg = va_arg(ap, void *); - if (ptr_arg != NULL) arg_sign = 1; - } else if (fmt_spec == 'd') { /* signed */ - switch (length_modifier) { - case '\0': - case 'h': - /* It is non-portable to specify a second argument of char or short - * to va_arg, because arguments seen by the called function - * are not char or short. C converts char and short arguments - * to int before passing them to a function. - */ - int_arg = va_arg(ap, int); - if (int_arg > 0) arg_sign = 1; - else if (int_arg < 0) arg_sign = -1; - break; - case 'l': - long_arg = va_arg(ap, long int); - if (long_arg > 0) arg_sign = 1; - else if (long_arg < 0) arg_sign = -1; - break; -#ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': - long_long_arg = va_arg(ap, long long int); - if (long_long_arg > 0) arg_sign = 1; - else if (long_long_arg < 0) arg_sign = -1; - break; -#endif - } - } else { /* unsigned */ - switch (length_modifier) { - case '\0': - case 'h': - uint_arg = va_arg(ap, unsigned int); - if (uint_arg) arg_sign = 1; - break; - case 'l': - ulong_arg = va_arg(ap, unsigned long int); - if (ulong_arg) arg_sign = 1; - break; -#ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': - ulong_long_arg = va_arg(ap, unsigned long long int); - if (ulong_long_arg) arg_sign = 1; - break; -#endif - } - } - str_arg = tmp; str_arg_l = 0; - /* NOTE: - * For d, i, u, o, x, and X conversions, if precision is specified, - * the '0' flag should be ignored. This is so with Solaris 2.6, - * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl. - */ -#ifndef PERL_COMPATIBLE - if (precision_specified) zero_padding = 0; -#endif - if (fmt_spec == 'd') { - if (force_sign && arg_sign >= 0) - tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; - /* leave negative numbers for sprintf to handle, - to avoid handling tricky cases like (short int)(-32768) */ -#ifdef LINUX_COMPATIBLE - } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) { - tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; -#endif - } else if (alternate_form) { - if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') ) - { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; } - /* alternate form should have no effect for p conversion, but ... */ -#ifdef HPUX_COMPATIBLE - else if (fmt_spec == 'p' - /* HPUX 10: for an alternate form of p conversion, - * a nonzero result is prefixed by 0x. */ -#ifndef HPUX_BUG_COMPATIBLE - /* Actually it uses 0x prefix even for a zero value. */ - && arg_sign != 0 -#endif - ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; } -#endif - } - zero_padding_insertion_ind = str_arg_l; - if (!precision_specified) precision = 1; /* default precision is 1 */ - if (precision == 0 && arg_sign == 0 -#if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE) - && fmt_spec != 'p' - /* HPUX 10 man page claims: With conversion character p the result of - * converting a zero value with a precision of zero is a null string. - * Actually HP returns all zeroes, and Linux returns "(nil)". */ -#endif - ) { - /* converted to null string */ - /* When zero value is formatted with an explicit precision 0, - the resulting formatted string is empty (d, i, u, o, x, X, p). */ - } else { - char f[5]; int f_l = 0; - f[f_l++] = '%'; /* construct a simple format string for sprintf */ - if (!length_modifier) { } - else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; } - else f[f_l++] = length_modifier; - f[f_l++] = fmt_spec; f[f_l++] = '\0'; - if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg); - else if (fmt_spec == 'd') { /* signed */ - switch (length_modifier) { - case '\0': - case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break; - case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break; -#ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break; -#endif - } - } else { /* unsigned */ - switch (length_modifier) { - case '\0': - case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break; - case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break; -#ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break; -#endif - } - } - /* include the optional minus sign and possible "0x" - in the region before the zero padding insertion point */ - if (zero_padding_insertion_ind < str_arg_l && - tmp[zero_padding_insertion_ind] == '-') { - zero_padding_insertion_ind++; - } - if (zero_padding_insertion_ind+1 < str_arg_l && - tmp[zero_padding_insertion_ind] == '0' && - (tmp[zero_padding_insertion_ind+1] == 'x' || - tmp[zero_padding_insertion_ind+1] == 'X') ) { - zero_padding_insertion_ind += 2; - } - } - { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind; - if (alternate_form && fmt_spec == 'o' -#ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */ - && (str_arg_l > 0) -#endif -#ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */ -#else - /* unless zero is already the first character */ - && !(zero_padding_insertion_ind < str_arg_l - && tmp[zero_padding_insertion_ind] == '0') -#endif - ) { /* assure leading zero for alternate-form octal numbers */ - if (!precision_specified || precision < num_of_digits+1) { - /* precision is increased to force the first character to be zero, - except if a zero value is formatted with an explicit precision - of zero */ - precision = num_of_digits+1; precision_specified = 1; - } - } - /* zero padding to specified precision? */ - if (num_of_digits < precision) - number_of_zeros_to_pad = precision - num_of_digits; - } - /* zero padding to specified minimal field width? */ - if (!justify_left && zero_padding) { - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) number_of_zeros_to_pad += n; - } - break; - } - default: /* unrecognized conversion specifier, keep format string as-is*/ - zero_padding = 0; /* turn zero padding off for non-numeric convers. */ -#ifndef DIGITAL_UNIX_COMPATIBLE - justify_left = 1; min_field_width = 0; /* reset flags */ -#endif -#if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE) - /* keep the entire format string unchanged */ - str_arg = starting_p; str_arg_l = p - starting_p; - /* well, not exactly so for Linux, which does something inbetween, - * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */ -#else - /* discard the unrecognized conversion, just keep * - * the unrecognized conversion character */ - str_arg = p; str_arg_l = 0; -#endif - if (*p) str_arg_l++; /* include invalid conversion specifier unchanged - if not at end-of-string */ - break; - } - if (*p) p++; /* step over the just processed conversion specifier */ - /* insert padding to the left as requested by min_field_width; - this does not include the zero padding in case of numerical conversions*/ - if (!justify_left) { /* left padding with blank or zero */ - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) { - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n)); - } - str_l += n; - } - } - /* zero padding as requested by the precision or by the minimal field width - * for numeric conversions required? */ - if (number_of_zeros_to_pad <= 0) { - /* will not copy first part of numeric right now, * - * force it to be copied later in its entirety */ - zero_padding_insertion_ind = 0; - } else { - /* insert first part of numerics (sign or '0x') before zero padding */ - int n = zero_padding_insertion_ind; - if (n > 0) { - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memcpy(str+str_l, str_arg, (n>avail?avail:n)); - } - str_l += n; - } - /* insert zero padding as requested by the precision or min field width */ - n = number_of_zeros_to_pad; - if (n > 0) { - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memset(str+str_l, '0', (n>avail?avail:n)); - } - str_l += n; - } - } - /* insert formatted string - * (or as-is conversion specifier for unknown conversions) */ - { int n = str_arg_l - zero_padding_insertion_ind; - if (n > 0) { - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind, - (n>avail?avail:n)); - } - str_l += n; - } - } - /* insert right padding */ - if (justify_left) { /* right blank padding to the field width */ - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) { - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memset(str+str_l, ' ', (n>avail?avail:n)); - } - str_l += n; - } - } - } - } -#if defined(NEED_SNPRINTF_ONLY) - va_end(ap); -#endif - if (str_m > 0) { /* make sure the string is null-terminated - even at the expense of overwriting the last character - (shouldn't happen, but just in case) */ - str[str_l <= str_m-1 ? str_l : str_m-1] = '\0'; - } - /* Return the number of characters formatted (excluding trailing null - * character), that is, the number of characters that would have been - * written to the buffer if it were large enough. - * - * The value of str_l should be returned, but str_l is of unsigned type - * size_t, and snprintf is int, possibly leading to an undetected - * integer overflow, resulting in a negative return value, which is illegal. - * Both XSH5 and ISO C99 (at least the draft) are silent on this issue. - * Should errno be set to EOVERFLOW and EOF returned in this case??? - */ - return (int) str_l; -} -#endif diff --git a/base/str_io.h b/base/str_io.h deleted file mode 100644 index 048d055f..00000000 --- a/base/str_io.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#ifndef STR_IO_H -#define STR_IO_H - -#include "MMBitmap.h" -#include "file_io.h" -#include - - -enum _MMBMPStringError { - kMMBMPStringGenericError = 0, - kMMBMPStringInvalidHeaderError, - kMMBMPStringDecodeError, - kMMBMPStringDecompressError, - kMMBMPStringSizeError, /* Size does not match header. */ - MMMBMPStringEncodeError, - kMMBMPStringCompressError -}; - -typedef MMIOError MMBMPStringError; - -/* Creates a 24-bit bitmap from a compressed, printable string. - * - * String should be in the format: "b[width],[height],[data]", - * where [width] and [height] are the image width & height, and [data] - * is the raw image data run through zlib_compress() and base64_encode(). - * - * Returns NULL on error; follows the Create Rule (that is, the caller is - * responsible for destroy'()ing object). - * If |error| is non-NULL, it will be set to the error code on return. - */ -MMBitmapRef createMMBitmapFromString(const uint8_t *buffer, size_t buflen, - MMBMPStringError *error); - -/* Inverse of createMMBitmapFromString(). - * - * Creates string in the format: "b[width],[height],[data]", where [width] and - * [height] are the image width & height, and [data] is the raw image data run - * through zlib_compress() and base64_encode(). - * - * Returns NULL on error, or new string on success (to be free'()d by caller). - * If |error| is non-NULL, it will be set to the error code on return. - */ -uint8_t *createStringFromMMBitmap(MMBitmapRef bitmap, MMBMPStringError *error); - -/* Returns description of given error code. - * Returned string is constant and hence should not be freed. */ -const char *MMBitmapStringErrorString(MMBMPStringError err); - -#endif /* STR_IO_H */ diff --git a/base/str_io_c.h b/base/str_io_c.h deleted file mode 100644 index fa80f8ef..00000000 --- a/base/str_io_c.h +++ /dev/null @@ -1,208 +0,0 @@ -#include "str_io.h" -#include "zlib_util_c.h" -#include "base64_c.h" -#include "snprintf_c.h" /* snprintf() */ -#include /* fputs() */ -#include /* isdigit() */ -#include /* atoi() */ -#include /* strlen() */ -#include - -#if defined(_MSC_VER) - #include "ms_stdbool.h" -#else - #include -#endif - -#define STR_BITS_PER_PIXEL 24 -#define STR_BYTES_PER_PIXEL ((STR_BITS_PER_PIXEL) / 8) - -#define MAX_DIMENSION_LEN 5 /* Maximum length for [width] or [height] - * in string. */ - -const char *MMBitmapStringErrorString(MMBMPStringError err) -{ - switch (err) { - case kMMBMPStringInvalidHeaderError: - return "Invalid header for string"; - case kMMBMPStringDecodeError: - return "Error decoding string"; - case kMMBMPStringDecompressError: - return "Error decompressing string"; - case kMMBMPStringSizeError: - return "String not of expected size"; - case MMMBMPStringEncodeError: - return "Error encoding string"; - case kMMBMPStringCompressError: - return "Error compressing string"; - default: - return NULL; - } -} - -/* Parses beginning of string in the form of "[width],[height],*". - * - * If successful, |width| and |height| are set to the appropropriate values, - * |len| is set to the length of [width] + the length of [height] + 2, - * and true is returned; otherwise, false is returned. - */ -static bool getSizeFromString(const uint8_t *buf, size_t buflen, - size_t *width, size_t *height, - size_t *len); - -MMBitmapRef createMMBitmapFromString(const uint8_t *buffer, size_t buflen, - MMBMPStringError *err) -{ - uint8_t *decoded, *decompressed; - size_t width, height; - size_t len, bytewidth; - - if (*buffer++ != 'b' || !getSizeFromString(buffer, --buflen, - &width, &height, &len)) { - if (err != NULL) *err = kMMBMPStringInvalidHeaderError; - return NULL; - } - buffer += len; - buflen -= len; - - decoded = base64decode(buffer, buflen, NULL); - if (decoded == NULL) { - if (err != NULL) *err = kMMBMPStringDecodeError; - return NULL; - } - - decompressed = zlib_decompress(decoded, &len); - free(decoded); - - if (decompressed == NULL) { - if (err != NULL) *err = kMMBMPStringDecompressError; - return NULL; - } - - bytewidth = width * STR_BYTES_PER_PIXEL; /* Note that bytewidth is NOT - * aligned to a padding. */ - if (height * bytewidth != len) { - if (err != NULL) *err = kMMBMPStringSizeError; - return NULL; - } - - return createMMBitmap(decompressed, width, height, - bytewidth, STR_BITS_PER_PIXEL, STR_BYTES_PER_PIXEL); -} - -/* Returns bitmap data suitable for encoding to a string; that is, 24-bit BGR - * bitmap with no padding and 3 bytes per pixel. - * - * Caller is responsible for free()'ing returned buffer. */ -static uint8_t *createRawBitmapData(MMBitmapRef bitmap); - -uint8_t *createStringFromMMBitmap(MMBitmapRef bitmap, MMBMPStringError *err) -{ - uint8_t *raw, *compressed; - uint8_t *ret, *encoded; - size_t len, retlen; - - assert(bitmap != NULL); - - raw = createRawBitmapData(bitmap); - if (raw == NULL) { - if (err != NULL) *err = kMMBMPStringGenericError; - return NULL; - } - - compressed = zlib_compress(raw, - bitmap->width * bitmap->height * - STR_BYTES_PER_PIXEL, - 9, &len); - free(raw); - if (compressed == NULL) { - if (err != NULL) *err = kMMBMPStringCompressError; - return NULL; - } - - encoded = base64encode(compressed, len - 1, &retlen); - free(compressed); - if (encoded == NULL) { - if (err != NULL) *err = MMMBMPStringEncodeError; - return NULL; - } - - retlen += 3 + (MAX_DIMENSION_LEN * 2); - ret = calloc(sizeof(char), (retlen + 1)); - snprintf((char *)ret, retlen, "b%lu,%lu,%s", (unsigned long)bitmap->width, - (unsigned long)bitmap->height, - encoded); - ret[retlen] = '\0'; - free(encoded); - return ret; -} - -static uint32_t parseDimension(const uint8_t *buf, size_t buflen, - size_t *numlen); - -static bool getSizeFromString(const uint8_t *buf, size_t buflen, - size_t *width, size_t *height, - size_t *len) -{ - size_t numlen; - assert(buf != NULL); - assert(width != NULL); - assert(height != NULL); - - if ((*width = parseDimension(buf, buflen, &numlen)) == 0) { - return false; - } - *len = numlen + 1; - - if ((*height = parseDimension(buf + *len, buflen, &numlen)) == 0) { - return false; - } - *len += numlen + 1; - - return true; -} - -/* Parses one dimension from string as described in getSizeFromString(). - * Returns dimension on success, or 0 on error. */ -static uint32_t parseDimension(const uint8_t *buf, - size_t buflen, size_t *numlen){ - char num[MAX_DIMENSION_LEN + 1]; - size_t i; - // ssize_t len; - // size_t len; - // uint8_t *len; - - assert(buf != NULL); - // assert(len != NULL); - for (i = 0; i < buflen && buf[i] != ',' && buf[i] != '\0'; ++i) { - if (!isdigit(buf[i]) || i > MAX_DIMENSION_LEN) return 0; - num[i] = buf[i]; - } - num[i] = '\0'; - *numlen = i; - - return (uint32_t)atoi(num); -} - -static uint8_t *createRawBitmapData(MMBitmapRef bitmap) -{ - uint8_t *raw = calloc(STR_BYTES_PER_PIXEL, bitmap->width * bitmap->height); - size_t y; - - for (y = 0; y < bitmap->height; ++y) { - /* No padding is added to string bitmaps. */ - const size_t rowOffset = y * bitmap->width * STR_BYTES_PER_PIXEL; - size_t x; - for (x = 0; x < bitmap->width; ++x) { - /* Copy in BGR format. */ - const size_t colOffset = x * STR_BYTES_PER_PIXEL; - uint8_t *dest = raw + rowOffset + colOffset; - MMRGBColor *srcColor = MMRGBColorRefAtPoint(bitmap, x, y); - dest[0] = srcColor->blue; - dest[1] = srcColor->green; - dest[2] = srcColor->red; - } - } - - return raw; -} diff --git a/base/types.h b/base/types.h index 4b88a1de..fc2d0a64 100644 --- a/base/types.h +++ b/base/types.h @@ -6,116 +6,63 @@ #include "inline_keywords.h" /* For H_INLINE */ #include #include +#include /* Some generic, cross-platform types. */ - -struct _MMPoint { - size_t x; - size_t y; -}; - -typedef struct _MMPoint MMPoint; +#ifdef RobotGo_64 + typedef int64_t intptr; + typedef uint64_t uintptr; +#else + typedef int32_t intptr; + typedef uint32_t uintptr; // Unsigned pointer integer +#endif struct _MMPointInt32 { int32_t x; int32_t y; }; - typedef struct _MMPointInt32 MMPointInt32; -struct _MMSize { - size_t width; - size_t height; -}; - -typedef struct _MMSize MMSize; - struct _MMSizeInt32 { int32_t w; int32_t h; }; - typedef struct _MMSizeInt32 MMSizeInt32; - -struct _MMRect { - MMPoint origin; - MMSize size; -}; - -typedef struct _MMRect MMRect; - struct _MMRectInt32 { MMPointInt32 origin; MMSizeInt32 size; }; - typedef struct _MMRectInt32 MMRectInt32; -H_INLINE MMPoint MMPointMake(size_t x, size_t y) -{ - MMPoint point; - point.x = x; - point.y = y; - return point; -} - -H_INLINE MMPointInt32 MMPointInt32Make(int32_t x, int32_t y) -{ +H_INLINE MMPointInt32 MMPointInt32Make(int32_t x, int32_t y) { MMPointInt32 point; point.x = x; point.y = y; return point; } -H_INLINE MMSize MMSizeMake(size_t width, size_t height) -{ - MMSize size; - size.width = width; - size.height = height; - return size; -} - -H_INLINE MMSizeInt32 MMSizeInt32Make(int32_t w, int32_t h) -{ +H_INLINE MMSizeInt32 MMSizeInt32Make(int32_t w, int32_t h) { MMSizeInt32 size; size.w = w; size.h = h; return size; } -H_INLINE MMRect MMRectMake(size_t x, size_t y, size_t width, size_t height) -{ - MMRect rect; - rect.origin = MMPointMake(x, y); - rect.size = MMSizeMake(width, height); - return rect; -} - -H_INLINE MMRectInt32 MMRectInt32Make(int32_t x, int32_t y, int32_t w, int32_t h) -{ +H_INLINE MMRectInt32 MMRectInt32Make(int32_t x, int32_t y, int32_t w, int32_t h) { MMRectInt32 rect; rect.origin = MMPointInt32Make(x, y); rect.size = MMSizeInt32Make(w, h); return rect; } -// -#define MMPointZero MMPointMake(0, 0) +#define MMPointZero MMPointInt32Make(0, 0) #if defined(IS_MACOSX) - -#define CGPointFromMMPoint(p) CGPointMake((CGFloat)(p).x, (CGFloat)(p).y) -#define MMPointFromCGPoint(p) MMPointMake((size_t)(p).x, (size_t)(p).y) - -#define CGPointFromMMPointInt32(p) CGPointMake((CGFloat)(p).x, (CGFloat)(p).y) -#define MMPointInt32FromCGPoint(p) MMPointInt32Make((int32_t)(p).x, (int32_t)(p).y) - + #define CGPointFromMMPointInt32(p) CGPointMake((CGFloat)(p).x, (CGFloat)(p).y) + #define MMPointInt32FromCGPoint(p) MMPointInt32Make((int32_t)(p).x, (int32_t)(p).y) #elif defined(IS_WINDOWS) - -#define MMPointFromPOINT(p) MMPointMake((size_t)p.x, (size_t)p.y) -#define MMPointInt32FromPOINT(p) MMPointInt32Make((int32_t)p.x, (int32_t)p.y) - + #define MMPointInt32FromPOINT(p) MMPointInt32Make((int32_t)p.x, (int32_t)p.y) #endif #endif /* TYPES_H */ diff --git a/base/uthash.h b/base/uthash.h deleted file mode 100644 index 1ea0fea1..00000000 --- a/base/uthash.h +++ /dev/null @@ -1,929 +0,0 @@ -/* - * Copyright (c) 2003-2009, Troy D. Hanson http://uthash.sourceforge.net - * 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. - * - * 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 THE COPYRIGHT OWNER - * OR CONTRIBUTORS 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. - */ - -#pragma once -#ifndef UTHASH_H -#define UTHASH_H - -#include /* memcmp, strlen */ -#include /* ptrdiff_t */ -#include - - -#define UTHASH_VERSION 1.8 - -/* C++ requires extra stringent casting */ -#if defined __cplusplus -#define TYPEOF(x) (typeof(x)) -#else -#define TYPEOF(x) -#endif - - -#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ -#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ -#define uthash_free(ptr) free(ptr) /* free fcn */ - -#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ -#define uthash_expand_fyi(tbl) /* can be defined to log expands */ - -/* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ -#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ - -/* calculate the element whose hash handle address is hhe */ -#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)hhp) - (tbl)->hho)) - -#define HASH_FIND(hh,head,keyptr,keylen,out) \ -do { \ - unsigned _hf_bkt,_hf_hashv; \ - out=TYPEOF(out)NULL; \ - if (head) { \ - HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ - if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ - HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ - keyptr,keylen,out); \ - } \ - } \ -} while (0) - -#if defined(HASH_BLOOM) -#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) -#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) -#define HASH_BLOOM_MAKE(tbl) \ -do { \ - (tbl)->bloom_nbits = HASH_BLOOM; \ - (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ - if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ - memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ - (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ -} while (0); - -#define HASH_BLOOM_FREE(tbl) \ -do { \ - uthash_free((tbl)->bloom_bv); \ -} while (0); - -#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) -#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) - -#define HASH_BLOOM_ADD(tbl,hashv) \ - HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) - -#define HASH_BLOOM_TEST(tbl,hashv) \ - HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) - -#else -#define HASH_BLOOM_MAKE(tbl) -#define HASH_BLOOM_FREE(tbl) -#define HASH_BLOOM_ADD(tbl,hashv) -#define HASH_BLOOM_TEST(tbl,hashv) (1) -#endif - -#define HASH_MAKE_TABLE(hh,head) \ -do { \ - (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ - sizeof(UT_hash_table)); \ - if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ - (head)->hh.tbl->tail = &((head)->hh); \ - (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ - (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ - (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ - (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl->buckets, 0, \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - HASH_BLOOM_MAKE((head)->hh.tbl); \ - (head)->hh.tbl->signature = HASH_SIGNATURE; \ -} while(0) - -#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ - HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) - -#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ -do { \ - unsigned _ha_bkt; \ - (add)->hh.next = NULL; \ - (add)->hh.key = (char*)keyptr; \ - (add)->hh.keylen = keylen_in; \ - if (!(head)) { \ - head = (add); \ - (head)->hh.prev = NULL; \ - HASH_MAKE_TABLE(hh,head); \ - } else { \ - (head)->hh.tbl->tail->next = (add); \ - (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ - (head)->hh.tbl->tail = &((add)->hh); \ - } \ - (head)->hh.tbl->num_items++; \ - (add)->hh.tbl = (head)->hh.tbl; \ - HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ - (add)->hh.hashv, _ha_bkt); \ - HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ - HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ - HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ - HASH_FSCK(hh,head); \ -} while(0) - -#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ -do { \ - bkt = ((hashv) & ((num_bkts) - 1)); \ -} while(0) - -/* delete "delptr" from the hash table. - * "the usual" patch-up process for the app-order doubly-linked-list. - * The use of _hd_hh_del below deserves special explanation. - * These used to be expressed using (delptr) but that led to a bug - * if someone used the same symbol for the head and deletee, like - * HASH_DELETE(hh,users,users); - * We want that to work, but by changing the head (users) below - * we were forfeiting our ability to further refer to the deletee (users) - * in the patch-up process. Solution: use scratch space in the table to - * copy the deletee pointer, then the latter references are via that - * scratch pointer rather than through the repointed (users) symbol. - */ -#define HASH_DELETE(hh,head,delptr) \ -do { \ - unsigned _hd_bkt; \ - struct UT_hash_handle *_hd_hh_del; \ - if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ - uthash_free((head)->hh.tbl->buckets ); \ - HASH_BLOOM_FREE((head)->hh.tbl); \ - uthash_free((head)->hh.tbl); \ - head = NULL; \ - } else { \ - _hd_hh_del = &((delptr)->hh); \ - if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ - (head)->hh.tbl->tail = \ - (UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho); \ - } \ - if ((delptr)->hh.prev) { \ - ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ - } else { \ - head = TYPEOF(head)((delptr)->hh.next); \ - } \ - if (_hd_hh_del->next) { \ - ((UT_hash_handle*)((char*)_hd_hh_del->next + \ - (head)->hh.tbl->hho))->prev = \ - _hd_hh_del->prev; \ - } \ - HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ - HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ - (head)->hh.tbl->num_items--; \ - } \ - HASH_FSCK(hh,head); \ -} while (0) - - -/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ -#define HASH_FIND_STR(head,findstr,out) \ - HASH_FIND(hh,head,findstr,strlen(findstr),out) -#define HASH_ADD_STR(head,strfield,add) \ - HASH_ADD(hh,head,strfield,strlen(add->strfield),add) -#define HASH_FIND_INT(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(int),out) -#define HASH_ADD_INT(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(int),add) -#define HASH_DEL(head,delptr) \ - HASH_DELETE(hh,head,delptr) - -/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. - * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. - */ -#if defined(HASH_DEBUG) -#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) -#define HASH_FSCK(hh,head) \ -do { \ - unsigned _bkt_i; \ - unsigned _count, _bkt_count; \ - char *_prev; \ - struct UT_hash_handle *_thh; \ - if (head) { \ - _count = 0; \ - for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ - _bkt_count = 0; \ - _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ - _prev = NULL; \ - while (_thh) { \ - if (_prev != (char*)(_thh->hh_prev)) { \ - HASH_OOPS("invalid hh_prev %p, actual %p\n", \ - _thh->hh_prev, _prev ); \ - } \ - _bkt_count++; \ - _prev = (char*)(_thh); \ - _thh = _thh->hh_next; \ - } \ - _count += _bkt_count; \ - if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ - HASH_OOPS("invalid bucket count %d, actual %d\n", \ - (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ - } \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid hh item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - /* traverse hh in app order; check next/prev integrity, count */ \ - _count = 0; \ - _prev = NULL; \ - _thh = &(head)->hh; \ - while (_thh) { \ - _count++; \ - if (_prev !=(char*)(_thh->prev)) { \ - HASH_OOPS("invalid prev %p, actual %p\n", \ - _thh->prev, _prev ); \ - } \ - _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ - _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ - (head)->hh.tbl->hho) : NULL ); \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid app item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - } \ -} while (0) -#else -#define HASH_FSCK(hh,head) -#endif - -/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to - * the descriptor to which this macro is defined for tuning the hash function. - * The app can #include to get the prototype for write(2). */ -#if defined(HASH_EMIT_KEYS) -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ -do { \ - unsigned _klen = fieldlen; \ - write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ - write(HASH_EMIT_KEYS, keyptr, fieldlen); \ -} while (0) -#else -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) -#endif - -/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ -#if defined(HASH_FUNCTION) -#define HASH_FCN HASH_FUNCTION -#else -#define HASH_FCN HASH_JEN -#endif - -/* The Bernstein hash function, used in Perl prior to v5.6 */ -#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hb_keylen=keylen; \ - char *_hb_key=(char*)key; \ - (hashv) = 0; \ - while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ - bkt = (hashv) & (num_bkts-1); \ -} while (0) - - -/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at - * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ -#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _sx_i; \ - char *_hs_key=(char*)key; \ - hashv = 0; \ - for(_sx_i=0; _sx_i < keylen; _sx_i++) \ - hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ - bkt = hashv & (num_bkts-1); \ -} while (0) - -#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _fn_i; \ - char *_hf_key=(char*)key; \ - hashv = 2166136261UL; \ - for(_fn_i=0; _fn_i < keylen; _fn_i++) \ - hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _ho_i; \ - char *_ho_key=(char*)key; \ - hashv = 0; \ - for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ - hashv += _ho_key[_ho_i]; \ - hashv += (hashv << 10); \ - hashv ^= (hashv >> 6); \ - } \ - hashv += (hashv << 3); \ - hashv ^= (hashv >> 11); \ - hashv += (hashv << 15); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -#define HASH_JEN_MIX(a,b,c) \ -do { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( b >> 13 ); \ - a -= b; a -= c; a ^= ( c >> 12 ); \ - b -= c; b -= a; b ^= ( a << 16 ); \ - c -= a; c -= b; c ^= ( b >> 5 ); \ - a -= b; a -= c; a ^= ( c >> 3 ); \ - b -= c; b -= a; b ^= ( a << 10 ); \ - c -= a; c -= b; c ^= ( b >> 15 ); \ -} while (0) - -#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hj_i,_hj_j,_hj_k; \ - char *_hj_key=(char*)key; \ - hashv = 0xfeedbeef; \ - _hj_i = _hj_j = 0x9e3779b9; \ - _hj_k = keylen; \ - while (_hj_k >= 12) { \ - _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ - + ( (unsigned)_hj_key[2] << 16 ) \ - + ( (unsigned)_hj_key[3] << 24 ) ); \ - _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ - + ( (unsigned)_hj_key[6] << 16 ) \ - + ( (unsigned)_hj_key[7] << 24 ) ); \ - hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ - + ( (unsigned)_hj_key[10] << 16 ) \ - + ( (unsigned)_hj_key[11] << 24 ) ); \ - \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - \ - _hj_key += 12; \ - _hj_k -= 12; \ - } \ - hashv += keylen; \ - switch ( _hj_k ) { \ - case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ - case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ - case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ - case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ - case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ - case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ - case 5: _hj_j += _hj_key[4]; \ - case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ - case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ - case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ - case 1: _hj_i += _hj_key[0]; \ - } \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* The Paul Hsieh hash function */ -#undef get16bits -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) -#endif - -#if !defined (get16bits) -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ - +(uint32_t)(((const uint8_t *)(d))[0]) ) -#endif -#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ -do { \ - char *_sfh_key=(char*)key; \ - uint32_t _sfh_tmp, _sfh_len = keylen; \ - \ - int _sfh_rem = _sfh_len & 3; \ - _sfh_len >>= 2; \ - hashv = 0xcafebabe; \ - \ - /* Main loop */ \ - for (;_sfh_len > 0; _sfh_len--) { \ - hashv += get16bits (_sfh_key); \ - _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ - hashv = (hashv << 16) ^ _sfh_tmp; \ - _sfh_key += 2*sizeof (uint16_t); \ - hashv += hashv >> 11; \ - } \ - \ - /* Handle end cases */ \ - switch (_sfh_rem) { \ - case 3: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 16; \ - hashv ^= _sfh_key[sizeof (uint16_t)] << 18; \ - hashv += hashv >> 11; \ - break; \ - case 2: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 11; \ - hashv += hashv >> 17; \ - break; \ - case 1: hashv += *_sfh_key; \ - hashv ^= hashv << 10; \ - hashv += hashv >> 1; \ - } \ - \ - /* Force "avalanching" of final 127 bits */ \ - hashv ^= hashv << 3; \ - hashv += hashv >> 5; \ - hashv ^= hashv << 4; \ - hashv += hashv >> 17; \ - hashv ^= hashv << 25; \ - hashv += hashv >> 6; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -#if defined(HASH_USING_NO_STRICT_ALIASING) -/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads. - * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. - * So MurmurHash comes in two versions, the faster unaligned one and the slower - * aligned one. We only use the faster one on CPU's where we know it's safe. - * - * Note the preprocessor built-in defines can be emitted using: - * - * gcc -m64 -dM -E - < /dev/null (on gcc) - * cc -## a.c (where a.c is a simple test file) (Sun Studio) - */ -#if (defined(__i386__) || defined(__x86_64__)) -#define HASH_MUR HASH_MUR_UNALIGNED -#else -#define HASH_MUR HASH_MUR_ALIGNED -#endif - -/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */ -#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const unsigned int _mur_m = 0x5bd1e995; \ - const int _mur_r = 24; \ - hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)key; \ - uint32_t _mur_tmp, _mur_len = keylen; \ - \ - for (;_mur_len >= 4; _mur_len-=4) { \ - _mur_tmp = *(uint32_t *)_mur_key; \ - _mur_tmp *= _mur_m; \ - _mur_tmp ^= _mur_tmp >> _mur_r; \ - _mur_tmp *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_tmp; \ - _mur_key += 4; \ - } \ - \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - }; \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */ -#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const unsigned int _mur_m = 0x5bd1e995; \ - const int _mur_r = 24; \ - hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)key; \ - uint32_t _mur_len = keylen; \ - int _mur_align = (int)_mur_key & 3; \ - \ - if (_mur_align && (_mur_len >= 4)) { \ - unsigned _mur_t = 0, _mur_d = 0; \ - switch(_mur_align) { \ - case 1: _mur_t |= _mur_key[2] << 16; \ - case 2: _mur_t |= _mur_key[1] << 8; \ - case 3: _mur_t |= _mur_key[0]; \ - } \ - _mur_t <<= (8 * _mur_align); \ - _mur_key += 4-_mur_align; \ - _mur_len -= 4-_mur_align; \ - int _mur_sl = 8 * (4-_mur_align); \ - int _mur_sr = 8 * _mur_align; \ - \ - for (;_mur_len >= 4; _mur_len-=4) { \ - _mur_d = *(unsigned *)_mur_key; \ - _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - unsigned _mur_k = _mur_t; \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_t = _mur_d; \ - _mur_key += 4; \ - } \ - _mur_d = 0; \ - if(_mur_len >= _mur_align) { \ - switch(_mur_align) { \ - case 3: _mur_d |= _mur_key[2] << 16; \ - case 2: _mur_d |= _mur_key[1] << 8; \ - case 1: _mur_d |= _mur_key[0]; \ - } \ - unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_k += _mur_align; \ - _mur_len -= _mur_align; \ - \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - } \ - } else { \ - switch(_mur_len) \ - { \ - case 3: _mur_d ^= _mur_key[2] << 16; \ - case 2: _mur_d ^= _mur_key[1] << 8; \ - case 1: _mur_d ^= _mur_key[0]; \ - case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - hashv *= _mur_m; \ - } \ - } \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - } else { \ - for (;_mur_len >= 4; _mur_len-=4) { \ - unsigned _mur_k = *(unsigned*)_mur_key; \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_key += 4; \ - } \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - } \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - } \ - bkt = hashv & (num_bkts-1); \ -} while(0) -#endif /* HASH_USING_NO_STRICT_ALIASING */ - -/* key comparison function; return 0 if keys equal */ -#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) - -/* iterate over items in a known bucket to find desired item */ -#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ -out = TYPEOF(out)((head.hh_head) ? ELMT_FROM_HH(tbl,head.hh_head) : NULL); \ -while (out) { \ - if (out->hh.keylen == keylen_in) { \ - if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ - } \ - out= TYPEOF(out)((out->hh.hh_next) ? \ - ELMT_FROM_HH(tbl,out->hh.hh_next) : NULL); \ -} - -/* add an item to a bucket */ -#define HASH_ADD_TO_BKT(head,addhh) \ -do { \ - head.count++; \ - (addhh)->hh_next = head.hh_head; \ - (addhh)->hh_prev = NULL; \ - if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ - (head).hh_head=addhh; \ - if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ - && (addhh)->tbl->noexpand != 1) { \ - HASH_EXPAND_BUCKETS((addhh)->tbl); \ - } \ -} while(0) - -/* remove an item from a given bucket */ -#define HASH_DEL_IN_BKT(hh,head,hh_del) \ - (head).count--; \ - if ((head).hh_head == hh_del) { \ - (head).hh_head = hh_del->hh_next; \ - } \ - if (hh_del->hh_prev) { \ - hh_del->hh_prev->hh_next = hh_del->hh_next; \ - } \ - if (hh_del->hh_next) { \ - hh_del->hh_next->hh_prev = hh_del->hh_prev; \ - } - -/* Bucket expansion has the effect of doubling the number of buckets - * and redistributing the items into the new buckets. Ideally the - * items will distribute more or less evenly into the new buckets - * (the extent to which this is true is a measure of the quality of - * the hash function as it applies to the key domain). - * - * With the items distributed into more buckets, the chain length - * (item count) in each bucket is reduced. Thus by expanding buckets - * the hash keeps a bound on the chain length. This bounded chain - * length is the essence of how a hash provides constant time lookup. - * - * The calculation of tbl->ideal_chain_maxlen below deserves some - * explanation. First, keep in mind that we're calculating the ideal - * maximum chain length based on the *new* (doubled) bucket count. - * In fractions this is just n/b (n=number of items,b=new num buckets). - * Since the ideal chain length is an integer, we want to calculate - * ceil(n/b). We don't depend on floating point arithmetic in this - * hash, so to calculate ceil(n/b) with integers we could write - * - * ceil(n/b) = (n/b) + ((n%b)?1:0) - * - * and in fact a previous version of this hash did just that. - * But now we have improved things a bit by recognizing that b is - * always a power of two. We keep its base 2 log handy (call it lb), - * so now we can write this with a bit shift and logical AND: - * - * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) - * - */ -#define HASH_EXPAND_BUCKETS(tbl) \ -do { \ - unsigned _he_bkt; \ - unsigned _he_bkt_i; \ - struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ - UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ - _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ - memset(_he_new_buckets, 0, \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - tbl->ideal_chain_maxlen = \ - (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ - ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ - tbl->nonideal_items = 0; \ - for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ - { \ - _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ - while (_he_thh) { \ - _he_hh_nxt = _he_thh->hh_next; \ - HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ - _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ - if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ - tbl->nonideal_items++; \ - _he_newbkt->expand_mult = _he_newbkt->count / \ - tbl->ideal_chain_maxlen; \ - } \ - _he_thh->hh_prev = NULL; \ - _he_thh->hh_next = _he_newbkt->hh_head; \ - if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ - _he_thh; \ - _he_newbkt->hh_head = _he_thh; \ - _he_thh = _he_hh_nxt; \ - } \ - } \ - tbl->num_buckets *= 2; \ - tbl->log2_num_buckets++; \ - uthash_free( tbl->buckets ); \ - tbl->buckets = _he_new_buckets; \ - tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ - (tbl->ineff_expands+1) : 0; \ - if (tbl->ineff_expands > 1) { \ - tbl->noexpand=1; \ - uthash_noexpand_fyi(tbl); \ - } \ - uthash_expand_fyi(tbl); \ -} while(0) - - -/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ -/* Note that HASH_SORT assumes the hash handle name to be hh. - * HASH_SRT was added to allow the hash handle name to be passed in. */ -#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) -#define HASH_SRT(hh,head,cmpfcn) \ -do { \ - unsigned _hs_i; \ - unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ - struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ - if (head) { \ - _hs_insize = 1; \ - _hs_looping = 1; \ - _hs_list = &((head)->hh); \ - while (_hs_looping) { \ - _hs_p = _hs_list; \ - _hs_list = NULL; \ - _hs_tail = NULL; \ - _hs_nmerges = 0; \ - while (_hs_p) { \ - _hs_nmerges++; \ - _hs_q = _hs_p; \ - _hs_psize = 0; \ - for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ - _hs_psize++; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - if (! (_hs_q) ) break; \ - } \ - _hs_qsize = _hs_insize; \ - while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ - if (_hs_psize == 0) { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else if (( \ - cmpfcn(TYPEOF(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ - TYPEOF(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ - ) <= 0) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } \ - if ( _hs_tail ) { \ - _hs_tail->next = ((_hs_e) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ - } else { \ - _hs_list = _hs_e; \ - } \ - _hs_e->prev = ((_hs_tail) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ - _hs_tail = _hs_e; \ - } \ - _hs_p = _hs_q; \ - } \ - _hs_tail->next = NULL; \ - if ( _hs_nmerges <= 1 ) { \ - _hs_looping=0; \ - (head)->hh.tbl->tail = _hs_tail; \ - (head) = TYPEOF(head)ELMT_FROM_HH((head)->hh.tbl, _hs_list); \ - } \ - _hs_insize *= 2; \ - } \ - HASH_FSCK(hh,head); \ - } \ -} while (0) - -/* This function selects items from one hash into another hash. - * The end result is that the selected items have dual presence - * in both hashes. There is no copy of the items made; rather - * they are added into the new hash through a secondary hash - * hash handle that must be present in the structure. */ -#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ -do { \ - unsigned _src_bkt, _dst_bkt; \ - void *_last_elt=NULL, *_elt; \ - UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ - ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ - if (src) { \ - for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ - for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ - _src_hh; \ - _src_hh = _src_hh->hh_next) { \ - _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ - if (cond(_elt)) { \ - _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ - _dst_hh->key = _src_hh->key; \ - _dst_hh->keylen = _src_hh->keylen; \ - _dst_hh->hashv = _src_hh->hashv; \ - _dst_hh->prev = _last_elt; \ - _dst_hh->next = NULL; \ - if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ - if (!dst) { \ - dst = TYPEOF(dst)_elt; \ - HASH_MAKE_TABLE(hh_dst,dst); \ - } else { \ - _dst_hh->tbl = (dst)->hh_dst.tbl; \ - } \ - HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ - HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ - (dst)->hh_dst.tbl->num_items++; \ - _last_elt = _elt; \ - _last_elt_hh = _dst_hh; \ - } \ - } \ - } \ - } \ - HASH_FSCK(hh_dst,dst); \ -} while (0) - -#define HASH_CLEAR(hh,head) \ -do { \ - if (head) { \ - uthash_free((head)->hh.tbl->buckets ); \ - uthash_free((head)->hh.tbl); \ - (head)=NULL; \ - } \ -} while(0) - -/* obtain a count of items in the hash */ -#define HASH_COUNT(head) HASH_CNT(hh,head) -#define HASH_CNT(hh,head) (head?(head->hh.tbl->num_items):0) - -typedef struct UT_hash_bucket { - struct UT_hash_handle *hh_head; - unsigned count; - - /* expand_mult is normally set to 0. In this situation, the max chain length - * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If - * the bucket's chain exceeds this length, bucket expansion is triggered). - * However, setting expand_mult to a non-zero value delays bucket expansion - * (that would be triggered by additions to this particular bucket) - * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. - * (The multiplier is simply expand_mult+1). The whole idea of this - * multiplier is to reduce bucket expansions, since they are expensive, in - * situations where we know that a particular bucket tends to be overused. - * It is better to let its chain length grow to a longer yet-still-bounded - * value, than to do an O(n) bucket expansion too often. - */ - unsigned expand_mult; - -} UT_hash_bucket; - -/* random signature used only to find hash tables in external analysis */ -#define HASH_SIGNATURE 0xa0111fe1 -#define HASH_BLOOM_SIGNATURE 0xb12220f2 - -typedef struct UT_hash_table { - UT_hash_bucket *buckets; - unsigned num_buckets, log2_num_buckets; - unsigned num_items; - struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ - ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ - - /* in an ideal situation (all buckets used equally), no bucket would have - * more than ceil(#items/#buckets) items. that's the ideal chain length. */ - unsigned ideal_chain_maxlen; - - /* nonideal_items is the number of items in the hash whose chain position - * exceeds the ideal chain maxlen. these items pay the penalty for an uneven - * hash distribution; reaching them in a chain traversal takes >ideal steps */ - unsigned nonideal_items; - - /* ineffective expands occur when a bucket doubling was performed, but - * afterward, more than half the items in the hash had nonideal chain - * positions. If this happens on two consecutive expansions we inhibit any - * further expansion, as it's not helping; this happens when the hash - * function isn't a good fit for the key domain. When expansion is inhibited - * the hash will still work, albeit no longer in constant time. */ - unsigned ineff_expands, noexpand; - - uint32_t signature; /* used only to find hash tables in external analysis */ -#if defined(HASH_BLOOM) - uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ - uint8_t *bloom_bv; - char bloom_nbits; -#endif - -} UT_hash_table; - -typedef struct UT_hash_handle { - struct UT_hash_table *tbl; - void *prev; /* prev element in app order */ - void *next; /* next element in app order */ - struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ - struct UT_hash_handle *hh_next; /* next hh in bucket order */ - void *key; /* ptr to enclosing struct's key */ - unsigned keylen; /* enclosing struct's key len */ - unsigned hashv; /* result of hash-fcn(key) */ -} UT_hash_handle; - -#endif /* UTHASH_H */ diff --git a/base/xdisplay.h b/base/xdisplay.h deleted file mode 100644 index 3c8663c2..00000000 --- a/base/xdisplay.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#ifndef XDISPLAY_H -#define XDISPLAY_H - -#include - -/* Returns the main display, closed either on exit or when closeMainDisplay() - * is invoked. This removes a bit of the overhead of calling XOpenDisplay() & - * XCloseDisplay() everytime the main display needs to be used. - * - * Note that this is almost certainly not thread safe. */ -Display *XGetMainDisplay(void); - -/* Closes the main display if it is open, or does nothing if not. */ -void XCloseMainDisplay(void); - -#ifdef __cplusplus -extern "C" -{ -#endif - -char *getXDisplay(void); -void setXDisplay(char *name); - -#ifdef __cplusplus -} -#endif - -#endif /* XDISPLAY_H */ diff --git a/base/xdisplay_c.h b/base/xdisplay_c.h index c6874f3a..0c0dedb6 100644 --- a/base/xdisplay_c.h +++ b/base/xdisplay_c.h @@ -1,14 +1,21 @@ -#include "xdisplay.h" #include /* For fputs() */ #include /* For atexit() */ +#include static Display *mainDisplay = NULL; static int registered = 0; -static char *displayName = ":0.0"; + +static char *displayName = NULL; static int hasDisplayNameChanged = 0; -Display *XGetMainDisplay(void) -{ +void XCloseMainDisplay(void) { + if (mainDisplay != NULL) { + XCloseDisplay(mainDisplay); + mainDisplay = NULL; + } +} + +Display *XGetMainDisplay(void) { /* Close the display if displayName has changed */ if (hasDisplayNameChanged) { XCloseMainDisplay(); @@ -20,10 +27,15 @@ Display *XGetMainDisplay(void) mainDisplay = XOpenDisplay(displayName); /* Then try using environment variable DISPLAY */ - if (mainDisplay == NULL) { + if (mainDisplay == NULL && displayName != NULL) { mainDisplay = XOpenDisplay(NULL); } + /* Fall back to the most likely :0.0*/ + if (mainDisplay == NULL) { + mainDisplay = XOpenDisplay(":0.0"); + } + if (mainDisplay == NULL) { fputs("Could not open main display\n", stderr); } else if (!registered) { @@ -35,22 +47,11 @@ Display *XGetMainDisplay(void) return mainDisplay; } -void XCloseMainDisplay(void) -{ - if (mainDisplay != NULL) { - XCloseDisplay(mainDisplay); - mainDisplay = NULL; - } -} - -void setXDisplay(char *name) -{ +void setXDisplay(char *name) { displayName = strdup(name); hasDisplayNameChanged = 1; } -char *getXDisplay(void) -{ +char *getXDisplay(void) { return displayName; } - diff --git a/base/zlib_util.h b/base/zlib_util.h deleted file mode 100644 index b0cee028..00000000 --- a/base/zlib_util.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#ifndef ZLIB_UTIL_H -#define ZLIB_UTIL_H - -#include - -#if defined(_MSC_VER) - #include "ms_stdint.h" -#else - #include -#endif - -/* Attempts to decompress given deflated NUL-terminated buffer. - * - * If successful and |len| is not NULL, |len| will be set to the number of - * bytes in the returned buffer. - * Returns new string to be free()'d by caller, or NULL on error. */ -uint8_t *zlib_decompress(const uint8_t *buf, size_t *len); - -/* Attempt to compress given buffer. - * - * The compression level is passed directly to zlib: it must between 0 and 9, - * where 1 gives best speed, 9 gives best compression, and 0 gives no - * compression at all. - * - * If successful and |len| is not NULL, |len| will be set to the number of - * bytes in the returned buffer. - * Returns new string to be free()'d by caller, or NULL on error. */ -uint8_t *zlib_compress(const uint8_t *buf, const size_t buflen, int level, - size_t *len); - -#endif /* ZLIB_UTIL_H */ diff --git a/base/zlib_util_c.h b/base/zlib_util_c.h deleted file mode 100644 index 101cc9c5..00000000 --- a/base/zlib_util_c.h +++ /dev/null @@ -1,98 +0,0 @@ -#include "zlib_util.h" -#include -#include /* fprintf() */ -#include /* malloc() */ -#include - -#define ZLIB_CHUNK (16 * 1024) - -uint8_t *zlib_decompress(const uint8_t *buf, size_t *len){ - size_t output_size = ZLIB_CHUNK; - uint8_t *output = malloc(output_size); - int err; - z_stream zst; - - /* Sanity check */ - if (output == NULL) return NULL; - assert(buf != NULL); - - /* Set inflate state */ - zst.zalloc = Z_NULL; - zst.zfree = Z_NULL; - zst.opaque = Z_NULL; - zst.next_out = (Byte *)output; - zst.next_in = (Byte *)buf; - zst.avail_out = ZLIB_CHUNK; - - if (inflateInit(&zst) != Z_OK) goto error; - - /* Decompress input buffer */ - do { - if ((err = inflate(&zst, Z_NO_FLUSH)) == Z_OK) { /* Need more memory */ - zst.avail_out = (uInt)output_size; - - /* Double size each time to avoid calls to realloc() */ - output_size <<= 1; - output = realloc(output, output_size + 1); - if (output == NULL) return NULL; - - zst.next_out = (Byte *)(output + zst.avail_out); - } else if (err != Z_STREAM_END) { /* Error decompressing */ - if (zst.msg != NULL) { - fprintf(stderr, "Could not decompress data: %s\n", zst.msg); - } - inflateEnd(&zst); - goto error; - } - } while (err != Z_STREAM_END); - - if (len != NULL) *len = zst.total_out; - if (inflateEnd(&zst) != Z_OK) goto error; - return output; /* To be free()'d by caller */ - -error: - if (output != NULL) free(output); - return NULL; -} - -uint8_t *zlib_compress(const uint8_t *buf, const size_t buflen, int level, - size_t *len) -{ - z_stream zst; - uint8_t *output = NULL; - - /* Sanity check */ - assert(buf != NULL); - assert(len != NULL); - assert(level <= 9 && level >= 0); - - zst.avail_out = (uInt)((buflen + (buflen / 10)) + 12); - output = malloc(zst.avail_out); - if (output == NULL) return NULL; - - /* Set deflate state */ - zst.zalloc = Z_NULL; - zst.zfree = Z_NULL; - zst.next_out = (Byte *)output; - zst.next_in = (Byte *)buf; - zst.avail_in = (uInt)buflen; - - if (deflateInit(&zst, level) != Z_OK) goto error; - - /* Compress input buffer */ - if (deflate(&zst, Z_FINISH) != Z_STREAM_END) { - if (zst.msg != NULL) { - fprintf(stderr, "Could not compress data: %s\n", zst.msg); - } - deflateEnd(&zst); - goto error; - } - - if (len != NULL) *len = zst.total_out; - if (deflateEnd(&zst) != Z_OK) goto error; - return output; /* To be free()'d by caller */ - -error: - if (output != NULL) free(output); - return NULL; -} diff --git a/bitmap/bitmap_class.h b/bitmap/bitmap_class.h deleted file mode 100644 index 1f7f9c0c..00000000 --- a/bitmap/bitmap_class.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -// #ifndef BITMAP_CLASS_H -// #define BITMAP_CLASS_H - -#include "../base/MMBitmap.h" - -/* This file defines the class "Bitmap" for dealing with raw bitmaps. */ -struct _BitmapObject { - MMBitmapRef bitmap; - MMPoint point; /* For iterator */ -}; - -typedef struct _BitmapObject BitmapObject; - -// extern PyTypeObject Bitmap_Type; - -/* Returns a newly-initialized BitmapObject from the given MMBitmap. - * The reference to |bitmap| is "stolen"; i.e., only the pointer is copied, and - * the reponsibility for free()'ing the buffer is given to the |BitmapObject|. - * - * Remember to call PyType_Ready() before using this for the first time! */ -BitmapObject BitmapObject_FromMMBitmap(MMBitmapRef bitmap); - -// #endif /* PY_BITMAP_CLASS_H */ \ No newline at end of file diff --git a/bitmap/bitmap_find.h b/bitmap/bitmap_find.h deleted file mode 100644 index 763fa234..00000000 --- a/bitmap/bitmap_find.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#ifndef BITMAP_H -#define BITMAP_H - -// #include "../base/types.h" -#include "../base/MMBitmap.h" -#include "../base/MMPointArray_c.h" - -/* Convenience wrapper around findBitmapInRect(), where |rect| is the bounds - * of |haystack|. */ -#define findBitmapInBitmap(needle, haystack, pointPtr, tol) \ - findBitmapInRect(needle, haystack, pointPtr, MMBitmapGetBounds(haystack), tol) - -/* Returns 0 and sets |point| to the origin of |needle| in |haystack| if - * |needle| was found in |haystack| inside of |rect|, or returns -1 if not. - * - * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the - * colors in the bitmaps need to match, with 0 being exact and 1 being any. - */ -int findBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack, - MMPoint *point, MMRect rect, float tolerance); - -/* Convenience wrapper around findAllBitmapInRect(), where |rect| is the bounds - * of |haystack|. */ -#define findAllBitmapInBitmap(needle, haystack, tolerance) \ - findAllBitmapInRect(needle, haystack, \ - MMBitmapGetBounds(haystack), tolerance) - -/* Returns MMPointArray of all occurrences of |needle| in |haystack| inside of - * |rect|. Note that an is returned regardless of whether |needle| was found; - * check array->count to see if it actually was. - * - * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the - * colors in the bitmaps need to match, with 0 being exact and 1 being any. - * - * Responsibility for freeing the MMPointArray with destroyMMPointArray() is - * given to the caller. - */ -MMPointArrayRef findAllBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack, - MMRect rect, float tolerance); - -// #define MMRGBHexAtPoint(image, x, y) \ -// hexFromMMRGB(MMRGBColorAtPoint(image, x, y)) - -/* Convenience wrapper around countOfBitmapInRect(), where |rect| is the bounds - * of |haystack|. */ -#define countOfBitmapInBitmap(needle, haystack, tolerance) \ - countOfBitmapInRect(needle, haystack, MMBitmapGetBounds(haystack), tolerance) - -/* Returns the number of occurences of |needle| in |haystack| inside - * of |rect|. */ -size_t countOfBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack, - MMRect rect, float tolerance); - -#endif /* BITMAP_H */ diff --git a/bitmap/bitmap_find_c.h b/bitmap/bitmap_find_c.h deleted file mode 100644 index 1df90f63..00000000 --- a/bitmap/bitmap_find_c.h +++ /dev/null @@ -1,270 +0,0 @@ -#include "bitmap_find.h" -#include "../base/UTHashTable_c.h" -#include - -/* Node to be used in hash table. */ -struct shiftNode { - UTHashNode_HEAD /* Make structure hashable */ - MMRGBHex color; /* Key */ - MMPoint offset; /* Value */ -}; - -/* --- Hash table helper functions --- */ - -/* Adds hex-color/offset pair to jump table. */ -static void addNodeToTable(UTHashTable *table, MMRGBHex color, MMPoint offset); - -/* Returns node associated with color in jump table, or NULL if it - * doesn't exist. */ -static struct shiftNode *nodeForColor(UTHashTable *table, MMRGBHex color); - -/* Returns nonzero (true) if table has key, or zero (false) if not. */ -#define tableHasKey(table, color) (nodeForColor(table, color) != NULL) - -/* --- Boyer-Moore helper functions --- */ - -/* Calculates the first table for use in a Boyer-Moore search algorithm. - * Table is in the form [colors: shift_values], where colors are those in - * |needle|, and the shift values are each color's distance from the rightmost - * offset. All other colors are assumed to have a shift value equal to the - * length of needle. - */ -static void initBadShiftTable(UTHashTable *jumpTable, MMBitmapRef needle); - -/* Frees memory occupied by calling initBadShiftTable(). - * Currently this is just an alias for destroyHashTable(). */ -#define destroyBadShiftTable(jumpTable) destroyHashTable(jumpTable) - -/* Returns true if |needle| is found in |haystack| at |offset|. */ -static int needleAtOffset(MMBitmapRef needle, MMBitmapRef haystack, - MMPoint offset, float tolerance); -/* --- --- */ - -/* An modification of the Boyer-Moore-Horspool Algorithm, only applied to - * bitmaps and colors instead of strings and characters. - * - * TODO: The Boyer-Moore algorithm (with the second jump table) would probably - * be more efficient, but this was simpler (for now). - * - * The jump table (|badShiftTable|) is passed as a parameter to avoid being - * recalculated each time. It should be a pointer to a UTHashTable init'd with - * initBadShiftTable(). - * - * Returns 0 and sets |point| to the starting point of |needle| in |haystack| - * if |needle| was found in |haystack|, or returns -1 if not. */ -static int findBitmapInRectAt(MMBitmapRef needle, - MMBitmapRef haystack, - MMPoint *point, - MMRect rect, - float tolerance, - MMPoint startPoint, - UTHashTable *badShiftTable) -{ - const size_t scanHeight = rect.size.height - needle->height; - const size_t scanWidth = rect.size.width - needle->width; - MMPoint pointOffset = startPoint; - /* const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1); */ - - /* Sanity check */ - if (needle->height > haystack->height || needle->width > haystack->width || - !MMBitmapRectInBounds(haystack, rect)) { - return -1; - } - - assert(point != NULL); - assert(needle != NULL); - assert(needle->height > 0 && needle->width > 0); - assert(haystack != NULL); - assert(haystack->height > 0 && haystack->width > 0); - assert(badShiftTable != NULL); - - /* Search |haystack|, while |needle| can still be within it. */ - while (pointOffset.y <= scanHeight) { - /* struct shiftNode *node = NULL; - MMRGBHex lastColor; */ - - while (pointOffset.x <= scanWidth) { - /* Check offset in |haystack| for |needle|. */ - if (needleAtOffset(needle, haystack, pointOffset, tolerance)) { - // ++pointOffset.x; - // ++pointOffset.y; - *point = pointOffset; - return 0; - } - - /* Otherwise, calculate next x offset to check. */ - /* - * Note that here we are getting the skip value based on the last - * color of |needle|, no matter where we didn't match. The - * alternative of pretending that the mismatched color was the previous - * color is slower in the normal case. - */ - /* lastColor = MMRGBHexAtPoint(haystack, pointOffset.x + lastPoint.x, - pointOffset.y + lastPoint.y); */ - - /* TODO: This fails on certain edge cases (issue#7). */ - /* When a color is encountered that does not occur in |needle|, we can - * safely skip ahead for the whole length of |needle|. - * Otherwise, use the value stored in the jump table. */ - /* node = nodeForColor(badShiftTable, lastColor); - pointOffset.x += (node == NULL) ? needle->width : (node->offset).x; */ - - /* For now, be naive. */ - ++pointOffset.x; - } - - pointOffset.x = rect.origin.x; - - /* lastColor = MMRGBHexAtPoint(haystack, pointOffset.x + lastPoint.x, - pointOffset.y + lastPoint.y); - node = nodeForColor(badShiftTable, lastColor); - pointOffset.y += node == NULL ? lastPoint.y : (node->offset).y; */ - - /* TODO: The above commented out code fails at certain edge cases, e.g.: - * Needle: [B, b - * b, b, - * B, b] - * Haystack: [w, w, w, w, w - * w, w, w, w, b - * w, w, w, b, b - * w, w, w, w, b] - * The previous algorithm noticed that the first 3 x 3 block had nothing - * in common with the image, and thus, after scanning the first row, - * skipped three blocks downward to scan the next (which didn't exist, - * so the loop ended). However, the needle was hidden IN-BETWEEN this - * jump -- skipping was appropriate for scanning the column but not - * the row. - * - * I need to figure out a more optimal solution; temporarily I am just - * scanning every single y coordinate, only skipping on x's. This - * always works, but is probably not optimal. - */ - ++pointOffset.y; - } - - return -1; -} - -int findBitmapInRect(MMBitmapRef needle, - MMBitmapRef haystack, - MMPoint *point, - MMRect rect, - float tolerance) -{ - UTHashTable badShiftTable; - int ret; - - initBadShiftTable(&badShiftTable, needle); - ret = findBitmapInRectAt(needle, haystack, point, rect, - tolerance, MMPointZero, &badShiftTable); - destroyBadShiftTable(&badShiftTable); - return ret; -} - -MMPointArrayRef findAllBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack, - MMRect rect, float tolerance) -{ - MMPointArrayRef pointArray = createMMPointArray(0); - MMPoint point = MMPointZero; - UTHashTable badShiftTable; - - initBadShiftTable(&badShiftTable, needle); - while (findBitmapInRectAt(needle, haystack, &point, rect, - tolerance, point, &badShiftTable) == 0) { - const size_t scanWidth = (haystack->width - needle->width) + 1; - MMPointArrayAppendPoint(pointArray, point); - ITER_NEXT_POINT(point, scanWidth, 0); - } - destroyBadShiftTable(&badShiftTable); - - return pointArray; -} - -size_t countOfBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack, - MMRect rect, float tolerance) -{ - size_t count = 0; - MMPoint point = MMPointZero; - UTHashTable badShiftTable; - - initBadShiftTable(&badShiftTable, needle); - while (findBitmapInRectAt(needle, haystack, &point, rect, - tolerance, point, &badShiftTable) == 0) { - const size_t scanWidth = (haystack->width - needle->width) + 1; - ++count; - ITER_NEXT_POINT(point, scanWidth, 0); - } - destroyBadShiftTable(&badShiftTable); - - return count; -} - -/* --- Boyer-Moore helper functions --- */ - -static void initBadShiftTable(UTHashTable *jumpTable, MMBitmapRef needle) -{ - const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1); - const size_t maxColors = needle->width * needle->height; - MMPoint scan; - - /* Allocate max size initially to avoid a million calls to malloc(). */ - initHashTable(jumpTable, maxColors, sizeof(struct shiftNode)); - - /* Populate jumpTable with analysis of |needle|. */ - for (scan.y = lastPoint.y; ; --scan.y) { - for (scan.x = lastPoint.x; ; --scan.x) { - MMRGBHex color = MMRGBHexAtPoint(needle, scan.x, scan.y); - if (!tableHasKey(jumpTable, color)) { - addNodeToTable(jumpTable, color, - MMPointMake(needle->width - scan.x, - needle->height - scan.y)); - } - - if (scan.x == 0) break; /* Avoid infinite loop from unsigned type. */ - } - if (scan.y == 0) break; - } -} - -static int needleAtOffset(MMBitmapRef needle, MMBitmapRef haystack, - MMPoint offset, float tolerance) -{ - const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1); - MMPoint scan; - - /* Note that |needle| is searched backwards, in accordance with the - * Boyer-Moore search algorithm. */ - for (scan.y = lastPoint.y; ; --scan.y) { - for (scan.x = lastPoint.x; ; --scan.x) { - MMRGBHex ncolor = MMRGBHexAtPoint(needle, scan.x, scan.y); - MMRGBHex hcolor = MMRGBHexAtPoint(haystack, offset.x + scan.x, - offset.y + scan.y); - if (!MMRGBHexSimilarToColor(ncolor, hcolor, tolerance)) return 0; - if (scan.x == 0) break; /* Avoid infinite loop from unsigned type. */ - } - if (scan.y == 0) break; - } - - return 1; -} - -/* --- Hash table helper functions --- */ - -static void addNodeToTable(UTHashTable *table, - MMRGBHex hexColor, - MMPoint offset) -{ - struct shiftNode *node = getNewNode(table); - node->color = hexColor; - node->offset = offset; - UTHASHTABLE_ADD_INT(table, color, node, struct shiftNode); -} - -static struct shiftNode *nodeForColor(UTHashTable *table, - MMRGBHex color) -{ - struct shiftNode *uttable = table->uttable; - struct shiftNode *node; - HASH_FIND_INT(uttable, &color, node); - return node; -} diff --git a/bitmap/goBitmap.h b/bitmap/goBitmap.h deleted file mode 100644 index 2a17bbdb..00000000 --- a/bitmap/goBitmap.h +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#include "bitmap_class.h" -#include "bitmap_find_c.h" -#include "../base/color_find_c.h" -// #include "../screen/screen_c.h" -#include "../base/file_io_c.h" -#include "../base/pasteboard_c.h" -#include "../base/str_io_c.h" -#include -#include - -/* Returns false and sets error if |bitmap| is NULL. */ -bool bitmap_ready(MMBitmapRef bitmap){ - if (bitmap == NULL || bitmap->imageBuffer == NULL) { - return false; - } - return true; -} - -void bitmap_dealloc(MMBitmapRef bitmap){ - if (bitmap != NULL) { - destroyMMBitmap(bitmap); - bitmap = NULL; - } -} - -bool bitmap_copy_to_pboard(MMBitmapRef bitmap){ - MMPasteError err; - - if (!bitmap_ready(bitmap)) return false; - if ((err = copyMMBitmapToPasteboard(bitmap)) != kMMPasteNoError) { - return false; - } - - return true; -} - -MMBitmapRef bitmap_deepcopy(MMBitmapRef bitmap){ - return bitmap == NULL ? NULL : copyMMBitmap(bitmap); -} - -MMPoint find_bitmap(MMBitmapRef bitmap, MMBitmapRef sbit, float tolerance){ - MMPoint point = {-1, -1}; - // printf("tolenrance=%f\n", tolerance); - if (!bitmap_ready(sbit) || !bitmap_ready(bitmap)) { - printf("bitmap is not ready yet!\n"); - return point; - } - - MMRect rect = MMBitmapGetBounds(sbit); - // printf("x=%d, y=%d, width=%d, height=%d\n", rect.origin.x, - // rect.origin.y, rect.size.width, rect.size.height); - - if (findBitmapInRect(bitmap, sbit, &point, - rect, tolerance) == 0) { - return point; - } - - return point; -} - -MMPoint *find_every_bitmap(MMBitmapRef bitmap, MMBitmapRef sbit, float tolerance, MMPoint *list){ - if (!bitmap_ready(bitmap) || !bitmap_ready(sbit)) return NULL; - - MMPoint point; - MMPointArrayRef pointArray; - MMRect rect = MMBitmapGetBounds(bitmap); - - if (findBitmapInRect(bitmap, sbit, &point, - rect, tolerance) == 0) { - return NULL; - } - - pointArray = findAllBitmapInRect(bitmap, sbit, rect, tolerance); - if (pointArray == NULL) return NULL; - - memcpy(list, pointArray->array, sizeof(MMPoint) * pointArray->count); - destroyMMPointArray(pointArray); - - return list; -} - -int count_of_bitmap(MMBitmapRef bitmap, MMBitmapRef sbit, float tolerance){ - if (!bitmap_ready(bitmap) || !bitmap_ready(sbit)) return 0; - - MMRect rect = MMBitmapGetBounds(bitmap); - - return countOfBitmapInRect(bitmap, sbit, rect, tolerance); -} - -bool point_in_bounds(MMBitmapRef bitmap, MMPoint point){ - if (!bitmap_ready(bitmap)) { - return NULL; - } - - if (MMBitmapPointInBounds(bitmap, point)) { - return true; - } - - return false; -} - -MMBitmapRef bitmap_open(char *path, uint16_t ttype){ - // MMImageType type; - MMBitmapRef bitmap; - MMIOError err; - - bitmap = newMMBitmapFromFile(path, ttype, &err); - // printf("....%zd\n", bitmap->width); - return bitmap; - -} - -MMBitmapRef bitmap_from_string(const char *str){ - size_t len = strlen(str); - - MMBitmapRef bitmap; - MMBMPStringError err; - - if ((bitmap = createMMBitmapFromString( - (unsigned char*)str, len, &err ) - ) == NULL) { - return NULL; - } - - return bitmap; -} - -char *bitmap_save(MMBitmapRef bitmap, char *path, uint16_t type){ - if (saveMMBitmapToFile(bitmap, path, (MMImageType) type) != 0) { - return "Could not save image to file."; - } - // destroyMMBitmap(bitmap); - return ""; -} - -char *tostring_bitmap(MMBitmapRef bitmap){ - char *buf = NULL; - MMBMPStringError err; - - buf = (char *)createStringFromMMBitmap(bitmap, &err); - - return buf; -} - -// out with size 200 is enough -bool bitmap_str(MMBitmapRef bitmap, char *out){ - if (!bitmap_ready(bitmap)) return false; - sprintf(out, "", - (unsigned long)bitmap->width, - (unsigned long)bitmap->height, - bitmap->bitsPerPixel, - bitmap->bytesPerPixel); - - return true; -} - -MMBitmapRef get_portion(MMBitmapRef bit_map, MMRect rect){ - // MMRect rect; - MMBitmapRef portion = NULL; - - portion = copyMMBitmapFromPortion(bit_map, rect); - return portion; -} - -MMRGBHex bitmap_get_color(MMBitmapRef bitmap, size_t x, size_t y){ - if (!bitmap_ready(bitmap)) return 0; - - MMPoint point; - point = MMPointMake(x, y); - - if (!MMBitmapPointInBounds(bitmap, point)) { - return 0; - } - - return MMRGBHexAtPoint(bitmap, point.x, point.y); -} - -MMPoint bitmap_find_color(MMBitmapRef bitmap, MMRGBHex color, float tolerance){ - MMRect rect = MMBitmapGetBounds(bitmap); - MMPoint point = {-1, -1}; - - if (findColorInRect(bitmap, color, &point, rect, tolerance) == 0) { - return point; - } - - return point; -} - -int bitmap_count_of_color(MMBitmapRef bitmap, MMRGBHex color, float tolerance){ - if (!bitmap_ready(bitmap)) return 0; - MMRect rect = MMBitmapGetBounds(bitmap); - - return countOfColorsInRect(bitmap, color, rect, tolerance); -} diff --git a/cdeps/README.md b/cdeps/README.md deleted file mode 100644 index 3303cf77..00000000 --- a/cdeps/README.md +++ /dev/null @@ -1 +0,0 @@ -C language dependent package, better to compilation. \ No newline at end of file diff --git a/cdeps/mac/libpng.a b/cdeps/mac/libpng.a deleted file mode 100644 index e2dc9659..00000000 Binary files a/cdeps/mac/libpng.a and /dev/null differ diff --git a/cdeps/mac/png.h b/cdeps/mac/png.h deleted file mode 100644 index 4c873f5c..00000000 --- a/cdeps/mac/png.h +++ /dev/null @@ -1,3278 +0,0 @@ - -/* png.h - header file for PNG reference library - * - * libpng version 1.6.34, September 29, 2017 - * - * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license (See LICENSE, below) - * - * Authors and maintainers: - * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat - * libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger - * libpng versions 0.97, January 1998, through 1.6.34, September 29, 2017: - * Glenn Randers-Pehrson. - * See also "Contributing Authors", below. - */ - -/* - * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: - * - * If you modify libpng you may insert additional notices immediately following - * this sentence. - * - * This code is released under the libpng license. - * - * libpng versions 1.0.7, July 1, 2000 through 1.6.34, September 29, 2017 are - * Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are - * derived from libpng-1.0.6, and are distributed according to the same - * disclaimer and license as libpng-1.0.6 with the following individuals - * added to the list of Contributing Authors: - * - * Simon-Pierre Cadieux - * Eric S. Raymond - * Mans Rullgard - * Cosmin Truta - * Gilles Vollant - * James Yu - * Mandar Sahastrabuddhe - * Google Inc. - * Vadim Barkov - * - * and with the following additions to the disclaimer: - * - * There is no warranty against interference with your enjoyment of the - * library or against infringement. There is no warranty that our - * efforts or the library will fulfill any of your particular purposes - * or needs. This library is provided with all faults, and the entire - * risk of satisfactory quality, performance, accuracy, and effort is with - * the user. - * - * Some files in the "contrib" directory and some configure-generated - * files that are distributed with libpng have other copyright owners and - * are released under other open source licenses. - * - * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are - * Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from - * libpng-0.96, and are distributed according to the same disclaimer and - * license as libpng-0.96, with the following individuals added to the list - * of Contributing Authors: - * - * Tom Lane - * Glenn Randers-Pehrson - * Willem van Schaik - * - * libpng versions 0.89, June 1996, through 0.96, May 1997, are - * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, - * and are distributed according to the same disclaimer and license as - * libpng-0.88, with the following individuals added to the list of - * Contributing Authors: - * - * John Bowler - * Kevin Bracey - * Sam Bushell - * Magnus Holmgren - * Greg Roelofs - * Tom Tanner - * - * Some files in the "scripts" directory have other copyright owners - * but are released under this license. - * - * libpng versions 0.5, May 1995, through 0.88, January 1996, are - * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - * - * For the purposes of this copyright and license, "Contributing Authors" - * is defined as the following set of individuals: - * - * Andreas Dilger - * Dave Martindale - * Guy Eric Schalnat - * Paul Schmidt - * Tim Wegner - * - * The PNG Reference Library is supplied "AS IS". The Contributing Authors - * and Group 42, Inc. disclaim all warranties, expressed or implied, - * including, without limitation, the warranties of merchantability and of - * fitness for any purpose. The Contributing Authors and Group 42, Inc. - * assume no liability for direct, indirect, incidental, special, exemplary, - * or consequential damages, which may result from the use of the PNG - * Reference Library, even if advised of the possibility of such damage. - * - * Permission is hereby granted to use, copy, modify, and distribute this - * source code, or portions hereof, for any purpose, without fee, subject - * to the following restrictions: - * - * 1. The origin of this source code must not be misrepresented. - * - * 2. Altered versions must be plainly marked as such and must not - * be misrepresented as being the original source. - * - * 3. This Copyright notice may not be removed or altered from any - * source or altered source distribution. - * - * The Contributing Authors and Group 42, Inc. specifically permit, without - * fee, and encourage the use of this source code as a component to - * supporting the PNG file format in commercial products. If you use this - * source code in a product, acknowledgment is not required but would be - * appreciated. - * - * END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE. - * - * TRADEMARK: - * - * The name "libpng" has not been registered by the Copyright owner - * as a trademark in any jurisdiction. However, because libpng has - * been distributed and maintained world-wide, continually since 1995, - * the Copyright owner claims "common-law trademark protection" in any - * jurisdiction where common-law trademark is recognized. - * - * OSI CERTIFICATION: - * - * Libpng is OSI Certified Open Source Software. OSI Certified Open Source is - * a certification mark of the Open Source Initiative. OSI has not addressed - * the additional disclaimers inserted at version 1.0.7. - * - * EXPORT CONTROL: - * - * The Copyright owner believes that the Export Control Classification - * Number (ECCN) for libpng is EAR99, which means not subject to export - * controls or International Traffic in Arms Regulations (ITAR) because - * it is open source, publicly available software, that does not contain - * any encryption software. See the EAR, paragraphs 734.3(b)(3) and - * 734.7(b). - */ - -/* - * A "png_get_copyright" function is available, for convenient use in "about" - * boxes and the like: - * - * printf("%s", png_get_copyright(NULL)); - * - * Also, the PNG logo (in PNG format, of course) is supplied in the - * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31). - */ - -/* - * The contributing authors would like to thank all those who helped - * with testing, bug fixes, and patience. This wouldn't have been - * possible without all of you. - * - * Thanks to Frank J. T. Wojcik for helping with the documentation. - */ - -/* Note about libpng version numbers: - * - * Due to various miscommunications, unforeseen code incompatibilities - * and occasional factors outside the authors' control, version numbering - * on the library has not always been consistent and straightforward. - * The following table summarizes matters since version 0.89c, which was - * the first widely used release: - * - * source png.h png.h shared-lib - * version string int version - * ------- ------ ----- ---------- - * 0.89c "1.0 beta 3" 0.89 89 1.0.89 - * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90] - * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95] - * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96] - * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97] - * 0.97c 0.97 97 2.0.97 - * 0.98 0.98 98 2.0.98 - * 0.99 0.99 98 2.0.99 - * 0.99a-m 0.99 99 2.0.99 - * 1.00 1.00 100 2.1.0 [100 should be 10000] - * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000] - * 1.0.1 png.h string is 10001 2.1.0 - * 1.0.1a-e identical to the 10002 from here on, the shared library - * 1.0.2 source version) 10002 is 2.V where V is the source code - * 1.0.2a-b 10003 version, except as noted. - * 1.0.3 10003 - * 1.0.3a-d 10004 - * 1.0.4 10004 - * 1.0.4a-f 10005 - * 1.0.5 (+ 2 patches) 10005 - * 1.0.5a-d 10006 - * 1.0.5e-r 10100 (not source compatible) - * 1.0.5s-v 10006 (not binary compatible) - * 1.0.6 (+ 3 patches) 10006 (still binary incompatible) - * 1.0.6d-f 10007 (still binary incompatible) - * 1.0.6g 10007 - * 1.0.6h 10007 10.6h (testing xy.z so-numbering) - * 1.0.6i 10007 10.6i - * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0) - * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible) - * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible) - * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible) - * 1.0.7 1 10007 (still compatible) - * ... - * 1.0.19 10 10019 10.so.0.19[.0] - * ... - * 1.2.59 13 10257 12.so.0.59[.0] - * ... - * 1.5.30 15 10527 15.so.15.30[.0] - * ... - * 1.6.34 16 10633 16.so.16.34[.0] - * - * Henceforth the source version will match the shared-library major - * and minor numbers; the shared-library major version number will be - * used for changes in backward compatibility, as it is intended. The - * PNG_LIBPNG_VER macro, which is not used within libpng but is available - * for applications, is an unsigned integer of the form xyyzz corresponding - * to the source version x.y.z (leading zeros in y and z). Beta versions - * were given the previous public release number plus a letter, until - * version 1.0.6j; from then on they were given the upcoming public - * release number plus "betaNN" or "rcNN". - * - * Binary incompatibility exists only when applications make direct access - * to the info_ptr or png_ptr members through png.h, and the compiled - * application is loaded with a different version of the library. - * - * DLLNUM will change each time there are forward or backward changes - * in binary compatibility (e.g., when a new feature is added). - * - * See libpng.txt or libpng.3 for more information. The PNG specification - * is available as a W3C Recommendation and as an ISO Specification, - * - * - * If you just need to read a PNG file and don't want to read the documentation - * skip to the end of this file and read the section entitled 'simplified API'. - */ - -/* Version information for png.h - this should match the version in png.c */ -#define PNG_LIBPNG_VER_STRING "1.6.34" -#define PNG_HEADER_VERSION_STRING " libpng version 1.6.34 - September 29, 2017\n" - -#define PNG_LIBPNG_VER_SONUM 16 -#define PNG_LIBPNG_VER_DLLNUM 16 - -/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */ -#define PNG_LIBPNG_VER_MAJOR 1 -#define PNG_LIBPNG_VER_MINOR 6 -#define PNG_LIBPNG_VER_RELEASE 34 - -/* This should match the numeric part of the final component of - * PNG_LIBPNG_VER_STRING, omitting any leading zero: - */ - -#define PNG_LIBPNG_VER_BUILD 0 - -/* Release Status */ -#define PNG_LIBPNG_BUILD_ALPHA 1 -#define PNG_LIBPNG_BUILD_BETA 2 -#define PNG_LIBPNG_BUILD_RC 3 -#define PNG_LIBPNG_BUILD_STABLE 4 -#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7 - -/* Release-Specific Flags */ -#define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with - PNG_LIBPNG_BUILD_STABLE only */ -#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with - PNG_LIBPNG_BUILD_SPECIAL */ -#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with - PNG_LIBPNG_BUILD_PRIVATE */ - -#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE - -/* Careful here. At one time, Guy wanted to use 082, but that would be octal. - * We must not include leading zeros. - * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only - * version 1.0.0 was mis-numbered 100 instead of 10000). From - * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release - */ -#define PNG_LIBPNG_VER 10634 /* 1.6.34 */ - -/* Library configuration: these options cannot be changed after - * the library has been built. - */ -#ifndef PNGLCONF_H -/* If pnglibconf.h is missing, you can - * copy scripts/pnglibconf.h.prebuilt to pnglibconf.h - */ -# include "pnglibconf.h" -#endif - -#ifndef PNG_VERSION_INFO_ONLY -/* Machine specific configuration. */ -# include "pngconf.h" -#endif - -/* - * Added at libpng-1.2.8 - * - * Ref MSDN: Private as priority over Special - * VS_FF_PRIVATEBUILD File *was not* built using standard release - * procedures. If this value is given, the StringFileInfo block must - * contain a PrivateBuild string. - * - * VS_FF_SPECIALBUILD File *was* built by the original company using - * standard release procedures but is a variation of the standard - * file of the same version number. If this value is given, the - * StringFileInfo block must contain a SpecialBuild string. - */ - -#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */ -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE) -#else -# ifdef PNG_LIBPNG_SPECIALBUILD -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL) -# else -# define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE) -# endif -#endif - -#ifndef PNG_VERSION_INFO_ONLY - -/* Inhibit C++ name-mangling for libpng functions but not for system calls. */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Version information for C files, stored in png.c. This had better match - * the version above. - */ -#define png_libpng_ver png_get_header_ver(NULL) - -/* This file is arranged in several sections: - * - * 1. [omitted] - * 2. Any configuration options that can be specified by for the application - * code when it is built. (Build time configuration is in pnglibconf.h) - * 3. Type definitions (base types are defined in pngconf.h), structure - * definitions. - * 4. Exported library functions. - * 5. Simplified API. - * 6. Implementation options. - * - * The library source code has additional files (principally pngpriv.h) that - * allow configuration of the library. - */ - -/* Section 1: [omitted] */ - -/* Section 2: run time configuration - * See pnglibconf.h for build time configuration - * - * Run time configuration allows the application to choose between - * implementations of certain arithmetic APIs. The default is set - * at build time and recorded in pnglibconf.h, but it is safe to - * override these (and only these) settings. Note that this won't - * change what the library does, only application code, and the - * settings can (and probably should) be made on a per-file basis - * by setting the #defines before including png.h - * - * Use macros to read integers from PNG data or use the exported - * functions? - * PNG_USE_READ_MACROS: use the macros (see below) Note that - * the macros evaluate their argument multiple times. - * PNG_NO_USE_READ_MACROS: call the relevant library function. - * - * Use the alternative algorithm for compositing alpha samples that - * does not use division? - * PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division' - * algorithm. - * PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm. - * - * How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is - * false? - * PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error - * APIs to png_warning. - * Otherwise the calls are mapped to png_error. - */ - -/* Section 3: type definitions, including structures and compile time - * constants. - * See pngconf.h for base types that vary by machine/system - */ - -/* This triggers a compiler error in png.c, if png.c and png.h - * do not agree upon the version number. - */ -typedef char* png_libpng_version_1_6_34; - -/* Basic control structions. Read libpng-manual.txt or libpng.3 for more info. - * - * png_struct is the cache of information used while reading or writing a single - * PNG file. One of these is always required, although the simplified API - * (below) hides the creation and destruction of it. - */ -typedef struct png_struct_def png_struct; -typedef const png_struct * png_const_structp; -typedef png_struct * png_structp; -typedef png_struct * * png_structpp; - -/* png_info contains information read from or to be written to a PNG file. One - * or more of these must exist while reading or creating a PNG file. The - * information is not used by libpng during read but is used to control what - * gets written when a PNG file is created. "png_get_" function calls read - * information during read and "png_set_" functions calls write information - * when creating a PNG. - * been moved into a separate header file that is not accessible to - * applications. Read libpng-manual.txt or libpng.3 for more info. - */ -typedef struct png_info_def png_info; -typedef png_info * png_infop; -typedef const png_info * png_const_infop; -typedef png_info * * png_infopp; - -/* Types with names ending 'p' are pointer types. The corresponding types with - * names ending 'rp' are identical pointer types except that the pointer is - * marked 'restrict', which means that it is the only pointer to the object - * passed to the function. Applications should not use the 'restrict' types; - * it is always valid to pass 'p' to a pointer with a function argument of the - * corresponding 'rp' type. Different compilers have different rules with - * regard to type matching in the presence of 'restrict'. For backward - * compatibility libpng callbacks never have 'restrict' in their parameters and, - * consequentially, writing portable application code is extremely difficult if - * an attempt is made to use 'restrict'. - */ -typedef png_struct * PNG_RESTRICT png_structrp; -typedef const png_struct * PNG_RESTRICT png_const_structrp; -typedef png_info * PNG_RESTRICT png_inforp; -typedef const png_info * PNG_RESTRICT png_const_inforp; - -/* Three color definitions. The order of the red, green, and blue, (and the - * exact size) is not important, although the size of the fields need to - * be png_byte or png_uint_16 (as defined below). - */ -typedef struct png_color_struct -{ - png_byte red; - png_byte green; - png_byte blue; -} png_color; -typedef png_color * png_colorp; -typedef const png_color * png_const_colorp; -typedef png_color * * png_colorpp; - -typedef struct png_color_16_struct -{ - png_byte index; /* used for palette files */ - png_uint_16 red; /* for use in red green blue files */ - png_uint_16 green; - png_uint_16 blue; - png_uint_16 gray; /* for use in grayscale files */ -} png_color_16; -typedef png_color_16 * png_color_16p; -typedef const png_color_16 * png_const_color_16p; -typedef png_color_16 * * png_color_16pp; - -typedef struct png_color_8_struct -{ - png_byte red; /* for use in red green blue files */ - png_byte green; - png_byte blue; - png_byte gray; /* for use in grayscale files */ - png_byte alpha; /* for alpha channel files */ -} png_color_8; -typedef png_color_8 * png_color_8p; -typedef const png_color_8 * png_const_color_8p; -typedef png_color_8 * * png_color_8pp; - -/* - * The following two structures are used for the in-core representation - * of sPLT chunks. - */ -typedef struct png_sPLT_entry_struct -{ - png_uint_16 red; - png_uint_16 green; - png_uint_16 blue; - png_uint_16 alpha; - png_uint_16 frequency; -} png_sPLT_entry; -typedef png_sPLT_entry * png_sPLT_entryp; -typedef const png_sPLT_entry * png_const_sPLT_entryp; -typedef png_sPLT_entry * * png_sPLT_entrypp; - -/* When the depth of the sPLT palette is 8 bits, the color and alpha samples - * occupy the LSB of their respective members, and the MSB of each member - * is zero-filled. The frequency member always occupies the full 16 bits. - */ - -typedef struct png_sPLT_struct -{ - png_charp name; /* palette name */ - png_byte depth; /* depth of palette samples */ - png_sPLT_entryp entries; /* palette entries */ - png_int_32 nentries; /* number of palette entries */ -} png_sPLT_t; -typedef png_sPLT_t * png_sPLT_tp; -typedef const png_sPLT_t * png_const_sPLT_tp; -typedef png_sPLT_t * * png_sPLT_tpp; - -#ifdef PNG_TEXT_SUPPORTED -/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file, - * and whether that contents is compressed or not. The "key" field - * points to a regular zero-terminated C string. The "text" fields can be a - * regular C string, an empty string, or a NULL pointer. - * However, the structure returned by png_get_text() will always contain - * the "text" field as a regular zero-terminated C string (possibly - * empty), never a NULL pointer, so it can be safely used in printf() and - * other string-handling functions. Note that the "itxt_length", "lang", and - * "lang_key" members of the structure only exist when the library is built - * with iTXt chunk support. Prior to libpng-1.4.0 the library was built by - * default without iTXt support. Also note that when iTXt *is* supported, - * the "lang" and "lang_key" fields contain NULL pointers when the - * "compression" field contains * PNG_TEXT_COMPRESSION_NONE or - * PNG_TEXT_COMPRESSION_zTXt. Note that the "compression value" is not the - * same as what appears in the PNG tEXt/zTXt/iTXt chunk's "compression flag" - * which is always 0 or 1, or its "compression method" which is always 0. - */ -typedef struct png_text_struct -{ - int compression; /* compression value: - -1: tEXt, none - 0: zTXt, deflate - 1: iTXt, none - 2: iTXt, deflate */ - png_charp key; /* keyword, 1-79 character description of "text" */ - png_charp text; /* comment, may be an empty string (ie "") - or a NULL pointer */ - png_size_t text_length; /* length of the text string */ - png_size_t itxt_length; /* length of the itxt string */ - png_charp lang; /* language code, 0-79 characters - or a NULL pointer */ - png_charp lang_key; /* keyword translated UTF-8 string, 0 or more - chars or a NULL pointer */ -} png_text; -typedef png_text * png_textp; -typedef const png_text * png_const_textp; -typedef png_text * * png_textpp; -#endif - -/* Supported compression types for text in PNG files (tEXt, and zTXt). - * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */ -#define PNG_TEXT_COMPRESSION_NONE_WR -3 -#define PNG_TEXT_COMPRESSION_zTXt_WR -2 -#define PNG_TEXT_COMPRESSION_NONE -1 -#define PNG_TEXT_COMPRESSION_zTXt 0 -#define PNG_ITXT_COMPRESSION_NONE 1 -#define PNG_ITXT_COMPRESSION_zTXt 2 -#define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */ - -/* png_time is a way to hold the time in an machine independent way. - * Two conversions are provided, both from time_t and struct tm. There - * is no portable way to convert to either of these structures, as far - * as I know. If you know of a portable way, send it to me. As a side - * note - PNG has always been Year 2000 compliant! - */ -typedef struct png_time_struct -{ - png_uint_16 year; /* full year, as in, 1995 */ - png_byte month; /* month of year, 1 - 12 */ - png_byte day; /* day of month, 1 - 31 */ - png_byte hour; /* hour of day, 0 - 23 */ - png_byte minute; /* minute of hour, 0 - 59 */ - png_byte second; /* second of minute, 0 - 60 (for leap seconds) */ -} png_time; -typedef png_time * png_timep; -typedef const png_time * png_const_timep; -typedef png_time * * png_timepp; - -#if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) ||\ - defined(PNG_USER_CHUNKS_SUPPORTED) -/* png_unknown_chunk is a structure to hold queued chunks for which there is - * no specific support. The idea is that we can use this to queue - * up private chunks for output even though the library doesn't actually - * know about their semantics. - * - * The data in the structure is set by libpng on read and used on write. - */ -typedef struct png_unknown_chunk_t -{ - png_byte name[5]; /* Textual chunk name with '\0' terminator */ - png_byte *data; /* Data, should not be modified on read! */ - png_size_t size; - - /* On write 'location' must be set using the flag values listed below. - * Notice that on read it is set by libpng however the values stored have - * more bits set than are listed below. Always treat the value as a - * bitmask. On write set only one bit - setting multiple bits may cause the - * chunk to be written in multiple places. - */ - png_byte location; /* mode of operation at read time */ -} -png_unknown_chunk; - -typedef png_unknown_chunk * png_unknown_chunkp; -typedef const png_unknown_chunk * png_const_unknown_chunkp; -typedef png_unknown_chunk * * png_unknown_chunkpp; -#endif - -/* Flag values for the unknown chunk location byte. */ -#define PNG_HAVE_IHDR 0x01 -#define PNG_HAVE_PLTE 0x02 -#define PNG_AFTER_IDAT 0x08 - -/* Maximum positive integer used in PNG is (2^31)-1 */ -#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL) -#define PNG_UINT_32_MAX ((png_uint_32)(-1)) -#define PNG_SIZE_MAX ((png_size_t)(-1)) - -/* These are constants for fixed point values encoded in the - * PNG specification manner (x100000) - */ -#define PNG_FP_1 100000 -#define PNG_FP_HALF 50000 -#define PNG_FP_MAX ((png_fixed_point)0x7fffffffL) -#define PNG_FP_MIN (-PNG_FP_MAX) - -/* These describe the color_type field in png_info. */ -/* color type masks */ -#define PNG_COLOR_MASK_PALETTE 1 -#define PNG_COLOR_MASK_COLOR 2 -#define PNG_COLOR_MASK_ALPHA 4 - -/* color types. Note that not all combinations are legal */ -#define PNG_COLOR_TYPE_GRAY 0 -#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE) -#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR) -#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA) -#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA) -/* aliases */ -#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA -#define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA - -/* This is for compression type. PNG 1.0-1.2 only define the single type. */ -#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */ -#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE - -/* This is for filter type. PNG 1.0-1.2 only define the single type. */ -#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */ -#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */ -#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE - -/* These are for the interlacing type. These values should NOT be changed. */ -#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */ -#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */ -#define PNG_INTERLACE_LAST 2 /* Not a valid value */ - -/* These are for the oFFs chunk. These values should NOT be changed. */ -#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */ -#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */ -#define PNG_OFFSET_LAST 2 /* Not a valid value */ - -/* These are for the pCAL chunk. These values should NOT be changed. */ -#define PNG_EQUATION_LINEAR 0 /* Linear transformation */ -#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */ -#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */ -#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */ -#define PNG_EQUATION_LAST 4 /* Not a valid value */ - -/* These are for the sCAL chunk. These values should NOT be changed. */ -#define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */ -#define PNG_SCALE_METER 1 /* meters per pixel */ -#define PNG_SCALE_RADIAN 2 /* radians per pixel */ -#define PNG_SCALE_LAST 3 /* Not a valid value */ - -/* These are for the pHYs chunk. These values should NOT be changed. */ -#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */ -#define PNG_RESOLUTION_METER 1 /* pixels/meter */ -#define PNG_RESOLUTION_LAST 2 /* Not a valid value */ - -/* These are for the sRGB chunk. These values should NOT be changed. */ -#define PNG_sRGB_INTENT_PERCEPTUAL 0 -#define PNG_sRGB_INTENT_RELATIVE 1 -#define PNG_sRGB_INTENT_SATURATION 2 -#define PNG_sRGB_INTENT_ABSOLUTE 3 -#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */ - -/* This is for text chunks */ -#define PNG_KEYWORD_MAX_LENGTH 79 - -/* Maximum number of entries in PLTE/sPLT/tRNS arrays */ -#define PNG_MAX_PALETTE_LENGTH 256 - -/* These determine if an ancillary chunk's data has been successfully read - * from the PNG header, or if the application has filled in the corresponding - * data in the info_struct to be written into the output file. The values - * of the PNG_INFO_ defines should NOT be changed. - */ -#define PNG_INFO_gAMA 0x0001U -#define PNG_INFO_sBIT 0x0002U -#define PNG_INFO_cHRM 0x0004U -#define PNG_INFO_PLTE 0x0008U -#define PNG_INFO_tRNS 0x0010U -#define PNG_INFO_bKGD 0x0020U -#define PNG_INFO_hIST 0x0040U -#define PNG_INFO_pHYs 0x0080U -#define PNG_INFO_oFFs 0x0100U -#define PNG_INFO_tIME 0x0200U -#define PNG_INFO_pCAL 0x0400U -#define PNG_INFO_sRGB 0x0800U /* GR-P, 0.96a */ -#define PNG_INFO_iCCP 0x1000U /* ESR, 1.0.6 */ -#define PNG_INFO_sPLT 0x2000U /* ESR, 1.0.6 */ -#define PNG_INFO_sCAL 0x4000U /* ESR, 1.0.6 */ -#define PNG_INFO_IDAT 0x8000U /* ESR, 1.0.6 */ -#define PNG_INFO_eXIf 0x10000U /* GR-P, 1.6.31 */ - -/* This is used for the transformation routines, as some of them - * change these values for the row. It also should enable using - * the routines for other purposes. - */ -typedef struct png_row_info_struct -{ - png_uint_32 width; /* width of row */ - png_size_t rowbytes; /* number of bytes in row */ - png_byte color_type; /* color type of row */ - png_byte bit_depth; /* bit depth of row */ - png_byte channels; /* number of channels (1, 2, 3, or 4) */ - png_byte pixel_depth; /* bits per pixel (depth * channels) */ -} png_row_info; - -typedef png_row_info * png_row_infop; -typedef png_row_info * * png_row_infopp; - -/* These are the function types for the I/O functions and for the functions - * that allow the user to override the default I/O functions with his or her - * own. The png_error_ptr type should match that of user-supplied warning - * and error functions, while the png_rw_ptr type should match that of the - * user read/write data functions. Note that the 'write' function must not - * modify the buffer it is passed. The 'read' function, on the other hand, is - * expected to return the read data in the buffer. - */ -typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp)); -typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t)); -typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp)); -typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32, - int)); -typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32, - int)); - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop)); -typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop)); - -/* The following callback receives png_uint_32 row_number, int pass for the - * png_bytep data of the row. When transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep, - png_uint_32, int)); -#endif - -#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ - defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) -typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop, - png_bytep)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp, - png_unknown_chunkp)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -/* not used anywhere */ -/* typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp)); */ -#endif - -#ifdef PNG_SETJMP_SUPPORTED -/* This must match the function definition in , and the application - * must include this before png.h to obtain the definition of jmp_buf. The - * function is required to be PNG_NORETURN, but this is not checked. If the - * function does return the application will crash via an abort() or similar - * system level call. - * - * If you get a warning here while building the library you may need to make - * changes to ensure that pnglibconf.h records the calling convention used by - * your compiler. This may be very difficult - try using a different compiler - * to build the library! - */ -PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef); -#endif - -/* Transform masks for the high-level interface */ -#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */ -#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */ -#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */ -#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */ -#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */ -#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */ -#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */ -#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */ -#define PNG_TRANSFORM_BGR 0x0080 /* read and write */ -#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */ -#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */ -#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */ -#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* write only */ -/* Added to libpng-1.2.34 */ -#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER -#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */ -/* Added to libpng-1.4.0 */ -#define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */ -/* Added to libpng-1.5.4 */ -#define PNG_TRANSFORM_EXPAND_16 0x4000 /* read only */ -#if INT_MAX >= 0x8000 /* else this might break */ -#define PNG_TRANSFORM_SCALE_16 0x8000 /* read only */ -#endif - -/* Flags for MNG supported features */ -#define PNG_FLAG_MNG_EMPTY_PLTE 0x01 -#define PNG_FLAG_MNG_FILTER_64 0x04 -#define PNG_ALL_MNG_FEATURES 0x05 - -/* NOTE: prior to 1.5 these functions had no 'API' style declaration, - * this allowed the zlib default functions to be used on Windows - * platforms. In 1.5 the zlib default malloc (which just calls malloc and - * ignores the first argument) should be completely compatible with the - * following. - */ -typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp, - png_alloc_size_t)); -typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp)); - -/* Section 4: exported functions - * Here are the function definitions most commonly used. This is not - * the place to find out how to use libpng. See libpng-manual.txt for the - * full explanation, see example.c for the summary. This just provides - * a simple one line description of the use of each function. - * - * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in - * pngconf.h and in the *.dfn files in the scripts directory. - * - * PNG_EXPORT(ordinal, type, name, (args)); - * - * ordinal: ordinal that is used while building - * *.def files. The ordinal value is only - * relevant when preprocessing png.h with - * the *.dfn files for building symbol table - * entries, and are removed by pngconf.h. - * type: return type of the function - * name: function name - * args: function arguments, with types - * - * When we wish to append attributes to a function prototype we use - * the PNG_EXPORTA() macro instead. - * - * PNG_EXPORTA(ordinal, type, name, (args), attributes); - * - * ordinal, type, name, and args: same as in PNG_EXPORT(). - * attributes: function attributes - */ - -/* Returns the version number of the library */ -PNG_EXPORT(1, png_uint_32, png_access_version_number, (void)); - -/* Tell lib we have already handled the first magic bytes. - * Handling more than 8 bytes from the beginning of the file is an error. - */ -PNG_EXPORT(2, void, png_set_sig_bytes, (png_structrp png_ptr, int num_bytes)); - -/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a - * PNG file. Returns zero if the supplied bytes match the 8-byte PNG - * signature, and non-zero otherwise. Having num_to_check == 0 or - * start > 7 will always fail (ie return non-zero). - */ -PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start, - png_size_t num_to_check)); - -/* Simple signature checking function. This is the same as calling - * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). - */ -#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n)) - -/* Allocate and initialize png_ptr struct for reading, and any other memory. */ -PNG_EXPORTA(4, png_structp, png_create_read_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warn_fn), - PNG_ALLOCATED); - -/* Allocate and initialize png_ptr struct for writing, and any other memory */ -PNG_EXPORTA(5, png_structp, png_create_write_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn), - PNG_ALLOCATED); - -PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size, - (png_const_structrp png_ptr)); - -PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structrp png_ptr, - png_size_t size)); - -/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp - * match up. - */ -#ifdef PNG_SETJMP_SUPPORTED -/* This function returns the jmp_buf built in to *png_ptr. It must be - * supplied with an appropriate 'longjmp' function to use on that jmp_buf - * unless the default error function is overridden in which case NULL is - * acceptable. The size of the jmp_buf is checked against the actual size - * allocated by the library - the call will return NULL on a mismatch - * indicating an ABI mismatch. - */ -PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structrp png_ptr, - png_longjmp_ptr longjmp_fn, size_t jmp_buf_size)); -# define png_jmpbuf(png_ptr) \ - (*png_set_longjmp_fn((png_ptr), longjmp, (sizeof (jmp_buf)))) -#else -# define png_jmpbuf(png_ptr) \ - (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP) -#endif -/* This function should be used by libpng applications in place of - * longjmp(png_ptr->jmpbuf, val). If longjmp_fn() has been set, it - * will use it; otherwise it will call PNG_ABORT(). This function was - * added in libpng-1.5.0. - */ -PNG_EXPORTA(9, void, png_longjmp, (png_const_structrp png_ptr, int val), - PNG_NORETURN); - -#ifdef PNG_READ_SUPPORTED -/* Reset the compression stream */ -PNG_EXPORTA(10, int, png_reset_zstream, (png_structrp png_ptr), PNG_DEPRECATED); -#endif - -/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */ -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(11, png_structp, png_create_read_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -PNG_EXPORTA(12, png_structp, png_create_write_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -#endif - -/* Write the PNG file signature. */ -PNG_EXPORT(13, void, png_write_sig, (png_structrp png_ptr)); - -/* Write a PNG chunk - size, type, (optional) data, CRC. */ -PNG_EXPORT(14, void, png_write_chunk, (png_structrp png_ptr, png_const_bytep - chunk_name, png_const_bytep data, png_size_t length)); - -/* Write the start of a PNG chunk - length and chunk name. */ -PNG_EXPORT(15, void, png_write_chunk_start, (png_structrp png_ptr, - png_const_bytep chunk_name, png_uint_32 length)); - -/* Write the data of a PNG chunk started with png_write_chunk_start(). */ -PNG_EXPORT(16, void, png_write_chunk_data, (png_structrp png_ptr, - png_const_bytep data, png_size_t length)); - -/* Finish a chunk started with png_write_chunk_start() (includes CRC). */ -PNG_EXPORT(17, void, png_write_chunk_end, (png_structrp png_ptr)); - -/* Allocate and initialize the info structure */ -PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_const_structrp png_ptr), - PNG_ALLOCATED); - -/* DEPRECATED: this function allowed init structures to be created using the - * default allocation method (typically malloc). Use is deprecated in 1.6.0 and - * the API will be removed in the future. - */ -PNG_EXPORTA(19, void, png_info_init_3, (png_infopp info_ptr, - png_size_t png_info_struct_size), PNG_DEPRECATED); - -/* Writes all the PNG information before the image. */ -PNG_EXPORT(20, void, png_write_info_before_PLTE, - (png_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(21, void, png_write_info, - (png_structrp png_ptr, png_const_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the information before the actual image data. */ -PNG_EXPORT(22, void, png_read_info, - (png_structrp png_ptr, png_inforp info_ptr)); -#endif - -#ifdef PNG_TIME_RFC1123_SUPPORTED - /* Convert to a US string format: there is no localization support in this - * routine. The original implementation used a 29 character buffer in - * png_struct, this will be removed in future versions. - */ -#if PNG_LIBPNG_VER < 10700 -/* To do: remove this from libpng17 (and from libpng17/png.c and pngstruct.h) */ -PNG_EXPORTA(23, png_const_charp, png_convert_to_rfc1123, (png_structrp png_ptr, - png_const_timep ptime),PNG_DEPRECATED); -#endif -PNG_EXPORT(241, int, png_convert_to_rfc1123_buffer, (char out[29], - png_const_timep ptime)); -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED -/* Convert from a struct tm to png_time */ -PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime, - const struct tm * ttime)); - -/* Convert from time_t to png_time. Uses gmtime() */ -PNG_EXPORT(25, void, png_convert_from_time_t, (png_timep ptime, time_t ttime)); -#endif /* CONVERT_tIME */ - -#ifdef PNG_READ_EXPAND_SUPPORTED -/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */ -PNG_EXPORT(26, void, png_set_expand, (png_structrp png_ptr)); -PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structrp png_ptr)); -PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structrp png_ptr)); -PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_EXPAND_16_SUPPORTED -/* Expand to 16-bit channels, forces conversion of palette to RGB and expansion - * of a tRNS chunk if present. - */ -PNG_EXPORT(221, void, png_set_expand_16, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) -/* Use blue, green, red order for pixels. */ -PNG_EXPORT(30, void, png_set_bgr, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED -/* Expand the grayscale to 24-bit RGB if necessary. */ -PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED -/* Reduce RGB to grayscale. */ -#define PNG_ERROR_ACTION_NONE 1 -#define PNG_ERROR_ACTION_WARN 2 -#define PNG_ERROR_ACTION_ERROR 3 -#define PNG_RGB_TO_GRAY_DEFAULT (-1)/*for red/green coefficients*/ - -PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structrp png_ptr, - int error_action, double red, double green)) -PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structrp png_ptr, - int error_action, png_fixed_point red, png_fixed_point green)) - -PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structrp - png_ptr)); -#endif - -#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED -PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth, - png_colorp palette)); -#endif - -#ifdef PNG_READ_ALPHA_MODE_SUPPORTED -/* How the alpha channel is interpreted - this affects how the color channels - * of a PNG file are returned to the calling application when an alpha channel, - * or a tRNS chunk in a palette file, is present. - * - * This has no effect on the way pixels are written into a PNG output - * datastream. The color samples in a PNG datastream are never premultiplied - * with the alpha samples. - * - * The default is to return data according to the PNG specification: the alpha - * channel is a linear measure of the contribution of the pixel to the - * corresponding composited pixel, and the color channels are unassociated - * (not premultiplied). The gamma encoded color channels must be scaled - * according to the contribution and to do this it is necessary to undo - * the encoding, scale the color values, perform the composition and reencode - * the values. This is the 'PNG' mode. - * - * The alternative is to 'associate' the alpha with the color information by - * storing color channel values that have been scaled by the alpha. - * image. These are the 'STANDARD', 'ASSOCIATED' or 'PREMULTIPLIED' modes - * (the latter being the two common names for associated alpha color channels). - * - * For the 'OPTIMIZED' mode, a pixel is treated as opaque only if the alpha - * value is equal to the maximum value. - * - * The final choice is to gamma encode the alpha channel as well. This is - * broken because, in practice, no implementation that uses this choice - * correctly undoes the encoding before handling alpha composition. Use this - * choice only if other serious errors in the software or hardware you use - * mandate it; the typical serious error is for dark halos to appear around - * opaque areas of the composited PNG image because of arithmetic overflow. - * - * The API function png_set_alpha_mode specifies which of these choices to use - * with an enumerated 'mode' value and the gamma of the required output: - */ -#define PNG_ALPHA_PNG 0 /* according to the PNG standard */ -#define PNG_ALPHA_STANDARD 1 /* according to Porter/Duff */ -#define PNG_ALPHA_ASSOCIATED 1 /* as above; this is the normal practice */ -#define PNG_ALPHA_PREMULTIPLIED 1 /* as above */ -#define PNG_ALPHA_OPTIMIZED 2 /* 'PNG' for opaque pixels, else 'STANDARD' */ -#define PNG_ALPHA_BROKEN 3 /* the alpha channel is gamma encoded */ - -PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structrp png_ptr, int mode, - double output_gamma)) -PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structrp png_ptr, - int mode, png_fixed_point output_gamma)) -#endif - -#if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED) -/* The output_gamma value is a screen gamma in libpng terminology: it expresses - * how to decode the output values, not how they are encoded. - */ -#define PNG_DEFAULT_sRGB -1 /* sRGB gamma and color space */ -#define PNG_GAMMA_MAC_18 -2 /* Old Mac '1.8' gamma and color space */ -#define PNG_GAMMA_sRGB 220000 /* Television standards--matches sRGB gamma */ -#define PNG_GAMMA_LINEAR PNG_FP_1 /* Linear */ -#endif - -/* The following are examples of calls to png_set_alpha_mode to achieve the - * required overall gamma correction and, where necessary, alpha - * premultiplication. - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB); - * This is the default libpng handling of the alpha channel - it is not - * pre-multiplied into the color components. In addition the call states - * that the output is for a sRGB system and causes all PNG files without gAMA - * chunks to be assumed to be encoded using sRGB. - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC); - * In this case the output is assumed to be something like an sRGB conformant - * display preceeded by a power-law lookup table of power 1.45. This is how - * early Mac systems behaved. - * - * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR); - * This is the classic Jim Blinn approach and will work in academic - * environments where everything is done by the book. It has the shortcoming - * of assuming that input PNG data with no gamma information is linear - this - * is unlikely to be correct unless the PNG files where generated locally. - * Most of the time the output precision will be so low as to show - * significant banding in dark areas of the image. - * - * png_set_expand_16(pp); - * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_DEFAULT_sRGB); - * This is a somewhat more realistic Jim Blinn inspired approach. PNG files - * are assumed to have the sRGB encoding if not marked with a gamma value and - * the output is always 16 bits per component. This permits accurate scaling - * and processing of the data. If you know that your input PNG files were - * generated locally you might need to replace PNG_DEFAULT_sRGB with the - * correct value for your system. - * - * png_set_alpha_mode(pp, PNG_ALPHA_OPTIMIZED, PNG_DEFAULT_sRGB); - * If you just need to composite the PNG image onto an existing background - * and if you control the code that does this you can use the optimization - * setting. In this case you just copy completely opaque pixels to the - * output. For pixels that are not completely transparent (you just skip - * those) you do the composition math using png_composite or png_composite_16 - * below then encode the resultant 8-bit or 16-bit values to match the output - * encoding. - * - * Other cases - * If neither the PNG nor the standard linear encoding work for you because - * of the software or hardware you use then you have a big problem. The PNG - * case will probably result in halos around the image. The linear encoding - * will probably result in a washed out, too bright, image (it's actually too - * contrasty.) Try the ALPHA_OPTIMIZED mode above - this will probably - * substantially reduce the halos. Alternatively try: - * - * png_set_alpha_mode(pp, PNG_ALPHA_BROKEN, PNG_DEFAULT_sRGB); - * This option will also reduce the halos, but there will be slight dark - * halos round the opaque parts of the image where the background is light. - * In the OPTIMIZED mode the halos will be light halos where the background - * is dark. Take your pick - the halos are unavoidable unless you can get - * your hardware/software fixed! (The OPTIMIZED approach is slightly - * faster.) - * - * When the default gamma of PNG files doesn't match the output gamma. - * If you have PNG files with no gamma information png_set_alpha_mode allows - * you to provide a default gamma, but it also sets the ouput gamma to the - * matching value. If you know your PNG files have a gamma that doesn't - * match the output you can take advantage of the fact that - * png_set_alpha_mode always sets the output gamma but only sets the PNG - * default if it is not already set: - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB); - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC); - * The first call sets both the default and the output gamma values, the - * second call overrides the output gamma without changing the default. This - * is easier than achieving the same effect with png_set_gamma. You must use - * PNG_ALPHA_PNG for the first call - internal checking in png_set_alpha will - * fire if more than one call to png_set_alpha_mode and png_set_background is - * made in the same read operation, however multiple calls with PNG_ALPHA_PNG - * are ignored. - */ - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED -PNG_EXPORT(36, void, png_set_strip_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) -PNG_EXPORT(37, void, png_set_swap_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) -PNG_EXPORT(38, void, png_set_invert_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) -/* Add a filler byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */ -PNG_EXPORT(39, void, png_set_filler, (png_structrp png_ptr, png_uint_32 filler, - int flags)); -/* The values of the PNG_FILLER_ defines should NOT be changed */ -# define PNG_FILLER_BEFORE 0 -# define PNG_FILLER_AFTER 1 -/* Add an alpha byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */ -PNG_EXPORT(40, void, png_set_add_alpha, (png_structrp png_ptr, - png_uint_32 filler, int flags)); -#endif /* READ_FILLER || WRITE_FILLER */ - -#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) -/* Swap bytes in 16-bit depth files. */ -PNG_EXPORT(41, void, png_set_swap, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) -/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */ -PNG_EXPORT(42, void, png_set_packing, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \ - defined(PNG_WRITE_PACKSWAP_SUPPORTED) -/* Swap packing order of pixels in bytes. */ -PNG_EXPORT(43, void, png_set_packswap, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) -/* Converts files to legal bit depths. */ -PNG_EXPORT(44, void, png_set_shift, (png_structrp png_ptr, png_const_color_8p - true_bits)); -#endif - -#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ - defined(PNG_WRITE_INTERLACING_SUPPORTED) -/* Have the code handle the interlacing. Returns the number of passes. - * MUST be called before png_read_update_info or png_start_read_image, - * otherwise it will not have the desired effect. Note that it is still - * necessary to call png_read_row or png_read_rows png_get_image_height - * times for each pass. -*/ -PNG_EXPORT(45, int, png_set_interlace_handling, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) -/* Invert monochrome files */ -PNG_EXPORT(46, void, png_set_invert_mono, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_BACKGROUND_SUPPORTED -/* Handle alpha and tRNS by replacing with a background color. Prior to - * libpng-1.5.4 this API must not be called before the PNG file header has been - * read. Doing so will result in unexpected behavior and possible warnings or - * errors if the PNG file contains a bKGD chunk. - */ -PNG_FP_EXPORT(47, void, png_set_background, (png_structrp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, double background_gamma)) -PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structrp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, png_fixed_point background_gamma)) -#endif -#ifdef PNG_READ_BACKGROUND_SUPPORTED -# define PNG_BACKGROUND_GAMMA_UNKNOWN 0 -# define PNG_BACKGROUND_GAMMA_SCREEN 1 -# define PNG_BACKGROUND_GAMMA_FILE 2 -# define PNG_BACKGROUND_GAMMA_UNIQUE 3 -#endif - -#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED -/* Scale a 16-bit depth file down to 8-bit, accurately. */ -PNG_EXPORT(229, void, png_set_scale_16, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED -#define PNG_READ_16_TO_8_SUPPORTED /* Name prior to 1.5.4 */ -/* Strip the second byte of information from a 16-bit depth file. */ -PNG_EXPORT(48, void, png_set_strip_16, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_QUANTIZE_SUPPORTED -/* Turn on quantizing, and reduce the palette to the number of colors - * available. - */ -PNG_EXPORT(49, void, png_set_quantize, (png_structrp png_ptr, - png_colorp palette, int num_palette, int maximum_colors, - png_const_uint_16p histogram, int full_quantize)); -#endif - -#ifdef PNG_READ_GAMMA_SUPPORTED -/* The threshold on gamma processing is configurable but hard-wired into the - * library. The following is the floating point variant. - */ -#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001) - -/* Handle gamma correction. Screen_gamma=(display_exponent). - * NOTE: this API simply sets the screen and file gamma values. It will - * therefore override the value for gamma in a PNG file if it is called after - * the file header has been read - use with care - call before reading the PNG - * file for best results! - * - * These routines accept the same gamma values as png_set_alpha_mode (described - * above). The PNG_GAMMA_ defines and PNG_DEFAULT_sRGB can be passed to either - * API (floating point or fixed.) Notice, however, that the 'file_gamma' value - * is the inverse of a 'screen gamma' value. - */ -PNG_FP_EXPORT(50, void, png_set_gamma, (png_structrp png_ptr, - double screen_gamma, double override_file_gamma)) -PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structrp png_ptr, - png_fixed_point screen_gamma, png_fixed_point override_file_gamma)) -#endif - -#ifdef PNG_WRITE_FLUSH_SUPPORTED -/* Set how many lines between output flushes - 0 for no flushing */ -PNG_EXPORT(51, void, png_set_flush, (png_structrp png_ptr, int nrows)); -/* Flush the current PNG output buffer */ -PNG_EXPORT(52, void, png_write_flush, (png_structrp png_ptr)); -#endif - -/* Optional update palette with requested transformations */ -PNG_EXPORT(53, void, png_start_read_image, (png_structrp png_ptr)); - -/* Optional call to update the users info structure */ -PNG_EXPORT(54, void, png_read_update_info, (png_structrp png_ptr, - png_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read one or more rows of image data. */ -PNG_EXPORT(55, void, png_read_rows, (png_structrp png_ptr, png_bytepp row, - png_bytepp display_row, png_uint_32 num_rows)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read a row of data. */ -PNG_EXPORT(56, void, png_read_row, (png_structrp png_ptr, png_bytep row, - png_bytep display_row)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the whole image into memory at once. */ -PNG_EXPORT(57, void, png_read_image, (png_structrp png_ptr, png_bytepp image)); -#endif - -/* Write a row of image data */ -PNG_EXPORT(58, void, png_write_row, (png_structrp png_ptr, - png_const_bytep row)); - -/* Write a few rows of image data: (*row) is not written; however, the type - * is declared as writeable to maintain compatibility with previous versions - * of libpng and to allow the 'display_row' array from read_rows to be passed - * unchanged to write_rows. - */ -PNG_EXPORT(59, void, png_write_rows, (png_structrp png_ptr, png_bytepp row, - png_uint_32 num_rows)); - -/* Write the image data */ -PNG_EXPORT(60, void, png_write_image, (png_structrp png_ptr, png_bytepp image)); - -/* Write the end of the PNG file. */ -PNG_EXPORT(61, void, png_write_end, (png_structrp png_ptr, - png_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the end of the PNG file. */ -PNG_EXPORT(62, void, png_read_end, (png_structrp png_ptr, png_inforp info_ptr)); -#endif - -/* Free any memory associated with the png_info_struct */ -PNG_EXPORT(63, void, png_destroy_info_struct, (png_const_structrp png_ptr, - png_infopp info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr)); - -/* Set the libpng method of handling chunk CRC errors */ -PNG_EXPORT(66, void, png_set_crc_action, (png_structrp png_ptr, int crit_action, - int ancil_action)); - -/* Values for png_set_crc_action() say how to handle CRC errors in - * ancillary and critical chunks, and whether to use the data contained - * therein. Note that it is impossible to "discard" data in a critical - * chunk. For versions prior to 0.90, the action was always error/quit, - * whereas in version 0.90 and later, the action for CRC errors in ancillary - * chunks is warn/discard. These values should NOT be changed. - * - * value action:critical action:ancillary - */ -#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */ -#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */ -#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */ -#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */ -#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */ -#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */ - -#ifdef PNG_WRITE_SUPPORTED -/* These functions give the user control over the scan-line filtering in - * libpng and the compression methods used by zlib. These functions are - * mainly useful for testing, as the defaults should work with most users. - * Those users who are tight on memory or want faster performance at the - * expense of compression can modify them. See the compression library - * header file (zlib.h) for an explination of the compression functions. - */ - -/* Set the filtering method(s) used by libpng. Currently, the only valid - * value for "method" is 0. - */ -PNG_EXPORT(67, void, png_set_filter, (png_structrp png_ptr, int method, - int filters)); -#endif /* WRITE */ - -/* Flags for png_set_filter() to say which filters to use. The flags - * are chosen so that they don't conflict with real filter types - * below, in case they are supplied instead of the #defined constants. - * These values should NOT be changed. - */ -#define PNG_NO_FILTERS 0x00 -#define PNG_FILTER_NONE 0x08 -#define PNG_FILTER_SUB 0x10 -#define PNG_FILTER_UP 0x20 -#define PNG_FILTER_AVG 0x40 -#define PNG_FILTER_PAETH 0x80 -#define PNG_FAST_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP) -#define PNG_ALL_FILTERS (PNG_FAST_FILTERS | PNG_FILTER_AVG | PNG_FILTER_PAETH) - -/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now. - * These defines should NOT be changed. - */ -#define PNG_FILTER_VALUE_NONE 0 -#define PNG_FILTER_VALUE_SUB 1 -#define PNG_FILTER_VALUE_UP 2 -#define PNG_FILTER_VALUE_AVG 3 -#define PNG_FILTER_VALUE_PAETH 4 -#define PNG_FILTER_VALUE_LAST 5 - -#ifdef PNG_WRITE_SUPPORTED -#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */ -PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structrp png_ptr, - int heuristic_method, int num_weights, png_const_doublep filter_weights, - png_const_doublep filter_costs)) -PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed, - (png_structrp png_ptr, int heuristic_method, int num_weights, - png_const_fixed_point_p filter_weights, - png_const_fixed_point_p filter_costs)) -#endif /* WRITE_WEIGHTED_FILTER */ - -/* The following are no longer used and will be removed from libpng-1.7: */ -#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */ -#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */ -#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */ -#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */ - -/* Set the library compression level. Currently, valid values range from - * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 - * (0 - no compression, 9 - "maximal" compression). Note that tests have - * shown that zlib compression levels 3-6 usually perform as well as level 9 - * for PNG images, and do considerably fewer caclulations. In the future, - * these values may not correspond directly to the zlib compression levels. - */ -#ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED -PNG_EXPORT(69, void, png_set_compression_level, (png_structrp png_ptr, - int level)); - -PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structrp png_ptr, - int mem_level)); - -PNG_EXPORT(71, void, png_set_compression_strategy, (png_structrp png_ptr, - int strategy)); - -/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a - * smaller value of window_bits if it can do so safely. - */ -PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structrp png_ptr, - int window_bits)); - -PNG_EXPORT(73, void, png_set_compression_method, (png_structrp png_ptr, - int method)); -#endif /* WRITE_CUSTOMIZE_COMPRESSION */ - -#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED -/* Also set zlib parameters for compressing non-IDAT chunks */ -PNG_EXPORT(222, void, png_set_text_compression_level, (png_structrp png_ptr, - int level)); - -PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structrp png_ptr, - int mem_level)); - -PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structrp png_ptr, - int strategy)); - -/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a - * smaller value of window_bits if it can do so safely. - */ -PNG_EXPORT(225, void, png_set_text_compression_window_bits, - (png_structrp png_ptr, int window_bits)); - -PNG_EXPORT(226, void, png_set_text_compression_method, (png_structrp png_ptr, - int method)); -#endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */ -#endif /* WRITE */ - -/* These next functions are called for input/output, memory, and error - * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c, - * and call standard C I/O routines such as fread(), fwrite(), and - * fprintf(). These functions can be made to use other I/O routines - * at run time for those applications that need to handle I/O in a - * different manner by calling png_set_???_fn(). See libpng-manual.txt for - * more information. - */ - -#ifdef PNG_STDIO_SUPPORTED -/* Initialize the input/output for the PNG file to the default functions. */ -PNG_EXPORT(74, void, png_init_io, (png_structrp png_ptr, png_FILE_p fp)); -#endif - -/* Replace the (error and abort), and warning functions with user - * supplied functions. If no messages are to be printed you must still - * write and use replacement functions. The replacement error_fn should - * still do a longjmp to the last setjmp location if you are using this - * method of error handling. If error_fn or warning_fn is NULL, the - * default function will be used. - */ - -PNG_EXPORT(75, void, png_set_error_fn, (png_structrp png_ptr, - png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn)); - -/* Return the user pointer associated with the error functions */ -PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structrp png_ptr)); - -/* Replace the default data output functions with a user supplied one(s). - * If buffered output is not used, then output_flush_fn can be set to NULL. - * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time - * output_flush_fn will be ignored (and thus can be NULL). - * It is probably a mistake to use NULL for output_flush_fn if - * write_data_fn is not also NULL unless you have built libpng with - * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's - * default flush function, which uses the standard *FILE structure, will - * be used. - */ -PNG_EXPORT(77, void, png_set_write_fn, (png_structrp png_ptr, png_voidp io_ptr, - png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)); - -/* Replace the default data input function with a user supplied one. */ -PNG_EXPORT(78, void, png_set_read_fn, (png_structrp png_ptr, png_voidp io_ptr, - png_rw_ptr read_data_fn)); - -/* Return the user pointer associated with the I/O functions */ -PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_const_structrp png_ptr)); - -PNG_EXPORT(80, void, png_set_read_status_fn, (png_structrp png_ptr, - png_read_status_ptr read_row_fn)); - -PNG_EXPORT(81, void, png_set_write_status_fn, (png_structrp png_ptr, - png_write_status_ptr write_row_fn)); - -#ifdef PNG_USER_MEM_SUPPORTED -/* Replace the default memory allocation functions with user supplied one(s). */ -PNG_EXPORT(82, void, png_set_mem_fn, (png_structrp png_ptr, png_voidp mem_ptr, - png_malloc_ptr malloc_fn, png_free_ptr free_fn)); -/* Return the user pointer associated with the memory functions */ -PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structrp png_ptr, - png_user_transform_ptr read_user_transform_fn)); -#endif - -#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structrp png_ptr, - png_user_transform_ptr write_user_transform_fn)); -#endif - -#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED -PNG_EXPORT(86, void, png_set_user_transform_info, (png_structrp png_ptr, - png_voidp user_transform_ptr, int user_transform_depth, - int user_transform_channels)); -/* Return the user pointer associated with the user transform functions */ -PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr, - (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED -/* Return information about the row currently being processed. Note that these - * APIs do not fail but will return unexpected results if called outside a user - * transform callback. Also note that when transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structrp)); -PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structrp)); -#endif - -#ifdef PNG_READ_USER_CHUNKS_SUPPORTED -/* This callback is called only for *unknown* chunks. If - * PNG_HANDLE_AS_UNKNOWN_SUPPORTED is set then it is possible to set known - * chunks to be treated as unknown, however in this case the callback must do - * any processing required by the chunk (e.g. by calling the appropriate - * png_set_ APIs.) - * - * There is no write support - on write, by default, all the chunks in the - * 'unknown' list are written in the specified position. - * - * The integer return from the callback function is interpreted thus: - * - * negative: An error occurred; png_chunk_error will be called. - * zero: The chunk was not handled, the chunk will be saved. A critical - * chunk will cause an error at this point unless it is to be saved. - * positive: The chunk was handled, libpng will ignore/discard it. - * - * See "INTERACTION WTIH USER CHUNK CALLBACKS" below for important notes about - * how this behavior will change in libpng 1.7 - */ -PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structrp png_ptr, - png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -/* Sets the function callbacks for the push reader, and a pointer to a - * user-defined structure available to the callback functions. - */ -PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structrp png_ptr, - png_voidp progressive_ptr, png_progressive_info_ptr info_fn, - png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn)); - -/* Returns the user pointer associated with the push read functions */ -PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, - (png_const_structrp png_ptr)); - -/* Function to be called when data becomes available */ -PNG_EXPORT(92, void, png_process_data, (png_structrp png_ptr, - png_inforp info_ptr, png_bytep buffer, png_size_t buffer_size)); - -/* A function which may be called *only* within png_process_data to stop the - * processing of any more data. The function returns the number of bytes - * remaining, excluding any that libpng has cached internally. A subsequent - * call to png_process_data must supply these bytes again. If the argument - * 'save' is set to true the routine will first save all the pending data and - * will always return 0. - */ -PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structrp, int save)); - -/* A function which may be called *only* outside (after) a call to - * png_process_data. It returns the number of bytes of data to skip in the - * input. Normally it will return 0, but if it returns a non-zero value the - * application must skip than number of bytes of input data and pass the - * following data to the next call to png_process_data. - */ -PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structrp)); - -/* Function that combines rows. 'new_row' is a flag that should come from - * the callback and be non-NULL if anything needs to be done; the library - * stores its own version of the new data internally and ignores the passed - * in value. - */ -PNG_EXPORT(93, void, png_progressive_combine_row, (png_const_structrp png_ptr, - png_bytep old_row, png_const_bytep new_row)); -#endif /* PROGRESSIVE_READ */ - -PNG_EXPORTA(94, png_voidp, png_malloc, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); -/* Added at libpng version 1.4.0 */ -PNG_EXPORTA(95, png_voidp, png_calloc, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Added at libpng version 1.2.4 */ -PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Frees a pointer allocated by png_malloc() */ -PNG_EXPORT(97, void, png_free, (png_const_structrp png_ptr, png_voidp ptr)); - -/* Free data that was allocated internally */ -PNG_EXPORT(98, void, png_free_data, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 free_me, int num)); - -/* Reassign responsibility for freeing existing data, whether allocated - * by libpng or by the application; this works on the png_info structure passed - * in, it does not change the state for other png_info structures. - * - * It is unlikely that this function works correctly as of 1.6.0 and using it - * may result either in memory leaks or double free of allocated data. - */ -PNG_EXPORT(99, void, png_data_freer, (png_const_structrp png_ptr, - png_inforp info_ptr, int freer, png_uint_32 mask)); - -/* Assignments for png_data_freer */ -#define PNG_DESTROY_WILL_FREE_DATA 1 -#define PNG_SET_WILL_FREE_DATA 1 -#define PNG_USER_WILL_FREE_DATA 2 -/* Flags for png_ptr->free_me and info_ptr->free_me */ -#define PNG_FREE_HIST 0x0008U -#define PNG_FREE_ICCP 0x0010U -#define PNG_FREE_SPLT 0x0020U -#define PNG_FREE_ROWS 0x0040U -#define PNG_FREE_PCAL 0x0080U -#define PNG_FREE_SCAL 0x0100U -#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -# define PNG_FREE_UNKN 0x0200U -#endif -/* PNG_FREE_LIST 0x0400U removed in 1.6.0 because it is ignored */ -#define PNG_FREE_PLTE 0x1000U -#define PNG_FREE_TRNS 0x2000U -#define PNG_FREE_TEXT 0x4000U -#define PNG_FREE_EXIF 0x8000U /* Added at libpng-1.6.31 */ -#define PNG_FREE_ALL 0xffffU -#define PNG_FREE_MUL 0x4220U /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */ - -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED PNG_DEPRECATED); -PNG_EXPORTA(101, void, png_free_default, (png_const_structrp png_ptr, - png_voidp ptr), PNG_DEPRECATED); -#endif - -#ifdef PNG_ERROR_TEXT_SUPPORTED -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(102, void, png_error, (png_const_structrp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -/* The same, but the chunk name is prepended to the error string. */ -PNG_EXPORTA(103, void, png_chunk_error, (png_const_structrp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -#else -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(104, void, png_err, (png_const_structrp png_ptr), PNG_NORETURN); -# define png_error(s1,s2) png_err(s1) -# define png_chunk_error(s1,s2) png_err(s1) -#endif - -#ifdef PNG_WARNINGS_SUPPORTED -/* Non-fatal error in libpng. Can continue, but may have a problem. */ -PNG_EXPORT(105, void, png_warning, (png_const_structrp png_ptr, - png_const_charp warning_message)); - -/* Non-fatal error in libpng, chunk name is prepended to message. */ -PNG_EXPORT(106, void, png_chunk_warning, (png_const_structrp png_ptr, - png_const_charp warning_message)); -#else -# define png_warning(s1,s2) ((void)(s1)) -# define png_chunk_warning(s1,s2) ((void)(s1)) -#endif - -#ifdef PNG_BENIGN_ERRORS_SUPPORTED -/* Benign error in libpng. Can continue, but may have a problem. - * User can choose whether to handle as a fatal error or as a warning. */ -PNG_EXPORT(107, void, png_benign_error, (png_const_structrp png_ptr, - png_const_charp warning_message)); - -#ifdef PNG_READ_SUPPORTED -/* Same, chunk name is prepended to message (only during read) */ -PNG_EXPORT(108, void, png_chunk_benign_error, (png_const_structrp png_ptr, - png_const_charp warning_message)); -#endif - -PNG_EXPORT(109, void, png_set_benign_errors, - (png_structrp png_ptr, int allowed)); -#else -# ifdef PNG_ALLOW_BENIGN_ERRORS -# define png_benign_error png_warning -# define png_chunk_benign_error png_chunk_warning -# else -# define png_benign_error png_error -# define png_chunk_benign_error png_chunk_error -# endif -#endif - -/* The png_set_ functions are for storing values in the png_info_struct. - * Similarly, the png_get_ calls are used to read values from the - * png_info_struct, either storing the parameters in the passed variables, or - * setting pointers into the png_info_struct where the data is stored. The - * png_get_ functions return a non-zero value if the data was available - * in info_ptr, or return zero and do not change any of the parameters if the - * data was not available. - * - * These functions should be used instead of directly accessing png_info - * to avoid problems with future changes in the size and internal layout of - * png_info_struct. - */ -/* Returns "flag" if chunk data is valid in info_ptr. */ -PNG_EXPORT(110, png_uint_32, png_get_valid, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 flag)); - -/* Returns number of bytes needed to hold a transformed row. */ -PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* Returns row_pointers, which is an array of pointers to scanlines that was - * returned from png_read_png(). - */ -PNG_EXPORT(112, png_bytepp, png_get_rows, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Set row_pointers, which is an array of pointers to scanlines for use - * by png_write_png(). - */ -PNG_EXPORT(113, void, png_set_rows, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytepp row_pointers)); -#endif - -/* Returns number of color channels in image. */ -PNG_EXPORT(114, png_byte, png_get_channels, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -#ifdef PNG_EASY_ACCESS_SUPPORTED -/* Returns image width in pixels. */ -PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image height in pixels. */ -PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image bit_depth. */ -PNG_EXPORT(117, png_byte, png_get_bit_depth, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image color_type. */ -PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image filter_type. */ -PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image interlace_type. */ -PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image compression_type. */ -PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image resolution in pixels per meter, from pHYs chunk data. */ -PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -/* Returns pixel aspect ratio, computed from pHYs chunk data. */ -PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) - -/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ -PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(128, png_int_32, png_get_x_offset_microns, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(129, png_int_32, png_get_y_offset_microns, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -#endif /* EASY_ACCESS */ - -#ifdef PNG_READ_SUPPORTED -/* Returns pointer to signature string read from PNG header */ -PNG_EXPORT(130, png_const_bytep, png_get_signature, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(131, png_uint_32, png_get_bKGD, (png_const_structrp png_ptr, - png_inforp info_ptr, png_color_16p *background)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(132, void, png_set_bKGD, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_color_16p background)); -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *white_x, double *white_y, double *red_x, - double *red_y, double *green_x, double *green_y, double *blue_x, - double *blue_y)) -PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *red_X, double *red_Y, double *red_Z, - double *green_X, double *green_Y, double *green_Z, double *blue_X, - double *blue_Y, double *blue_Z)) -PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_white_x, png_fixed_point *int_white_y, - png_fixed_point *int_red_x, png_fixed_point *int_red_y, - png_fixed_point *int_green_x, png_fixed_point *int_green_y, - png_fixed_point *int_blue_x, png_fixed_point *int_blue_y)) -PNG_FIXED_EXPORT(231, png_uint_32, png_get_cHRM_XYZ_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_red_X, png_fixed_point *int_red_Y, - png_fixed_point *int_red_Z, png_fixed_point *int_green_X, - png_fixed_point *int_green_Y, png_fixed_point *int_green_Z, - png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y, - png_fixed_point *int_blue_Z)) -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(135, void, png_set_cHRM, (png_const_structrp png_ptr, - png_inforp info_ptr, - double white_x, double white_y, double red_x, double red_y, double green_x, - double green_y, double blue_x, double blue_y)) -PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_const_structrp png_ptr, - png_inforp info_ptr, double red_X, double red_Y, double red_Z, - double green_X, double green_Y, double green_Z, double blue_X, - double blue_Y, double blue_Z)) -PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_white_x, - png_fixed_point int_white_y, png_fixed_point int_red_x, - png_fixed_point int_red_y, png_fixed_point int_green_x, - png_fixed_point int_green_y, png_fixed_point int_blue_x, - png_fixed_point int_blue_y)) -PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y, - png_fixed_point int_red_Z, png_fixed_point int_green_X, - png_fixed_point int_green_Y, png_fixed_point int_green_Z, - png_fixed_point int_blue_X, png_fixed_point int_blue_Y, - png_fixed_point int_blue_Z)) -#endif - -#ifdef PNG_eXIf_SUPPORTED -PNG_EXPORT(246, png_uint_32, png_get_eXIf, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytep *exif)); -PNG_EXPORT(247, void, png_set_eXIf, (png_const_structrp png_ptr, - png_inforp info_ptr, const png_bytep exif)); - -PNG_EXPORT(248, png_uint_32, png_get_eXIf_1, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *num_exif, png_bytep *exif)); -PNG_EXPORT(249, void, png_set_eXIf_1, (png_const_structrp png_ptr, - png_inforp info_ptr, const png_uint_32 num_exif, const png_bytep exif)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *file_gamma)) -PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_file_gamma)) -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(139, void, png_set_gAMA, (png_const_structrp png_ptr, - png_inforp info_ptr, double file_gamma)) -PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_file_gamma)) -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(141, png_uint_32, png_get_hIST, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_16p *hist)); -PNG_EXPORT(142, void, png_set_hIST, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_uint_16p hist)); -#endif - -PNG_EXPORT(143, png_uint_32, png_get_IHDR, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *width, png_uint_32 *height, - int *bit_depth, int *color_type, int *interlace_method, - int *compression_method, int *filter_method)); - -PNG_EXPORT(144, void, png_set_IHDR, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, - int color_type, int interlace_method, int compression_method, - int filter_method)); - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(145, png_uint_32, png_get_oFFs, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_int_32 *offset_x, png_int_32 *offset_y, - int *unit_type)); -#endif - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(146, void, png_set_oFFs, (png_const_structrp png_ptr, - png_inforp info_ptr, png_int_32 offset_x, png_int_32 offset_y, - int unit_type)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(147, png_uint_32, png_get_pCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, png_charp *purpose, png_int_32 *X0, - png_int_32 *X1, int *type, int *nparams, png_charp *units, - png_charpp *params)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(148, void, png_set_pCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_charp purpose, png_int_32 X0, png_int_32 X1, - int type, int nparams, png_const_charp units, png_charpp params)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(149, png_uint_32, png_get_pHYs, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(150, void, png_set_pHYs, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type)); -#endif - -PNG_EXPORT(151, png_uint_32, png_get_PLTE, (png_const_structrp png_ptr, - png_inforp info_ptr, png_colorp *palette, int *num_palette)); - -PNG_EXPORT(152, void, png_set_PLTE, (png_structrp png_ptr, - png_inforp info_ptr, png_const_colorp palette, int num_palette)); - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(153, png_uint_32, png_get_sBIT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_color_8p *sig_bit)); -#endif - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(154, void, png_set_sBIT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_color_8p sig_bit)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structrp png_ptr, - png_const_inforp info_ptr, int *file_srgb_intent)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(156, void, png_set_sRGB, (png_const_structrp png_ptr, - png_inforp info_ptr, int srgb_intent)); -PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_const_structrp png_ptr, - png_inforp info_ptr, int srgb_intent)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(158, png_uint_32, png_get_iCCP, (png_const_structrp png_ptr, - png_inforp info_ptr, png_charpp name, int *compression_type, - png_bytepp profile, png_uint_32 *proflen)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(159, void, png_set_iCCP, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_charp name, int compression_type, - png_const_bytep profile, png_uint_32 proflen)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(160, int, png_get_sPLT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_sPLT_tpp entries)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(161, void, png_set_sPLT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_sPLT_tp entries, int nentries)); -#endif - -#ifdef PNG_TEXT_SUPPORTED -/* png_get_text also returns the number of text chunks in *num_text */ -PNG_EXPORT(162, int, png_get_text, (png_const_structrp png_ptr, - png_inforp info_ptr, png_textp *text_ptr, int *num_text)); -#endif - -/* Note while png_set_text() will accept a structure whose text, - * language, and translated keywords are NULL pointers, the structure - * returned by png_get_text will always contain regular - * zero-terminated C strings. They might be empty strings but - * they will never be NULL pointers. - */ - -#ifdef PNG_TEXT_SUPPORTED -PNG_EXPORT(163, void, png_set_text, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_textp text_ptr, int num_text)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(164, png_uint_32, png_get_tIME, (png_const_structrp png_ptr, - png_inforp info_ptr, png_timep *mod_time)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(165, void, png_set_tIME, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_timep mod_time)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(166, png_uint_32, png_get_tRNS, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytep *trans_alpha, int *num_trans, - png_color_16p *trans_color)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(167, void, png_set_tRNS, (png_structrp png_ptr, - png_inforp info_ptr, png_const_bytep trans_alpha, int num_trans, - png_const_color_16p trans_color)); -#endif - -#ifdef PNG_sCAL_SUPPORTED -PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL, (png_const_structrp png_ptr, - png_const_inforp info_ptr, int *unit, double *width, double *height)) -#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || \ - defined(PNG_FLOATING_POINT_SUPPORTED) -/* NOTE: this API is currently implemented using floating point arithmetic, - * consequently it can only be used on systems with floating point support. - * In any case the range of values supported by png_fixed_point is small and it - * is highly recommended that png_get_sCAL_s be used instead. - */ -PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, - png_fixed_point *width, png_fixed_point *height)) -#endif -PNG_EXPORT(169, png_uint_32, png_get_sCAL_s, - (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, - png_charpp swidth, png_charpp sheight)); - -PNG_FP_EXPORT(170, void, png_set_sCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, double width, double height)) -PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, png_fixed_point width, - png_fixed_point height)) -PNG_EXPORT(171, void, png_set_sCAL_s, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, - png_const_charp swidth, png_const_charp sheight)); -#endif /* sCAL */ - -#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED -/* Provide the default handling for all unknown chunks or, optionally, for - * specific unknown chunks. - * - * NOTE: prior to 1.6.0 the handling specified for particular chunks on read was - * ignored and the default was used, the per-chunk setting only had an effect on - * write. If you wish to have chunk-specific handling on read in code that must - * work on earlier versions you must use a user chunk callback to specify the - * desired handling (keep or discard.) - * - * The 'keep' parameter is a PNG_HANDLE_CHUNK_ value as listed below. The - * parameter is interpreted as follows: - * - * READ: - * PNG_HANDLE_CHUNK_AS_DEFAULT: - * Known chunks: do normal libpng processing, do not keep the chunk (but - * see the comments below about PNG_HANDLE_AS_UNKNOWN_SUPPORTED) - * Unknown chunks: for a specific chunk use the global default, when used - * as the default discard the chunk data. - * PNG_HANDLE_CHUNK_NEVER: - * Discard the chunk data. - * PNG_HANDLE_CHUNK_IF_SAFE: - * Keep the chunk data if the chunk is not critical else raise a chunk - * error. - * PNG_HANDLE_CHUNK_ALWAYS: - * Keep the chunk data. - * - * If the chunk data is saved it can be retrieved using png_get_unknown_chunks, - * below. Notice that specifying "AS_DEFAULT" as a global default is equivalent - * to specifying "NEVER", however when "AS_DEFAULT" is used for specific chunks - * it simply resets the behavior to the libpng default. - * - * INTERACTION WTIH USER CHUNK CALLBACKS: - * The per-chunk handling is always used when there is a png_user_chunk_ptr - * callback and the callback returns 0; the chunk is then always stored *unless* - * it is critical and the per-chunk setting is other than ALWAYS. Notice that - * the global default is *not* used in this case. (In effect the per-chunk - * value is incremented to at least IF_SAFE.) - * - * IMPORTANT NOTE: this behavior will change in libpng 1.7 - the global and - * per-chunk defaults will be honored. If you want to preserve the current - * behavior when your callback returns 0 you must set PNG_HANDLE_CHUNK_IF_SAFE - * as the default - if you don't do this libpng 1.6 will issue a warning. - * - * If you want unhandled unknown chunks to be discarded in libpng 1.6 and - * earlier simply return '1' (handled). - * - * PNG_HANDLE_AS_UNKNOWN_SUPPORTED: - * If this is *not* set known chunks will always be handled by libpng and - * will never be stored in the unknown chunk list. Known chunks listed to - * png_set_keep_unknown_chunks will have no effect. If it is set then known - * chunks listed with a keep other than AS_DEFAULT will *never* be processed - * by libpng, in addition critical chunks must either be processed by the - * callback or saved. - * - * The IHDR and IEND chunks must not be listed. Because this turns off the - * default handling for chunks that would otherwise be recognized the - * behavior of libpng transformations may well become incorrect! - * - * WRITE: - * When writing chunks the options only apply to the chunks specified by - * png_set_unknown_chunks (below), libpng will *always* write known chunks - * required by png_set_ calls and will always write the core critical chunks - * (as required for PLTE). - * - * Each chunk in the png_set_unknown_chunks list is looked up in the - * png_set_keep_unknown_chunks list to find the keep setting, this is then - * interpreted as follows: - * - * PNG_HANDLE_CHUNK_AS_DEFAULT: - * Write safe-to-copy chunks and write other chunks if the global - * default is set to _ALWAYS, otherwise don't write this chunk. - * PNG_HANDLE_CHUNK_NEVER: - * Do not write the chunk. - * PNG_HANDLE_CHUNK_IF_SAFE: - * Write the chunk if it is safe-to-copy, otherwise do not write it. - * PNG_HANDLE_CHUNK_ALWAYS: - * Write the chunk. - * - * Note that the default behavior is effectively the opposite of the read case - - * in read unknown chunks are not stored by default, in write they are written - * by default. Also the behavior of PNG_HANDLE_CHUNK_IF_SAFE is very different - * - on write the safe-to-copy bit is checked, on read the critical bit is - * checked and on read if the chunk is critical an error will be raised. - * - * num_chunks: - * =========== - * If num_chunks is positive, then the "keep" parameter specifies the manner - * for handling only those chunks appearing in the chunk_list array, - * otherwise the chunk list array is ignored. - * - * If num_chunks is 0 the "keep" parameter specifies the default behavior for - * unknown chunks, as described above. - * - * If num_chunks is negative, then the "keep" parameter specifies the manner - * for handling all unknown chunks plus all chunks recognized by libpng - * except for the IHDR, PLTE, tRNS, IDAT, and IEND chunks (which continue to - * be processed by libpng. - */ -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED -PNG_EXPORT(172, void, png_set_keep_unknown_chunks, (png_structrp png_ptr, - int keep, png_const_bytep chunk_list, int num_chunks)); -#endif /* HANDLE_AS_UNKNOWN */ - -/* The "keep" PNG_HANDLE_CHUNK_ parameter for the specified chunk is returned; - * the result is therefore true (non-zero) if special handling is required, - * false for the default handling. - */ -PNG_EXPORT(173, int, png_handle_as_unknown, (png_const_structrp png_ptr, - png_const_bytep chunk_name)); -#endif /* SET_UNKNOWN_CHUNKS */ - -#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -PNG_EXPORT(174, void, png_set_unknown_chunks, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_unknown_chunkp unknowns, - int num_unknowns)); - /* NOTE: prior to 1.6.0 this routine set the 'location' field of the added - * unknowns to the location currently stored in the png_struct. This is - * invariably the wrong value on write. To fix this call the following API - * for each chunk in the list with the correct location. If you know your - * code won't be compiled on earlier versions you can rely on - * png_set_unknown_chunks(write-ptr, png_get_unknown_chunks(read-ptr)) doing - * the correct thing. - */ - -PNG_EXPORT(175, void, png_set_unknown_chunk_location, - (png_const_structrp png_ptr, png_inforp info_ptr, int chunk, int location)); - -PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structrp png_ptr, - png_inforp info_ptr, png_unknown_chunkpp entries)); -#endif - -/* Png_free_data() will turn off the "valid" flag for anything it frees. - * If you need to turn it off for a chunk that your application has freed, - * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); - */ -PNG_EXPORT(177, void, png_set_invalid, (png_const_structrp png_ptr, - png_inforp info_ptr, int mask)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* The "params" pointer is currently not used and is for future expansion. */ -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -PNG_EXPORT(178, void, png_read_png, (png_structrp png_ptr, png_inforp info_ptr, - int transforms, png_voidp params)); -#endif -#ifdef PNG_WRITE_SUPPORTED -PNG_EXPORT(179, void, png_write_png, (png_structrp png_ptr, png_inforp info_ptr, - int transforms, png_voidp params)); -#endif -#endif - -PNG_EXPORT(180, png_const_charp, png_get_copyright, - (png_const_structrp png_ptr)); -PNG_EXPORT(181, png_const_charp, png_get_header_ver, - (png_const_structrp png_ptr)); -PNG_EXPORT(182, png_const_charp, png_get_header_version, - (png_const_structrp png_ptr)); -PNG_EXPORT(183, png_const_charp, png_get_libpng_ver, - (png_const_structrp png_ptr)); - -#ifdef PNG_MNG_FEATURES_SUPPORTED -PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structrp png_ptr, - png_uint_32 mng_features_permitted)); -#endif - -/* For use in png_set_keep_unknown, added to version 1.2.6 */ -#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 -#define PNG_HANDLE_CHUNK_NEVER 1 -#define PNG_HANDLE_CHUNK_IF_SAFE 2 -#define PNG_HANDLE_CHUNK_ALWAYS 3 -#define PNG_HANDLE_CHUNK_LAST 4 - -/* Strip the prepended error numbers ("#nnn ") from error and warning - * messages before passing them to the error or warning handler. - */ -#ifdef PNG_ERROR_NUMBERS_SUPPORTED -PNG_EXPORT(185, void, png_set_strip_error_numbers, (png_structrp png_ptr, - png_uint_32 strip_mode)); -#endif - -/* Added in libpng-1.2.6 */ -#ifdef PNG_SET_USER_LIMITS_SUPPORTED -PNG_EXPORT(186, void, png_set_user_limits, (png_structrp png_ptr, - png_uint_32 user_width_max, png_uint_32 user_height_max)); -PNG_EXPORT(187, png_uint_32, png_get_user_width_max, - (png_const_structrp png_ptr)); -PNG_EXPORT(188, png_uint_32, png_get_user_height_max, - (png_const_structrp png_ptr)); -/* Added in libpng-1.4.0 */ -PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structrp png_ptr, - png_uint_32 user_chunk_cache_max)); -PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max, - (png_const_structrp png_ptr)); -/* Added in libpng-1.4.1 */ -PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structrp png_ptr, - png_alloc_size_t user_chunk_cache_max)); -PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max, - (png_const_structrp png_ptr)); -#endif - -#if defined(PNG_INCH_CONVERSIONS_SUPPORTED) -PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_FP_EXPORT(196, float, png_get_x_offset_inches, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#endif - -PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structrp png_ptr, - png_const_inforp info_ptr)) -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#endif - -# ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -# endif /* pHYs */ -#endif /* INCH_CONVERSIONS */ - -/* Added in libpng-1.4.0 */ -#ifdef PNG_IO_STATE_SUPPORTED -PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_const_structrp png_ptr)); - -/* Removed from libpng 1.6; use png_get_io_chunk_type. */ -PNG_REMOVED(200, png_const_bytep, png_get_io_chunk_name, (png_structrp png_ptr), - PNG_DEPRECATED) - -PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type, - (png_const_structrp png_ptr)); - -/* The flags returned by png_get_io_state() are the following: */ -# define PNG_IO_NONE 0x0000 /* no I/O at this moment */ -# define PNG_IO_READING 0x0001 /* currently reading */ -# define PNG_IO_WRITING 0x0002 /* currently writing */ -# define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */ -# define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */ -# define PNG_IO_CHUNK_DATA 0x0040 /* currently at the chunk data */ -# define PNG_IO_CHUNK_CRC 0x0080 /* currently at the chunk crc */ -# define PNG_IO_MASK_OP 0x000f /* current operation: reading/writing */ -# define PNG_IO_MASK_LOC 0x00f0 /* current location: sig/hdr/data/crc */ -#endif /* IO_STATE */ - -/* Interlace support. The following macros are always defined so that if - * libpng interlace handling is turned off the macros may be used to handle - * interlaced images within the application. - */ -#define PNG_INTERLACE_ADAM7_PASSES 7 - -/* Two macros to return the first row and first column of the original, - * full, image which appears in a given pass. 'pass' is in the range 0 - * to 6 and the result is in the range 0 to 7. - */ -#define PNG_PASS_START_ROW(pass) (((1&~(pass))<<(3-((pass)>>1)))&7) -#define PNG_PASS_START_COL(pass) (((1& (pass))<<(3-(((pass)+1)>>1)))&7) - -/* A macro to return the offset between pixels in the output row for a pair of - * pixels in the input - effectively the inverse of the 'COL_SHIFT' macro that - * follows. Note that ROW_OFFSET is the offset from one row to the next whereas - * COL_OFFSET is from one column to the next, within a row. - */ -#define PNG_PASS_ROW_OFFSET(pass) ((pass)>2?(8>>(((pass)-1)>>1)):8) -#define PNG_PASS_COL_OFFSET(pass) (1<<((7-(pass))>>1)) - -/* Two macros to help evaluate the number of rows or columns in each - * pass. This is expressed as a shift - effectively log2 of the number or - * rows or columns in each 8x8 tile of the original image. - */ -#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) -#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) - -/* Hence two macros to determine the number of rows or columns in a given - * pass of an image given its height or width. In fact these macros may - * return non-zero even though the sub-image is empty, because the other - * dimension may be empty for a small image. - */ -#define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) -#define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) - -/* For the reader row callbacks (both progressive and sequential) it is - * necessary to find the row in the output image given a row in an interlaced - * image, so two more macros: - */ -#define PNG_ROW_FROM_PASS_ROW(y_in, pass) \ - (((y_in)<>(((7-(off))-(pass))<<2)) & 0xF) | \ - ((0x01145AF0>>(((7-(off))-(pass))<<2)) & 0xF0)) - -#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ - ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) -#define PNG_COL_IN_INTERLACE_PASS(x, pass) \ - ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) - -#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED -/* With these routines we avoid an integer divide, which will be slower on - * most machines. However, it does take more operations than the corresponding - * divide method, so it may be slower on a few RISC systems. There are two - * shifts (by 8 or 16 bits) and an addition, versus a single integer divide. - * - * Note that the rounding factors are NOT supposed to be the same! 128 and - * 32768 are correct for the NODIV code; 127 and 32767 are correct for the - * standard method. - * - * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ] - */ - - /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */ - -# define png_composite(composite, fg, alpha, bg) \ - { \ - png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \ - * (png_uint_16)(alpha) \ - + (png_uint_16)(bg)*(png_uint_16)(255 \ - - (png_uint_16)(alpha)) + 128); \ - (composite) = (png_byte)(((temp + (temp >> 8)) >> 8) & 0xff); \ - } - -# define png_composite_16(composite, fg, alpha, bg) \ - { \ - png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) \ - * (png_uint_32)(alpha) \ - + (png_uint_32)(bg)*(65535 \ - - (png_uint_32)(alpha)) + 32768); \ - (composite) = (png_uint_16)(0xffff & ((temp + (temp >> 16)) >> 16)); \ - } - -#else /* Standard method using integer division */ - -# define png_composite(composite, fg, alpha, bg) \ - (composite) = \ - (png_byte)(0xff & (((png_uint_16)(fg) * (png_uint_16)(alpha) + \ - (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \ - 127) / 255)) - -# define png_composite_16(composite, fg, alpha, bg) \ - (composite) = \ - (png_uint_16)(0xffff & (((png_uint_32)(fg) * (png_uint_32)(alpha) + \ - (png_uint_32)(bg)*(png_uint_32)(65535 - (png_uint_32)(alpha)) + \ - 32767) / 65535)) -#endif /* READ_COMPOSITE_NODIV */ - -#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf)); -PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf)); -PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf)); -#endif - -PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_const_structrp png_ptr, - png_const_bytep buf)); -/* No png_get_int_16 -- may be added if there's a real need for it. */ - -/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i)); -#endif -#ifdef PNG_SAVE_INT_32_SUPPORTED -PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i)); -#endif - -/* Place a 16-bit number into a buffer in PNG byte order. - * The parameter is declared unsigned int, not png_uint_16, - * just to avoid potential problems on pre-ANSI C compilers. - */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i)); -/* No png_save_int_16 -- may be added if there's a real need for it. */ -#endif - -#ifdef PNG_USE_READ_MACROS -/* Inline macros to do direct reads of bytes from the input buffer. - * The png_get_int_32() routine assumes we are using two's complement - * format for negative values, which is almost certainly true. - */ -# define PNG_get_uint_32(buf) \ - (((png_uint_32)(*(buf)) << 24) + \ - ((png_uint_32)(*((buf) + 1)) << 16) + \ - ((png_uint_32)(*((buf) + 2)) << 8) + \ - ((png_uint_32)(*((buf) + 3)))) - - /* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the - * function) incorrectly returned a value of type png_uint_32. - */ -# define PNG_get_uint_16(buf) \ - ((png_uint_16) \ - (((unsigned int)(*(buf)) << 8) + \ - ((unsigned int)(*((buf) + 1))))) - -# define PNG_get_int_32(buf) \ - ((png_int_32)((*(buf) & 0x80) \ - ? -((png_int_32)(((png_get_uint_32(buf)^0xffffffffU)+1U)&0x7fffffffU)) \ - : (png_int_32)png_get_uint_32(buf))) - -/* If PNG_PREFIX is defined the same thing as below happens in pnglibconf.h, - * but defining a macro name prefixed with PNG_PREFIX. - */ -# ifndef PNG_PREFIX -# define png_get_uint_32(buf) PNG_get_uint_32(buf) -# define png_get_uint_16(buf) PNG_get_uint_16(buf) -# define png_get_int_32(buf) PNG_get_int_32(buf) -# endif -#else -# ifdef PNG_PREFIX - /* No macros; revert to the (redefined) function */ -# define PNG_get_uint_32 (png_get_uint_32) -# define PNG_get_uint_16 (png_get_uint_16) -# define PNG_get_int_32 (png_get_int_32) -# endif -#endif - -#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED -PNG_EXPORT(242, void, png_set_check_for_invalid_index, - (png_structrp png_ptr, int allowed)); -# ifdef PNG_GET_PALETTE_MAX_SUPPORTED -PNG_EXPORT(243, int, png_get_palette_max, (png_const_structp png_ptr, - png_const_infop info_ptr)); -# endif -#endif /* CHECK_FOR_INVALID_INDEX */ - -/******************************************************************************* - * Section 5: SIMPLIFIED API - ******************************************************************************* - * - * Please read the documentation in libpng-manual.txt (TODO: write said - * documentation) if you don't understand what follows. - * - * The simplified API hides the details of both libpng and the PNG file format - * itself. It allows PNG files to be read into a very limited number of - * in-memory bitmap formats or to be written from the same formats. If these - * formats do not accomodate your needs then you can, and should, use the more - * sophisticated APIs above - these support a wide variety of in-memory formats - * and a wide variety of sophisticated transformations to those formats as well - * as a wide variety of APIs to manipulate ancillary information. - * - * To read a PNG file using the simplified API: - * - * 1) Declare a 'png_image' structure (see below) on the stack, set the - * version field to PNG_IMAGE_VERSION and the 'opaque' pointer to NULL - * (this is REQUIRED, your program may crash if you don't do it.) - * 2) Call the appropriate png_image_begin_read... function. - * 3) Set the png_image 'format' member to the required sample format. - * 4) Allocate a buffer for the image and, if required, the color-map. - * 5) Call png_image_finish_read to read the image and, if required, the - * color-map into your buffers. - * - * There are no restrictions on the format of the PNG input itself; all valid - * color types, bit depths, and interlace methods are acceptable, and the - * input image is transformed as necessary to the requested in-memory format - * during the png_image_finish_read() step. The only caveat is that if you - * request a color-mapped image from a PNG that is full-color or makes - * complex use of an alpha channel the transformation is extremely lossy and the - * result may look terrible. - * - * To write a PNG file using the simplified API: - * - * 1) Declare a 'png_image' structure on the stack and memset() it to all zero. - * 2) Initialize the members of the structure that describe the image, setting - * the 'format' member to the format of the image samples. - * 3) Call the appropriate png_image_write... function with a pointer to the - * image and, if necessary, the color-map to write the PNG data. - * - * png_image is a structure that describes the in-memory format of an image - * when it is being read or defines the in-memory format of an image that you - * need to write: - */ -#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) || \ - defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) - -#define PNG_IMAGE_VERSION 1 - -typedef struct png_control *png_controlp; -typedef struct -{ - png_controlp opaque; /* Initialize to NULL, free with png_image_free */ - png_uint_32 version; /* Set to PNG_IMAGE_VERSION */ - png_uint_32 width; /* Image width in pixels (columns) */ - png_uint_32 height; /* Image height in pixels (rows) */ - png_uint_32 format; /* Image format as defined below */ - png_uint_32 flags; /* A bit mask containing informational flags */ - png_uint_32 colormap_entries; - /* Number of entries in the color-map */ - - /* In the event of an error or warning the following field will be set to a - * non-zero value and the 'message' field will contain a '\0' terminated - * string with the libpng error or warning message. If both warnings and - * an error were encountered, only the error is recorded. If there - * are multiple warnings, only the first one is recorded. - * - * The upper 30 bits of this value are reserved, the low two bits contain - * a value as follows: - */ -# define PNG_IMAGE_WARNING 1 -# define PNG_IMAGE_ERROR 2 - /* - * The result is a two-bit code such that a value more than 1 indicates - * a failure in the API just called: - * - * 0 - no warning or error - * 1 - warning - * 2 - error - * 3 - error preceded by warning - */ -# define PNG_IMAGE_FAILED(png_cntrl) ((((png_cntrl).warning_or_error)&0x03)>1) - - png_uint_32 warning_or_error; - - char message[64]; -} png_image, *png_imagep; - -/* The samples of the image have one to four channels whose components have - * original values in the range 0 to 1.0: - * - * 1: A single gray or luminance channel (G). - * 2: A gray/luminance channel and an alpha channel (GA). - * 3: Three red, green, blue color channels (RGB). - * 4: Three color channels and an alpha channel (RGBA). - * - * The components are encoded in one of two ways: - * - * a) As a small integer, value 0..255, contained in a single byte. For the - * alpha channel the original value is simply value/255. For the color or - * luminance channels the value is encoded according to the sRGB specification - * and matches the 8-bit format expected by typical display devices. - * - * The color/gray channels are not scaled (pre-multiplied) by the alpha - * channel and are suitable for passing to color management software. - * - * b) As a value in the range 0..65535, contained in a 2-byte integer. All - * channels can be converted to the original value by dividing by 65535; all - * channels are linear. Color channels use the RGB encoding (RGB end-points) of - * the sRGB specification. This encoding is identified by the - * PNG_FORMAT_FLAG_LINEAR flag below. - * - * When the simplified API needs to convert between sRGB and linear colorspaces, - * the actual sRGB transfer curve defined in the sRGB specification (see the - * article at https://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2 - * approximation used elsewhere in libpng. - * - * When an alpha channel is present it is expected to denote pixel coverage - * of the color or luminance channels and is returned as an associated alpha - * channel: the color/gray channels are scaled (pre-multiplied) by the alpha - * value. - * - * The samples are either contained directly in the image data, between 1 and 8 - * bytes per pixel according to the encoding, or are held in a color-map indexed - * by bytes in the image data. In the case of a color-map the color-map entries - * are individual samples, encoded as above, and the image data has one byte per - * pixel to select the relevant sample from the color-map. - */ - -/* PNG_FORMAT_* - * - * #defines to be used in png_image::format. Each #define identifies a - * particular layout of sample data and, if present, alpha values. There are - * separate defines for each of the two component encodings. - * - * A format is built up using single bit flag values. All combinations are - * valid. Formats can be built up from the flag values or you can use one of - * the predefined values below. When testing formats always use the FORMAT_FLAG - * macros to test for individual features - future versions of the library may - * add new flags. - * - * When reading or writing color-mapped images the format should be set to the - * format of the entries in the color-map then png_image_{read,write}_colormap - * called to read or write the color-map and set the format correctly for the - * image data. Do not set the PNG_FORMAT_FLAG_COLORMAP bit directly! - * - * NOTE: libpng can be built with particular features disabled. If you see - * compiler errors because the definition of one of the following flags has been - * compiled out it is because libpng does not have the required support. It is - * possible, however, for the libpng configuration to enable the format on just - * read or just write; in that case you may see an error at run time. You can - * guard against this by checking for the definition of the appropriate - * "_SUPPORTED" macro, one of: - * - * PNG_SIMPLIFIED_{READ,WRITE}_{BGR,AFIRST}_SUPPORTED - */ -#define PNG_FORMAT_FLAG_ALPHA 0x01U /* format with an alpha channel */ -#define PNG_FORMAT_FLAG_COLOR 0x02U /* color format: otherwise grayscale */ -#define PNG_FORMAT_FLAG_LINEAR 0x04U /* 2-byte channels else 1-byte */ -#define PNG_FORMAT_FLAG_COLORMAP 0x08U /* image data is color-mapped */ - -#ifdef PNG_FORMAT_BGR_SUPPORTED -# define PNG_FORMAT_FLAG_BGR 0x10U /* BGR colors, else order is RGB */ -#endif - -#ifdef PNG_FORMAT_AFIRST_SUPPORTED -# define PNG_FORMAT_FLAG_AFIRST 0x20U /* alpha channel comes first */ -#endif - -#define PNG_FORMAT_FLAG_ASSOCIATED_ALPHA 0x40U /* alpha channel is associated */ - -/* Commonly used formats have predefined macros. - * - * First the single byte (sRGB) formats: - */ -#define PNG_FORMAT_GRAY 0 -#define PNG_FORMAT_GA PNG_FORMAT_FLAG_ALPHA -#define PNG_FORMAT_AG (PNG_FORMAT_GA|PNG_FORMAT_FLAG_AFIRST) -#define PNG_FORMAT_RGB PNG_FORMAT_FLAG_COLOR -#define PNG_FORMAT_BGR (PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_BGR) -#define PNG_FORMAT_RGBA (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_ARGB (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_AFIRST) -#define PNG_FORMAT_BGRA (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_ABGR (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_AFIRST) - -/* Then the linear 2-byte formats. When naming these "Y" is used to - * indicate a luminance (gray) channel. - */ -#define PNG_FORMAT_LINEAR_Y PNG_FORMAT_FLAG_LINEAR -#define PNG_FORMAT_LINEAR_Y_ALPHA (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_LINEAR_RGB (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR) -#define PNG_FORMAT_LINEAR_RGB_ALPHA \ - (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA) - -/* With color-mapped formats the image data is one byte for each pixel, the byte - * is an index into the color-map which is formatted as above. To obtain a - * color-mapped format it is sufficient just to add the PNG_FOMAT_FLAG_COLORMAP - * to one of the above definitions, or you can use one of the definitions below. - */ -#define PNG_FORMAT_RGB_COLORMAP (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_BGR_COLORMAP (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_RGBA_COLORMAP (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_ARGB_COLORMAP (PNG_FORMAT_ARGB|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_BGRA_COLORMAP (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_ABGR_COLORMAP (PNG_FORMAT_ABGR|PNG_FORMAT_FLAG_COLORMAP) - -/* PNG_IMAGE macros - * - * These are convenience macros to derive information from a png_image - * structure. The PNG_IMAGE_SAMPLE_ macros return values appropriate to the - * actual image sample values - either the entries in the color-map or the - * pixels in the image. The PNG_IMAGE_PIXEL_ macros return corresponding values - * for the pixels and will always return 1 for color-mapped formats. The - * remaining macros return information about the rows in the image and the - * complete image. - * - * NOTE: All the macros that take a png_image::format parameter are compile time - * constants if the format parameter is, itself, a constant. Therefore these - * macros can be used in array declarations and case labels where required. - * Similarly the macros are also pre-processor constants (sizeof is not used) so - * they can be used in #if tests. - * - * First the information about the samples. - */ -#define PNG_IMAGE_SAMPLE_CHANNELS(fmt)\ - (((fmt)&(PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA))+1) - /* Return the total number of channels in a given format: 1..4 */ - -#define PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)\ - ((((fmt) & PNG_FORMAT_FLAG_LINEAR) >> 2)+1) - /* Return the size in bytes of a single component of a pixel or color-map - * entry (as appropriate) in the image: 1 or 2. - */ - -#define PNG_IMAGE_SAMPLE_SIZE(fmt)\ - (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)) - /* This is the size of the sample data for one sample. If the image is - * color-mapped it is the size of one color-map entry (and image pixels are - * one byte in size), otherwise it is the size of one image pixel. - */ - -#define PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)\ - (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * 256) - /* The maximum size of the color-map required by the format expressed in a - * count of components. This can be used to compile-time allocate a - * color-map: - * - * png_uint_16 colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(linear_fmt)]; - * - * png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)]; - * - * Alternatively use the PNG_IMAGE_COLORMAP_SIZE macro below to use the - * information from one of the png_image_begin_read_ APIs and dynamically - * allocate the required memory. - */ - -/* Corresponding information about the pixels */ -#define PNG_IMAGE_PIXEL_(test,fmt)\ - (((fmt)&PNG_FORMAT_FLAG_COLORMAP)?1:test(fmt)) - -#define PNG_IMAGE_PIXEL_CHANNELS(fmt)\ - PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_CHANNELS,fmt) - /* The number of separate channels (components) in a pixel; 1 for a - * color-mapped image. - */ - -#define PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)\ - PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_COMPONENT_SIZE,fmt) - /* The size, in bytes, of each component in a pixel; 1 for a color-mapped - * image. - */ - -#define PNG_IMAGE_PIXEL_SIZE(fmt) PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_SIZE,fmt) - /* The size, in bytes, of a complete pixel; 1 for a color-mapped image. */ - -/* Information about the whole row, or whole image */ -#define PNG_IMAGE_ROW_STRIDE(image)\ - (PNG_IMAGE_PIXEL_CHANNELS((image).format) * (image).width) - /* Return the total number of components in a single row of the image; this - * is the minimum 'row stride', the minimum count of components between each - * row. For a color-mapped image this is the minimum number of bytes in a - * row. - * - * WARNING: this macro overflows for some images with more than one component - * and very large image widths. libpng will refuse to process an image where - * this macro would overflow. - */ - -#define PNG_IMAGE_BUFFER_SIZE(image, row_stride)\ - (PNG_IMAGE_PIXEL_COMPONENT_SIZE((image).format)*(image).height*(row_stride)) - /* Return the size, in bytes, of an image buffer given a png_image and a row - * stride - the number of components to leave space for in each row. - * - * WARNING: this macro overflows a 32-bit integer for some large PNG images, - * libpng will refuse to process an image where such an overflow would occur. - */ - -#define PNG_IMAGE_SIZE(image)\ - PNG_IMAGE_BUFFER_SIZE(image, PNG_IMAGE_ROW_STRIDE(image)) - /* Return the size, in bytes, of the image in memory given just a png_image; - * the row stride is the minimum stride required for the image. - */ - -#define PNG_IMAGE_COLORMAP_SIZE(image)\ - (PNG_IMAGE_SAMPLE_SIZE((image).format) * (image).colormap_entries) - /* Return the size, in bytes, of the color-map of this image. If the image - * format is not a color-map format this will return a size sufficient for - * 256 entries in the given format; check PNG_FORMAT_FLAG_COLORMAP if - * you don't want to allocate a color-map in this case. - */ - -/* PNG_IMAGE_FLAG_* - * - * Flags containing additional information about the image are held in the - * 'flags' field of png_image. - */ -#define PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB 0x01 - /* This indicates the the RGB values of the in-memory bitmap do not - * correspond to the red, green and blue end-points defined by sRGB. - */ - -#define PNG_IMAGE_FLAG_FAST 0x02 - /* On write emphasise speed over compression; the resultant PNG file will be - * larger but will be produced significantly faster, particular for large - * images. Do not use this option for images which will be distributed, only - * used it when producing intermediate files that will be read back in - * repeatedly. For a typical 24-bit image the option will double the read - * speed at the cost of increasing the image size by 25%, however for many - * more compressible images the PNG file can be 10 times larger with only a - * slight speed gain. - */ - -#define PNG_IMAGE_FLAG_16BIT_sRGB 0x04 - /* On read if the image is a 16-bit per component image and there is no gAMA - * or sRGB chunk assume that the components are sRGB encoded. Notice that - * images output by the simplified API always have gamma information; setting - * this flag only affects the interpretation of 16-bit images from an - * external source. It is recommended that the application expose this flag - * to the user; the user can normally easily recognize the difference between - * linear and sRGB encoding. This flag has no effect on write - the data - * passed to the write APIs must have the correct encoding (as defined - * above.) - * - * If the flag is not set (the default) input 16-bit per component data is - * assumed to be linear. - * - * NOTE: the flag can only be set after the png_image_begin_read_ call, - * because that call initializes the 'flags' field. - */ - -#ifdef PNG_SIMPLIFIED_READ_SUPPORTED -/* READ APIs - * --------- - * - * The png_image passed to the read APIs must have been initialized by setting - * the png_controlp field 'opaque' to NULL (or, safer, memset the whole thing.) - */ -#ifdef PNG_STDIO_SUPPORTED -PNG_EXPORT(234, int, png_image_begin_read_from_file, (png_imagep image, - const char *file_name)); - /* The named file is opened for read and the image header is filled in - * from the PNG header in the file. - */ - -PNG_EXPORT(235, int, png_image_begin_read_from_stdio, (png_imagep image, - FILE* file)); - /* The PNG header is read from the stdio FILE object. */ -#endif /* STDIO */ - -PNG_EXPORT(236, int, png_image_begin_read_from_memory, (png_imagep image, - png_const_voidp memory, png_size_t size)); - /* The PNG header is read from the given memory buffer. */ - -PNG_EXPORT(237, int, png_image_finish_read, (png_imagep image, - png_const_colorp background, void *buffer, png_int_32 row_stride, - void *colormap)); - /* Finish reading the image into the supplied buffer and clean up the - * png_image structure. - * - * row_stride is the step, in byte or 2-byte units as appropriate, - * between adjacent rows. A positive stride indicates that the top-most row - * is first in the buffer - the normal top-down arrangement. A negative - * stride indicates that the bottom-most row is first in the buffer. - * - * background need only be supplied if an alpha channel must be removed from - * a png_byte format and the removal is to be done by compositing on a solid - * color; otherwise it may be NULL and any composition will be done directly - * onto the buffer. The value is an sRGB color to use for the background, - * for grayscale output the green channel is used. - * - * background must be supplied when an alpha channel must be removed from a - * single byte color-mapped output format, in other words if: - * - * 1) The original format from png_image_begin_read_from_* had - * PNG_FORMAT_FLAG_ALPHA set. - * 2) The format set by the application does not. - * 3) The format set by the application has PNG_FORMAT_FLAG_COLORMAP set and - * PNG_FORMAT_FLAG_LINEAR *not* set. - * - * For linear output removing the alpha channel is always done by compositing - * on black and background is ignored. - * - * colormap must be supplied when PNG_FORMAT_FLAG_COLORMAP is set. It must - * be at least the size (in bytes) returned by PNG_IMAGE_COLORMAP_SIZE. - * image->colormap_entries will be updated to the actual number of entries - * written to the colormap; this may be less than the original value. - */ - -PNG_EXPORT(238, void, png_image_free, (png_imagep image)); - /* Free any data allocated by libpng in image->opaque, setting the pointer to - * NULL. May be called at any time after the structure is initialized. - */ -#endif /* SIMPLIFIED_READ */ - -#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED -/* WRITE APIS - * ---------- - * For write you must initialize a png_image structure to describe the image to - * be written. To do this use memset to set the whole structure to 0 then - * initialize fields describing your image. - * - * version: must be set to PNG_IMAGE_VERSION - * opaque: must be initialized to NULL - * width: image width in pixels - * height: image height in rows - * format: the format of the data (image and color-map) you wish to write - * flags: set to 0 unless one of the defined flags applies; set - * PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB for color format images where the RGB - * values do not correspond to the colors in sRGB. - * colormap_entries: set to the number of entries in the color-map (0 to 256) - */ -#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED -PNG_EXPORT(239, int, png_image_write_to_file, (png_imagep image, - const char *file, int convert_to_8bit, const void *buffer, - png_int_32 row_stride, const void *colormap)); - /* Write the image to the named file. */ - -PNG_EXPORT(240, int, png_image_write_to_stdio, (png_imagep image, FILE *file, - int convert_to_8_bit, const void *buffer, png_int_32 row_stride, - const void *colormap)); - /* Write the image to the given (FILE*). */ -#endif /* SIMPLIFIED_WRITE_STDIO */ - -/* With all write APIs if image is in one of the linear formats with 16-bit - * data then setting convert_to_8_bit will cause the output to be an 8-bit PNG - * gamma encoded according to the sRGB specification, otherwise a 16-bit linear - * encoded PNG file is written. - * - * With color-mapped data formats the colormap parameter point to a color-map - * with at least image->colormap_entries encoded in the specified format. If - * the format is linear the written PNG color-map will be converted to sRGB - * regardless of the convert_to_8_bit flag. - * - * With all APIs row_stride is handled as in the read APIs - it is the spacing - * from one row to the next in component sized units (1 or 2 bytes) and if - * negative indicates a bottom-up row layout in the buffer. If row_stride is - * zero, libpng will calculate it for you from the image width and number of - * channels. - * - * Note that the write API does not support interlacing, sub-8-bit pixels or - * most ancillary chunks. If you need to write text chunks (e.g. for copyright - * notices) you need to use one of the other APIs. - */ - -PNG_EXPORT(245, int, png_image_write_to_memory, (png_imagep image, void *memory, - png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8_bit, - const void *buffer, png_int_32 row_stride, const void *colormap)); - /* Write the image to the given memory buffer. The function both writes the - * whole PNG data stream to *memory and updates *memory_bytes with the count - * of bytes written. - * - * 'memory' may be NULL. In this case *memory_bytes is not read however on - * success the number of bytes which would have been written will still be - * stored in *memory_bytes. On failure *memory_bytes will contain 0. - * - * If 'memory' is not NULL it must point to memory[*memory_bytes] of - * writeable memory. - * - * If the function returns success memory[*memory_bytes] (if 'memory' is not - * NULL) contains the written PNG data. *memory_bytes will always be less - * than or equal to the original value. - * - * If the function returns false and *memory_bytes was not changed an error - * occured during write. If *memory_bytes was changed, or is not 0 if - * 'memory' was NULL, the write would have succeeded but for the memory - * buffer being too small. *memory_bytes contains the required number of - * bytes and will be bigger that the original value. - */ - -#define png_image_write_get_memory_size(image, size, convert_to_8_bit, buffer,\ - row_stride, colormap)\ - png_image_write_to_memory(&(image), 0, &(size), convert_to_8_bit, buffer,\ - row_stride, colormap) - /* Return the amount of memory in 'size' required to compress this image. - * The png_image structure 'image' must be filled in as in the above - * function and must not be changed before the actual write call, the buffer - * and all other parameters must also be identical to that in the final - * write call. The 'size' variable need not be initialized. - * - * NOTE: the macro returns true/false, if false is returned 'size' will be - * set to zero and the write failed and probably will fail if tried again. - */ - -/* You can pre-allocate the buffer by making sure it is of sufficient size - * regardless of the amount of compression achieved. The buffer size will - * always be bigger than the original image and it will never be filled. The - * following macros are provided to assist in allocating the buffer. - */ -#define PNG_IMAGE_DATA_SIZE(image) (PNG_IMAGE_SIZE(image)+(image).height) - /* The number of uncompressed bytes in the PNG byte encoding of the image; - * uncompressing the PNG IDAT data will give this number of bytes. - * - * NOTE: while PNG_IMAGE_SIZE cannot overflow for an image in memory this - * macro can because of the extra bytes used in the PNG byte encoding. You - * need to avoid this macro if your image size approaches 2^30 in width or - * height. The same goes for the remainder of these macros; they all produce - * bigger numbers than the actual in-memory image size. - */ -#ifndef PNG_ZLIB_MAX_SIZE -# define PNG_ZLIB_MAX_SIZE(b) ((b)+(((b)+7U)>>3)+(((b)+63U)>>6)+11U) - /* An upper bound on the number of compressed bytes given 'b' uncompressed - * bytes. This is based on deflateBounds() in zlib; different - * implementations of zlib compression may conceivably produce more data so - * if your zlib implementation is not zlib itself redefine this macro - * appropriately. - */ -#endif - -#define PNG_IMAGE_COMPRESSED_SIZE_MAX(image)\ - PNG_ZLIB_MAX_SIZE((png_alloc_size_t)PNG_IMAGE_DATA_SIZE(image)) - /* An upper bound on the size of the data in the PNG IDAT chunks. */ - -#define PNG_IMAGE_PNG_SIZE_MAX_(image, image_size)\ - ((8U/*sig*/+25U/*IHDR*/+16U/*gAMA*/+44U/*cHRM*/+12U/*IEND*/+\ - (((image).format&PNG_FORMAT_FLAG_COLORMAP)?/*colormap: PLTE, tRNS*/\ - 12U+3U*(image).colormap_entries/*PLTE data*/+\ - (((image).format&PNG_FORMAT_FLAG_ALPHA)?\ - 12U/*tRNS*/+(image).colormap_entries:0U):0U)+\ - 12U)+(12U*((image_size)/PNG_ZBUF_SIZE))/*IDAT*/+(image_size)) - /* A helper for the following macro; if your compiler cannot handle the - * following macro use this one with the result of - * PNG_IMAGE_COMPRESSED_SIZE_MAX(image) as the second argument (most - * compilers should handle this just fine.) - */ - -#define PNG_IMAGE_PNG_SIZE_MAX(image)\ - PNG_IMAGE_PNG_SIZE_MAX_(image, PNG_IMAGE_COMPRESSED_SIZE_MAX(image)) - /* An upper bound on the total length of the PNG data stream for 'image'. - * The result is of type png_alloc_size_t, on 32-bit systems this may - * overflow even though PNG_IMAGE_DATA_SIZE does not overflow; the write will - * run out of buffer space but return a corrected size which should work. - */ -#endif /* SIMPLIFIED_WRITE */ -/******************************************************************************* - * END OF SIMPLIFIED API - ******************************************************************************/ -#endif /* SIMPLIFIED_{READ|WRITE} */ - -/******************************************************************************* - * Section 6: IMPLEMENTATION OPTIONS - ******************************************************************************* - * - * Support for arbitrary implementation-specific optimizations. The API allows - * particular options to be turned on or off. 'Option' is the number of the - * option and 'onoff' is 0 (off) or non-0 (on). The value returned is given - * by the PNG_OPTION_ defines below. - * - * HARDWARE: normally hardware capabilites, such as the Intel SSE instructions, - * are detected at run time, however sometimes it may be impossible - * to do this in user mode, in which case it is necessary to discover - * the capabilities in an OS specific way. Such capabilities are - * listed here when libpng has support for them and must be turned - * ON by the application if present. - * - * SOFTWARE: sometimes software optimizations actually result in performance - * decrease on some architectures or systems, or with some sets of - * PNG images. 'Software' options allow such optimizations to be - * selected at run time. - */ -#ifdef PNG_SET_OPTION_SUPPORTED -#ifdef PNG_ARM_NEON_API_SUPPORTED -# define PNG_ARM_NEON 0 /* HARDWARE: ARM Neon SIMD instructions supported */ -#endif -#define PNG_MAXIMUM_INFLATE_WINDOW 2 /* SOFTWARE: force maximum window */ -#define PNG_SKIP_sRGB_CHECK_PROFILE 4 /* SOFTWARE: Check ICC profile for sRGB */ -#ifdef PNG_MIPS_MSA_API_SUPPORTED -# define PNG_MIPS_MSA 6 /* HARDWARE: MIPS Msa SIMD instructions supported */ -#endif -#define PNG_IGNORE_ADLER32 8 -#ifdef PNG_POWERPC_VSX_API_SUPPORTED -# define PNG_POWERPC_VSX 10 /* HARDWARE: PowerPC VSX SIMD instructions supported */ -#endif -#define PNG_OPTION_NEXT 12 /* Next option - numbers must be even */ - -/* Return values: NOTE: there are four values and 'off' is *not* zero */ -#define PNG_OPTION_UNSET 0 /* Unset - defaults to off */ -#define PNG_OPTION_INVALID 1 /* Option number out of range */ -#define PNG_OPTION_OFF 2 -#define PNG_OPTION_ON 3 - -PNG_EXPORT(244, int, png_set_option, (png_structrp png_ptr, int option, - int onoff)); -#endif /* SET_OPTION */ - -/******************************************************************************* - * END OF HARDWARE AND SOFTWARE OPTIONS - ******************************************************************************/ - -/* Maintainer: Put new public prototypes here ^, in libpng.3, in project - * defs, and in scripts/symbols.def. - */ - -/* The last ordinal number (this is the *last* one already used; the next - * one to use is one more than this.) - */ -#ifdef PNG_EXPORT_LAST_ORDINAL - PNG_EXPORT_LAST_ORDINAL(249); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* PNG_VERSION_INFO_ONLY */ -/* Do not put anything past this line */ -#endif /* PNG_H */ diff --git a/cdeps/mac/pngconf.h b/cdeps/mac/pngconf.h deleted file mode 100644 index d13b13e5..00000000 --- a/cdeps/mac/pngconf.h +++ /dev/null @@ -1,622 +0,0 @@ - -/* pngconf.h - machine configurable file for libpng - * - * libpng version 1.6.34, September 29, 2017 - * - * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license. - * For conditions of distribution and use, see the disclaimer - * and license in png.h - * - * Any machine specific code is near the front of this file, so if you - * are configuring libpng for a machine, you may want to read the section - * starting here down to where it starts to typedef png_color, png_text, - * and png_info. - */ - -#ifndef PNGCONF_H -#define PNGCONF_H - -#ifndef PNG_BUILDING_SYMBOL_TABLE /* else includes may cause problems */ - -/* From libpng 1.6.0 libpng requires an ANSI X3.159-1989 ("ISOC90") compliant C - * compiler for correct compilation. The following header files are required by - * the standard. If your compiler doesn't provide these header files, or they - * do not match the standard, you will need to provide/improve them. - */ -#include -#include - -/* Library header files. These header files are all defined by ISOC90; libpng - * expects conformant implementations, however, an ISOC90 conformant system need - * not provide these header files if the functionality cannot be implemented. - * In this case it will be necessary to disable the relevant parts of libpng in - * the build of pnglibconf.h. - * - * Prior to 1.6.0 string.h was included here; the API changes in 1.6.0 to not - * include this unnecessary header file. - */ - -#ifdef PNG_STDIO_SUPPORTED - /* Required for the definition of FILE: */ -# include -#endif - -#ifdef PNG_SETJMP_SUPPORTED - /* Required for the definition of jmp_buf and the declaration of longjmp: */ -# include -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED - /* Required for struct tm: */ -# include -#endif - -#endif /* PNG_BUILDING_SYMBOL_TABLE */ - -/* Prior to 1.6.0 it was possible to turn off 'const' in declarations using - * PNG_NO_CONST; this is no longer supported except for data declarations which - * apparently still cause problems in 2011 on some compilers. - */ -#define PNG_CONST const /* backward compatibility only */ - -/* This controls optimization of the reading of 16-bit and 32-bit values - * from PNG files. It can be set on a per-app-file basis - it - * just changes whether a macro is used when the function is called. - * The library builder sets the default; if read functions are not - * built into the library the macro implementation is forced on. - */ -#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED -# define PNG_USE_READ_MACROS -#endif -#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS) -# if PNG_DEFAULT_READ_MACROS -# define PNG_USE_READ_MACROS -# endif -#endif - -/* COMPILER SPECIFIC OPTIONS. - * - * These options are provided so that a variety of difficult compilers - * can be used. Some are fixed at build time (e.g. PNG_API_RULE - * below) but still have compiler specific implementations, others - * may be changed on a per-file basis when compiling against libpng. - */ - -/* The PNGARG macro was used in versions of libpng prior to 1.6.0 to protect - * against legacy (pre ISOC90) compilers that did not understand function - * prototypes. It is not required for modern C compilers. - */ -#ifndef PNGARG -# define PNGARG(arglist) arglist -#endif - -/* Function calling conventions. - * ============================= - * Normally it is not necessary to specify to the compiler how to call - * a function - it just does it - however on x86 systems derived from - * Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems - * and some others) there are multiple ways to call a function and the - * default can be changed on the compiler command line. For this reason - * libpng specifies the calling convention of every exported function and - * every function called via a user supplied function pointer. This is - * done in this file by defining the following macros: - * - * PNGAPI Calling convention for exported functions. - * PNGCBAPI Calling convention for user provided (callback) functions. - * PNGCAPI Calling convention used by the ANSI-C library (required - * for longjmp callbacks and sometimes used internally to - * specify the calling convention for zlib). - * - * These macros should never be overridden. If it is necessary to - * change calling convention in a private build this can be done - * by setting PNG_API_RULE (which defaults to 0) to one of the values - * below to select the correct 'API' variants. - * - * PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout. - * This is correct in every known environment. - * PNG_API_RULE=1 Use the operating system convention for PNGAPI and - * the 'C' calling convention (from PNGCAPI) for - * callbacks (PNGCBAPI). This is no longer required - * in any known environment - if it has to be used - * please post an explanation of the problem to the - * libpng mailing list. - * - * These cases only differ if the operating system does not use the C - * calling convention, at present this just means the above cases - * (x86 DOS/Windows sytems) and, even then, this does not apply to - * Cygwin running on those systems. - * - * Note that the value must be defined in pnglibconf.h so that what - * the application uses to call the library matches the conventions - * set when building the library. - */ - -/* Symbol export - * ============= - * When building a shared library it is almost always necessary to tell - * the compiler which symbols to export. The png.h macro 'PNG_EXPORT' - * is used to mark the symbols. On some systems these symbols can be - * extracted at link time and need no special processing by the compiler, - * on other systems the symbols are flagged by the compiler and just - * the declaration requires a special tag applied (unfortunately) in a - * compiler dependent way. Some systems can do either. - * - * A small number of older systems also require a symbol from a DLL to - * be flagged to the program that calls it. This is a problem because - * we do not know in the header file included by application code that - * the symbol will come from a shared library, as opposed to a statically - * linked one. For this reason the application must tell us by setting - * the magic flag PNG_USE_DLL to turn on the special processing before - * it includes png.h. - * - * Four additional macros are used to make this happen: - * - * PNG_IMPEXP The magic (if any) to cause a symbol to be exported from - * the build or imported if PNG_USE_DLL is set - compiler - * and system specific. - * - * PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to - * 'type', compiler specific. - * - * PNG_DLL_EXPORT Set to the magic to use during a libpng build to - * make a symbol exported from the DLL. Not used in the - * public header files; see pngpriv.h for how it is used - * in the libpng build. - * - * PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come - * from a DLL - used to define PNG_IMPEXP when - * PNG_USE_DLL is set. - */ - -/* System specific discovery. - * ========================== - * This code is used at build time to find PNG_IMPEXP, the API settings - * and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL - * import processing is possible. On Windows systems it also sets - * compiler-specific macros to the values required to change the calling - * conventions of the various functions. - */ -#if defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\ - defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) - /* Windows system (DOS doesn't support DLLs). Includes builds under Cygwin or - * MinGW on any architecture currently supported by Windows. Also includes - * Watcom builds but these need special treatment because they are not - * compatible with GCC or Visual C because of different calling conventions. - */ -# if PNG_API_RULE == 2 - /* If this line results in an error, either because __watcall is not - * understood or because of a redefine just below you cannot use *this* - * build of the library with the compiler you are using. *This* build was - * build using Watcom and applications must also be built using Watcom! - */ -# define PNGCAPI __watcall -# endif - -# if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 800)) -# define PNGCAPI __cdecl -# if PNG_API_RULE == 1 - /* If this line results in an error __stdcall is not understood and - * PNG_API_RULE should not have been set to '1'. - */ -# define PNGAPI __stdcall -# endif -# else - /* An older compiler, or one not detected (erroneously) above, - * if necessary override on the command line to get the correct - * variants for the compiler. - */ -# ifndef PNGCAPI -# define PNGCAPI _cdecl -# endif -# if PNG_API_RULE == 1 && !defined(PNGAPI) -# define PNGAPI _stdcall -# endif -# endif /* compiler/api */ - - /* NOTE: PNGCBAPI always defaults to PNGCAPI. */ - -# if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD) -# error "PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed" -# endif - -# if (defined(_MSC_VER) && _MSC_VER < 800) ||\ - (defined(__BORLANDC__) && __BORLANDC__ < 0x500) - /* older Borland and MSC - * compilers used '__export' and required this to be after - * the type. - */ -# ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) type PNG_IMPEXP -# endif -# define PNG_DLL_EXPORT __export -# else /* newer compiler */ -# define PNG_DLL_EXPORT __declspec(dllexport) -# ifndef PNG_DLL_IMPORT -# define PNG_DLL_IMPORT __declspec(dllimport) -# endif -# endif /* compiler */ - -#else /* !Windows */ -# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__) -# define PNGAPI _System -# else /* !Windows/x86 && !OS/2 */ - /* Use the defaults, or define PNG*API on the command line (but - * this will have to be done for every compile!) - */ -# endif /* other system, !OS/2 */ -#endif /* !Windows/x86 */ - -/* Now do all the defaulting . */ -#ifndef PNGCAPI -# define PNGCAPI -#endif -#ifndef PNGCBAPI -# define PNGCBAPI PNGCAPI -#endif -#ifndef PNGAPI -# define PNGAPI PNGCAPI -#endif - -/* PNG_IMPEXP may be set on the compilation system command line or (if not set) - * then in an internal header file when building the library, otherwise (when - * using the library) it is set here. - */ -#ifndef PNG_IMPEXP -# if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT) - /* This forces use of a DLL, disallowing static linking */ -# define PNG_IMPEXP PNG_DLL_IMPORT -# endif - -# ifndef PNG_IMPEXP -# define PNG_IMPEXP -# endif -#endif - -/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat - * 'attributes' as a storage class - the attributes go at the start of the - * function definition, and attributes are always appended regardless of the - * compiler. This considerably simplifies these macros but may cause problems - * if any compilers both need function attributes and fail to handle them as - * a storage class (this is unlikely.) - */ -#ifndef PNG_FUNCTION -# define PNG_FUNCTION(type, name, args, attributes) attributes type name args -#endif - -#ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) PNG_IMPEXP type -#endif - - /* The ordinal value is only relevant when preprocessing png.h for symbol - * table entries, so we discard it here. See the .dfn files in the - * scripts directory. - */ - -#ifndef PNG_EXPORTA -# define PNG_EXPORTA(ordinal, type, name, args, attributes) \ - PNG_FUNCTION(PNG_EXPORT_TYPE(type), (PNGAPI name), PNGARG(args), \ - PNG_LINKAGE_API attributes) -#endif - -/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument, - * so make something non-empty to satisfy the requirement: - */ -#define PNG_EMPTY /*empty list*/ - -#define PNG_EXPORT(ordinal, type, name, args) \ - PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY) - -/* Use PNG_REMOVED to comment out a removed interface. */ -#ifndef PNG_REMOVED -# define PNG_REMOVED(ordinal, type, name, args, attributes) -#endif - -#ifndef PNG_CALLBACK -# define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args) -#endif - -/* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. - * - * Added at libpng-1.2.41. - */ - -#ifndef PNG_NO_PEDANTIC_WARNINGS -# ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED -# define PNG_PEDANTIC_WARNINGS_SUPPORTED -# endif -#endif - -#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED - /* Support for compiler specific function attributes. These are used - * so that where compiler support is available, incorrect use of API - * functions in png.h will generate compiler warnings. Added at libpng - * version 1.2.41. Disabling these removes the warnings but may also produce - * less efficient code. - */ -# if defined(__clang__) && defined(__has_attribute) - /* Clang defines both __clang__ and __GNUC__. Check __clang__ first. */ -# if !defined(PNG_USE_RESULT) && __has_attribute(__warn_unused_result__) -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# if !defined(PNG_NORETURN) && __has_attribute(__noreturn__) -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# if !defined(PNG_ALLOCATED) && __has_attribute(__malloc__) -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif -# if !defined(PNG_DEPRECATED) && __has_attribute(__deprecated__) -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# if !defined(PNG_PRIVATE) -# ifdef __has_extension -# if __has_extension(attribute_unavailable_with_message) -# define PNG_PRIVATE __attribute__((__unavailable__(\ - "This function is not exported by libpng."))) -# endif -# endif -# endif -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif - -# elif defined(__GNUC__) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# if __GNUC__ >= 3 -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# ifndef PNG_PRIVATE -# if 0 /* Doesn't work so we use deprecated instead*/ -# define PNG_PRIVATE \ - __attribute__((warning("This function is not exported by libpng."))) -# else -# define PNG_PRIVATE \ - __attribute__((__deprecated__)) -# endif -# endif -# if ((__GNUC__ > 3) || !defined(__GNUC_MINOR__) || (__GNUC_MINOR__ >= 1)) -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif -# endif /* __GNUC__.__GNUC_MINOR__ > 3.0 */ -# endif /* __GNUC__ >= 3 */ - -# elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* not supported */ -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __declspec(noreturn) -# endif -# ifndef PNG_ALLOCATED -# if (_MSC_VER >= 1400) -# define PNG_ALLOCATED __declspec(restrict) -# endif -# endif -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __declspec(deprecated) -# endif -# ifndef PNG_PRIVATE -# define PNG_PRIVATE __declspec(deprecated) -# endif -# ifndef PNG_RESTRICT -# if (_MSC_VER >= 1400) -# define PNG_RESTRICT __restrict -# endif -# endif - -# elif defined(__WATCOMC__) -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif -# endif -#endif /* PNG_PEDANTIC_WARNINGS */ - -#ifndef PNG_DEPRECATED -# define PNG_DEPRECATED /* Use of this function is deprecated */ -#endif -#ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* The result of this function must be checked */ -#endif -#ifndef PNG_NORETURN -# define PNG_NORETURN /* This function does not return */ -#endif -#ifndef PNG_ALLOCATED -# define PNG_ALLOCATED /* The result of the function is new memory */ -#endif -#ifndef PNG_PRIVATE -# define PNG_PRIVATE /* This is a private libpng function */ -#endif -#ifndef PNG_RESTRICT -# define PNG_RESTRICT /* The C99 "restrict" feature */ -#endif - -#ifndef PNG_FP_EXPORT /* A floating point API. */ -# ifdef PNG_FLOATING_POINT_SUPPORTED -# define PNG_FP_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args); -# else /* No floating point APIs */ -# define PNG_FP_EXPORT(ordinal, type, name, args) -# endif -#endif -#ifndef PNG_FIXED_EXPORT /* A fixed point API. */ -# ifdef PNG_FIXED_POINT_SUPPORTED -# define PNG_FIXED_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args); -# else /* No fixed point APIs */ -# define PNG_FIXED_EXPORT(ordinal, type, name, args) -# endif -#endif - -#ifndef PNG_BUILDING_SYMBOL_TABLE -/* Some typedefs to get us started. These should be safe on most of the common - * platforms. - * - * png_uint_32 and png_int_32 may, currently, be larger than required to hold a - * 32-bit value however this is not normally advisable. - * - * png_uint_16 and png_int_16 should always be two bytes in size - this is - * verified at library build time. - * - * png_byte must always be one byte in size. - * - * The checks below use constants from limits.h, as defined by the ISOC90 - * standard. - */ -#if CHAR_BIT == 8 && UCHAR_MAX == 255 - typedef unsigned char png_byte; -#else -# error "libpng requires 8-bit bytes" -#endif - -#if INT_MIN == -32768 && INT_MAX == 32767 - typedef int png_int_16; -#elif SHRT_MIN == -32768 && SHRT_MAX == 32767 - typedef short png_int_16; -#else -# error "libpng requires a signed 16-bit type" -#endif - -#if UINT_MAX == 65535 - typedef unsigned int png_uint_16; -#elif USHRT_MAX == 65535 - typedef unsigned short png_uint_16; -#else -# error "libpng requires an unsigned 16-bit type" -#endif - -#if INT_MIN < -2147483646 && INT_MAX > 2147483646 - typedef int png_int_32; -#elif LONG_MIN < -2147483646 && LONG_MAX > 2147483646 - typedef long int png_int_32; -#else -# error "libpng requires a signed 32-bit (or more) type" -#endif - -#if UINT_MAX > 4294967294U - typedef unsigned int png_uint_32; -#elif ULONG_MAX > 4294967294U - typedef unsigned long int png_uint_32; -#else -# error "libpng requires an unsigned 32-bit (or more) type" -#endif - -/* Prior to 1.6.0 it was possible to disable the use of size_t, 1.6.0, however, - * requires an ISOC90 compiler and relies on consistent behavior of sizeof. - */ -typedef size_t png_size_t; -typedef ptrdiff_t png_ptrdiff_t; - -/* libpng needs to know the maximum value of 'size_t' and this controls the - * definition of png_alloc_size_t, below. This maximum value of size_t limits - * but does not control the maximum allocations the library makes - there is - * direct application control of this through png_set_user_limits(). - */ -#ifndef PNG_SMALL_SIZE_T - /* Compiler specific tests for systems where size_t is known to be less than - * 32 bits (some of these systems may no longer work because of the lack of - * 'far' support; see above.) - */ -# if (defined(__TURBOC__) && !defined(__FLAT__)) ||\ - (defined(_MSC_VER) && defined(MAXSEG_64K)) -# define PNG_SMALL_SIZE_T -# endif -#endif - -/* png_alloc_size_t is guaranteed to be no smaller than png_size_t, and no - * smaller than png_uint_32. Casts from png_size_t or png_uint_32 to - * png_alloc_size_t are not necessary; in fact, it is recommended not to use - * them at all so that the compiler can complain when something turns out to be - * problematic. - * - * Casts in the other direction (from png_alloc_size_t to png_size_t or - * png_uint_32) should be explicitly applied; however, we do not expect to - * encounter practical situations that require such conversions. - * - * PNG_SMALL_SIZE_T must be defined if the maximum value of size_t is less than - * 4294967295 - i.e. less than the maximum value of png_uint_32. - */ -#ifdef PNG_SMALL_SIZE_T - typedef png_uint_32 png_alloc_size_t; -#else - typedef png_size_t png_alloc_size_t; -#endif - -/* Prior to 1.6.0 libpng offered limited support for Microsoft C compiler - * implementations of Intel CPU specific support of user-mode segmented address - * spaces, where 16-bit pointers address more than 65536 bytes of memory using - * separate 'segment' registers. The implementation requires two different - * types of pointer (only one of which includes the segment value.) - * - * If required this support is available in version 1.2 of libpng and may be - * available in versions through 1.5, although the correctness of the code has - * not been verified recently. - */ - -/* Typedef for floating-point numbers that are converted to fixed-point with a - * multiple of 100,000, e.g., gamma - */ -typedef png_int_32 png_fixed_point; - -/* Add typedefs for pointers */ -typedef void * png_voidp; -typedef const void * png_const_voidp; -typedef png_byte * png_bytep; -typedef const png_byte * png_const_bytep; -typedef png_uint_32 * png_uint_32p; -typedef const png_uint_32 * png_const_uint_32p; -typedef png_int_32 * png_int_32p; -typedef const png_int_32 * png_const_int_32p; -typedef png_uint_16 * png_uint_16p; -typedef const png_uint_16 * png_const_uint_16p; -typedef png_int_16 * png_int_16p; -typedef const png_int_16 * png_const_int_16p; -typedef char * png_charp; -typedef const char * png_const_charp; -typedef png_fixed_point * png_fixed_point_p; -typedef const png_fixed_point * png_const_fixed_point_p; -typedef png_size_t * png_size_tp; -typedef const png_size_t * png_const_size_tp; - -#ifdef PNG_STDIO_SUPPORTED -typedef FILE * png_FILE_p; -#endif - -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double * png_doublep; -typedef const double * png_const_doublep; -#endif - -/* Pointers to pointers; i.e. arrays */ -typedef png_byte * * png_bytepp; -typedef png_uint_32 * * png_uint_32pp; -typedef png_int_32 * * png_int_32pp; -typedef png_uint_16 * * png_uint_16pp; -typedef png_int_16 * * png_int_16pp; -typedef const char * * png_const_charpp; -typedef char * * png_charpp; -typedef png_fixed_point * * png_fixed_point_pp; -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double * * png_doublepp; -#endif - -/* Pointers to pointers to pointers; i.e., pointer to array */ -typedef char * * * png_charppp; - -#endif /* PNG_BUILDING_SYMBOL_TABLE */ - -#endif /* PNGCONF_H */ diff --git a/cdeps/mac/pnglibconf.h b/cdeps/mac/pnglibconf.h deleted file mode 100644 index cb4ea9e2..00000000 --- a/cdeps/mac/pnglibconf.h +++ /dev/null @@ -1,218 +0,0 @@ -/* pnglibconf.h - library build configuration */ - -/* libpng version 1.6.34, September 29, 2017 */ - -/* Copyright (c) 1998-2017 Glenn Randers-Pehrson */ - -/* This code is released under the libpng license. */ -/* For conditions of distribution and use, see the disclaimer */ -/* and license in png.h */ - -/* pnglibconf.h */ -/* Machine generated file: DO NOT EDIT */ -/* Derived from: scripts/pnglibconf.dfa */ -#ifndef PNGLCONF_H -#define PNGLCONF_H -/* options */ -#define PNG_16BIT_SUPPORTED -#define PNG_ALIGNED_MEMORY_SUPPORTED -/*#undef PNG_ARM_NEON_API_SUPPORTED*/ -/*#undef PNG_ARM_NEON_CHECK_SUPPORTED*/ -#define PNG_BENIGN_ERRORS_SUPPORTED -#define PNG_BENIGN_READ_ERRORS_SUPPORTED -/*#undef PNG_BENIGN_WRITE_ERRORS_SUPPORTED*/ -#define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED -#define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_COLORSPACE_SUPPORTED -#define PNG_CONSOLE_IO_SUPPORTED -#define PNG_CONVERT_tIME_SUPPORTED -#define PNG_EASY_ACCESS_SUPPORTED -/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ -#define PNG_ERROR_TEXT_SUPPORTED -#define PNG_FIXED_POINT_SUPPORTED -#define PNG_FLOATING_ARITHMETIC_SUPPORTED -#define PNG_FLOATING_POINT_SUPPORTED -#define PNG_FORMAT_AFIRST_SUPPORTED -#define PNG_FORMAT_BGR_SUPPORTED -#define PNG_GAMMA_SUPPORTED -#define PNG_GET_PALETTE_MAX_SUPPORTED -#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED -#define PNG_INCH_CONVERSIONS_SUPPORTED -#define PNG_INFO_IMAGE_SUPPORTED -#define PNG_IO_STATE_SUPPORTED -#define PNG_MNG_FEATURES_SUPPORTED -#define PNG_POINTER_INDEXING_SUPPORTED -/*#undef PNG_POWERPC_VSX_API_SUPPORTED*/ -/*#undef PNG_POWERPC_VSX_CHECK_SUPPORTED*/ -#define PNG_PROGRESSIVE_READ_SUPPORTED -#define PNG_READ_16BIT_SUPPORTED -#define PNG_READ_ALPHA_MODE_SUPPORTED -#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_READ_BACKGROUND_SUPPORTED -#define PNG_READ_BGR_SUPPORTED -#define PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_READ_COMPOSITE_NODIV_SUPPORTED -#define PNG_READ_COMPRESSED_TEXT_SUPPORTED -#define PNG_READ_EXPAND_16_SUPPORTED -#define PNG_READ_EXPAND_SUPPORTED -#define PNG_READ_FILLER_SUPPORTED -#define PNG_READ_GAMMA_SUPPORTED -#define PNG_READ_GET_PALETTE_MAX_SUPPORTED -#define PNG_READ_GRAY_TO_RGB_SUPPORTED -#define PNG_READ_INTERLACING_SUPPORTED -#define PNG_READ_INT_FUNCTIONS_SUPPORTED -#define PNG_READ_INVERT_ALPHA_SUPPORTED -#define PNG_READ_INVERT_SUPPORTED -#define PNG_READ_OPT_PLTE_SUPPORTED -#define PNG_READ_PACKSWAP_SUPPORTED -#define PNG_READ_PACK_SUPPORTED -#define PNG_READ_QUANTIZE_SUPPORTED -#define PNG_READ_RGB_TO_GRAY_SUPPORTED -#define PNG_READ_SCALE_16_TO_8_SUPPORTED -#define PNG_READ_SHIFT_SUPPORTED -#define PNG_READ_STRIP_16_TO_8_SUPPORTED -#define PNG_READ_STRIP_ALPHA_SUPPORTED -#define PNG_READ_SUPPORTED -#define PNG_READ_SWAP_ALPHA_SUPPORTED -#define PNG_READ_SWAP_SUPPORTED -#define PNG_READ_TEXT_SUPPORTED -#define PNG_READ_TRANSFORMS_SUPPORTED -#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_READ_USER_CHUNKS_SUPPORTED -#define PNG_READ_USER_TRANSFORM_SUPPORTED -#define PNG_READ_bKGD_SUPPORTED -#define PNG_READ_cHRM_SUPPORTED -#define PNG_READ_eXIf_SUPPORTED -#define PNG_READ_gAMA_SUPPORTED -#define PNG_READ_hIST_SUPPORTED -#define PNG_READ_iCCP_SUPPORTED -#define PNG_READ_iTXt_SUPPORTED -#define PNG_READ_oFFs_SUPPORTED -#define PNG_READ_pCAL_SUPPORTED -#define PNG_READ_pHYs_SUPPORTED -#define PNG_READ_sBIT_SUPPORTED -#define PNG_READ_sCAL_SUPPORTED -#define PNG_READ_sPLT_SUPPORTED -#define PNG_READ_sRGB_SUPPORTED -#define PNG_READ_tEXt_SUPPORTED -#define PNG_READ_tIME_SUPPORTED -#define PNG_READ_tRNS_SUPPORTED -#define PNG_READ_zTXt_SUPPORTED -#define PNG_SAVE_INT_32_SUPPORTED -#define PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_SEQUENTIAL_READ_SUPPORTED -#define PNG_SETJMP_SUPPORTED -#define PNG_SET_OPTION_SUPPORTED -#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_SET_USER_LIMITS_SUPPORTED -#define PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED -#define PNG_SIMPLIFIED_READ_BGR_SUPPORTED -#define PNG_SIMPLIFIED_READ_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_SUPPORTED -#define PNG_STDIO_SUPPORTED -#define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_TEXT_SUPPORTED -#define PNG_TIME_RFC1123_SUPPORTED -#define PNG_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_USER_CHUNKS_SUPPORTED -#define PNG_USER_LIMITS_SUPPORTED -#define PNG_USER_MEM_SUPPORTED -#define PNG_USER_TRANSFORM_INFO_SUPPORTED -#define PNG_USER_TRANSFORM_PTR_SUPPORTED -#define PNG_WARNINGS_SUPPORTED -#define PNG_WRITE_16BIT_SUPPORTED -#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_WRITE_BGR_SUPPORTED -#define PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED -#define PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED -#define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED -#define PNG_WRITE_FILLER_SUPPORTED -#define PNG_WRITE_FILTER_SUPPORTED -#define PNG_WRITE_FLUSH_SUPPORTED -#define PNG_WRITE_GET_PALETTE_MAX_SUPPORTED -#define PNG_WRITE_INTERLACING_SUPPORTED -#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED -#define PNG_WRITE_INVERT_ALPHA_SUPPORTED -#define PNG_WRITE_INVERT_SUPPORTED -#define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED -#define PNG_WRITE_PACKSWAP_SUPPORTED -#define PNG_WRITE_PACK_SUPPORTED -#define PNG_WRITE_SHIFT_SUPPORTED -#define PNG_WRITE_SUPPORTED -#define PNG_WRITE_SWAP_ALPHA_SUPPORTED -#define PNG_WRITE_SWAP_SUPPORTED -#define PNG_WRITE_TEXT_SUPPORTED -#define PNG_WRITE_TRANSFORMS_SUPPORTED -#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_WRITE_USER_TRANSFORM_SUPPORTED -#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED -#define PNG_WRITE_bKGD_SUPPORTED -#define PNG_WRITE_cHRM_SUPPORTED -#define PNG_WRITE_eXIf_SUPPORTED -#define PNG_WRITE_gAMA_SUPPORTED -#define PNG_WRITE_hIST_SUPPORTED -#define PNG_WRITE_iCCP_SUPPORTED -#define PNG_WRITE_iTXt_SUPPORTED -#define PNG_WRITE_oFFs_SUPPORTED -#define PNG_WRITE_pCAL_SUPPORTED -#define PNG_WRITE_pHYs_SUPPORTED -#define PNG_WRITE_sBIT_SUPPORTED -#define PNG_WRITE_sCAL_SUPPORTED -#define PNG_WRITE_sPLT_SUPPORTED -#define PNG_WRITE_sRGB_SUPPORTED -#define PNG_WRITE_tEXt_SUPPORTED -#define PNG_WRITE_tIME_SUPPORTED -#define PNG_WRITE_tRNS_SUPPORTED -#define PNG_WRITE_zTXt_SUPPORTED -#define PNG_bKGD_SUPPORTED -#define PNG_cHRM_SUPPORTED -#define PNG_eXIf_SUPPORTED -#define PNG_gAMA_SUPPORTED -#define PNG_hIST_SUPPORTED -#define PNG_iCCP_SUPPORTED -#define PNG_iTXt_SUPPORTED -#define PNG_oFFs_SUPPORTED -#define PNG_pCAL_SUPPORTED -#define PNG_pHYs_SUPPORTED -#define PNG_sBIT_SUPPORTED -#define PNG_sCAL_SUPPORTED -#define PNG_sPLT_SUPPORTED -#define PNG_sRGB_SUPPORTED -#define PNG_tEXt_SUPPORTED -#define PNG_tIME_SUPPORTED -#define PNG_tRNS_SUPPORTED -#define PNG_zTXt_SUPPORTED -/* end of options */ -/* settings */ -#define PNG_API_RULE 0 -#define PNG_DEFAULT_READ_MACROS 1 -#define PNG_GAMMA_THRESHOLD_FIXED 5000 -#define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE -#define PNG_INFLATE_BUF_SIZE 1024 -#define PNG_LINKAGE_API extern -#define PNG_LINKAGE_CALLBACK extern -#define PNG_LINKAGE_DATA extern -#define PNG_LINKAGE_FUNCTION extern -#define PNG_MAX_GAMMA_8 11 -#define PNG_QUANTIZE_BLUE_BITS 5 -#define PNG_QUANTIZE_GREEN_BITS 5 -#define PNG_QUANTIZE_RED_BITS 5 -#define PNG_TEXT_Z_DEFAULT_COMPRESSION (-1) -#define PNG_TEXT_Z_DEFAULT_STRATEGY 0 -#define PNG_USER_CHUNK_CACHE_MAX 1000 -#define PNG_USER_CHUNK_MALLOC_MAX 8000000 -#define PNG_USER_HEIGHT_MAX 1000000 -#define PNG_USER_WIDTH_MAX 1000000 -#define PNG_ZBUF_SIZE 8192 -#define PNG_ZLIB_VERNUM 0x12b0 -#define PNG_Z_DEFAULT_COMPRESSION (-1) -#define PNG_Z_DEFAULT_NOFILTER_STRATEGY 0 -#define PNG_Z_DEFAULT_STRATEGY 1 -#define PNG_sCAL_PRECISION 5 -#define PNG_sRGB_PROFILE_CHECKS 2 -/* end of settings */ -#endif /* PNGLCONF_H */ diff --git a/cdeps/win32/libpng.a b/cdeps/win32/libpng.a deleted file mode 100644 index d85652f2..00000000 Binary files a/cdeps/win32/libpng.a and /dev/null differ diff --git a/cdeps/win32/png.h b/cdeps/win32/png.h deleted file mode 100755 index 9e9b46c0..00000000 --- a/cdeps/win32/png.h +++ /dev/null @@ -1,2309 +0,0 @@ - -/* png.h - header file for PNG reference library - * - * libpng version 1.5.2 - March 31, 2011 - * Copyright (c) 1998-2011 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license (See LICENSE, below) - * - * Authors and maintainers: - * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat - * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger - * libpng versions 0.97, January 1998, through 1.5.2 - March 31, 2011: Glenn - * See also "Contributing Authors", below. - * - * Note about libpng version numbers: - * - * Due to various miscommunications, unforeseen code incompatibilities - * and occasional factors outside the authors' control, version numbering - * on the library has not always been consistent and straightforward. - * The following table summarizes matters since version 0.89c, which was - * the first widely used release: - * - * source png.h png.h shared-lib - * version string int version - * ------- ------ ----- ---------- - * 0.89c "1.0 beta 3" 0.89 89 1.0.89 - * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90] - * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95] - * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96] - * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97] - * 0.97c 0.97 97 2.0.97 - * 0.98 0.98 98 2.0.98 - * 0.99 0.99 98 2.0.99 - * 0.99a-m 0.99 99 2.0.99 - * 1.00 1.00 100 2.1.0 [100 should be 10000] - * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000] - * 1.0.1 png.h string is 10001 2.1.0 - * 1.0.1a-e identical to the 10002 from here on, the shared library - * 1.0.2 source version) 10002 is 2.V where V is the source code - * 1.0.2a-b 10003 version, except as noted. - * 1.0.3 10003 - * 1.0.3a-d 10004 - * 1.0.4 10004 - * 1.0.4a-f 10005 - * 1.0.5 (+ 2 patches) 10005 - * 1.0.5a-d 10006 - * 1.0.5e-r 10100 (not source compatible) - * 1.0.5s-v 10006 (not binary compatible) - * 1.0.6 (+ 3 patches) 10006 (still binary incompatible) - * 1.0.6d-f 10007 (still binary incompatible) - * 1.0.6g 10007 - * 1.0.6h 10007 10.6h (testing xy.z so-numbering) - * 1.0.6i 10007 10.6i - * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0) - * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible) - * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible) - * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible) - * 1.0.7 1 10007 (still compatible) - * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4 - * 1.0.8rc1 1 10008 2.1.0.8rc1 - * 1.0.8 1 10008 2.1.0.8 - * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6 - * 1.0.9rc1 1 10009 2.1.0.9rc1 - * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10 - * 1.0.9rc2 1 10009 2.1.0.9rc2 - * 1.0.9 1 10009 2.1.0.9 - * 1.0.10beta1 1 10010 2.1.0.10beta1 - * 1.0.10rc1 1 10010 2.1.0.10rc1 - * 1.0.10 1 10010 2.1.0.10 - * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3 - * 1.0.11rc1 1 10011 2.1.0.11rc1 - * 1.0.11 1 10011 2.1.0.11 - * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2 - * 1.0.12rc1 2 10012 2.1.0.12rc1 - * 1.0.12 2 10012 2.1.0.12 - * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned) - * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2 - * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5 - * 1.2.0rc1 3 10200 3.1.2.0rc1 - * 1.2.0 3 10200 3.1.2.0 - * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4 - * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2 - * 1.2.1 3 10201 3.1.2.1 - * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6 - * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1 - * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1 - * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1 - * 1.0.13 10 10013 10.so.0.1.0.13 - * 1.2.2 12 10202 12.so.0.1.2.2 - * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6 - * 1.2.3 12 10203 12.so.0.1.2.3 - * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3 - * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1 - * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1 - * 1.0.14 10 10014 10.so.0.1.0.14 - * 1.2.4 13 10204 12.so.0.1.2.4 - * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2 - * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3 - * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3 - * 1.0.15 10 10015 10.so.0.1.0.15 - * 1.2.5 13 10205 12.so.0.1.2.5 - * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4 - * 1.0.16 10 10016 10.so.0.1.0.16 - * 1.2.6 13 10206 12.so.0.1.2.6 - * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2 - * 1.0.17rc1 10 10017 12.so.0.1.0.17rc1 - * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1 - * 1.0.17 10 10017 12.so.0.1.0.17 - * 1.2.7 13 10207 12.so.0.1.2.7 - * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5 - * 1.0.18rc1-5 10 10018 12.so.0.1.0.18rc1-5 - * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5 - * 1.0.18 10 10018 12.so.0.1.0.18 - * 1.2.8 13 10208 12.so.0.1.2.8 - * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3 - * 1.2.9beta4-11 13 10209 12.so.0.9[.0] - * 1.2.9rc1 13 10209 12.so.0.9[.0] - * 1.2.9 13 10209 12.so.0.9[.0] - * 1.2.10beta1-7 13 10210 12.so.0.10[.0] - * 1.2.10rc1-2 13 10210 12.so.0.10[.0] - * 1.2.10 13 10210 12.so.0.10[.0] - * 1.4.0beta1-5 14 10400 14.so.0.0[.0] - * 1.2.11beta1-4 13 10211 12.so.0.11[.0] - * 1.4.0beta7-8 14 10400 14.so.0.0[.0] - * 1.2.11 13 10211 12.so.0.11[.0] - * 1.2.12 13 10212 12.so.0.12[.0] - * 1.4.0beta9-14 14 10400 14.so.0.0[.0] - * 1.2.13 13 10213 12.so.0.13[.0] - * 1.4.0beta15-36 14 10400 14.so.0.0[.0] - * 1.4.0beta37-87 14 10400 14.so.14.0[.0] - * 1.4.0rc01 14 10400 14.so.14.0[.0] - * 1.4.0beta88-109 14 10400 14.so.14.0[.0] - * 1.4.0rc02-08 14 10400 14.so.14.0[.0] - * 1.4.0 14 10400 14.so.14.0[.0] - * 1.4.1beta01-03 14 10401 14.so.14.1[.0] - * 1.4.1rc01 14 10401 14.so.14.1[.0] - * 1.4.1beta04-12 14 10401 14.so.14.1[.0] - * 1.4.1 14 10401 14.so.14.1[.0] - * 1.4.2 14 10402 14.so.14.2[.0] - * 1.4.3 14 10403 14.so.14.3[.0] - * 1.4.4 14 10404 14.so.14.4[.0] - * 1.5.0beta01-58 15 10500 15.so.15.0[.0] - * 1.5.0rc01-07 15 10500 15.so.15.0[.0] - * 1.5.0 15 10500 15.so.15.0[.0] - * 1.5.1beta01-11 15 10501 15.so.15.1[.0] - * 1.5.1rc01-02 15 10501 15.so.15.1[.0] - * 1.5.1 15 10501 15.so.15.1[.0] - * 1.5.2beta01-03 15 10502 15.so.15.2[.0] - * 1.5.2rc01-03 15 10502 15.so.15.2[.0] - * 1.5.2 15 10502 15.so.15.2[.0] - * - * Henceforth the source version will match the shared-library major - * and minor numbers; the shared-library major version number will be - * used for changes in backward compatibility, as it is intended. The - * PNG_LIBPNG_VER macro, which is not used within libpng but is available - * for applications, is an unsigned integer of the form xyyzz corresponding - * to the source version x.y.z (leading zeros in y and z). Beta versions - * were given the previous public release number plus a letter, until - * version 1.0.6j; from then on they were given the upcoming public - * release number plus "betaNN" or "rcN". - * - * Binary incompatibility exists only when applications make direct access - * to the info_ptr or png_ptr members through png.h, and the compiled - * application is loaded with a different version of the library. - * - * DLLNUM will change each time there are forward or backward changes - * in binary compatibility (e.g., when a new feature is added). - * - * See libpng-manual.txt or libpng.3 for more information. The PNG - * specification is available as a W3C Recommendation and as an ISO - * Specification, -# endif - - /* Need the time information for converting tIME chunks, it - * defines struct tm: - */ -# ifdef PNG_CONVERT_tIME_SUPPORTED - /* "time.h" functions are not supported on all operating systems */ -# include -# endif -# endif - -/* Machine specific configuration. */ -# include "pngconf.h" -#endif - -/* - * Added at libpng-1.2.8 - * - * Ref MSDN: Private as priority over Special - * VS_FF_PRIVATEBUILD File *was not* built using standard release - * procedures. If this value is given, the StringFileInfo block must - * contain a PrivateBuild string. - * - * VS_FF_SPECIALBUILD File *was* built by the original company using - * standard release procedures but is a variation of the standard - * file of the same version number. If this value is given, the - * StringFileInfo block must contain a SpecialBuild string. - */ - -#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */ -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE) -#else -# ifdef PNG_LIBPNG_SPECIALBUILD -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL) -# else -# define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE) -# endif -#endif - -#ifndef PNG_VERSION_INFO_ONLY - -/* Inhibit C++ name-mangling for libpng functions but not for system calls. */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Version information for C files, stored in png.c. This had better match - * the version above. - */ -#define png_libpng_ver png_get_header_ver(NULL) - -/* This file is arranged in several sections: - * - * 1. Any configuration options that can be specified by for the application - * code when it is built. (Build time configuration is in pnglibconf.h) - * 2. Type definitions (base types are defined in pngconf.h), structure - * definitions. - * 3. Exported library functions. - * - * The library source code has additional files (principally pngpriv.h) that - * allow configuration of the library. - */ -/* Section 1: run time configuration - * See pnglibconf.h for build time configuration - * - * Run time configuration allows the application to choose between - * implementations of certain arithmetic APIs. The default is set - * at build time and recorded in pnglibconf.h, but it is safe to - * override these (and only these) settings. Note that this won't - * change what the library does, only application code, and the - * settings can (and probably should) be made on a per-file basis - * by setting the #defines before including png.h - * - * Use macros to read integers from PNG data or use the exported - * functions? - * PNG_USE_READ_MACROS: use the macros (see below) Note that - * the macros evaluate their argument multiple times. - * PNG_NO_USE_READ_MACROS: call the relevant library function. - * - * Use the alternative algorithm for compositing alpha samples that - * does not use division? - * PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division' - * algorithm. - * PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm. - * - * How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is - * false? - * PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error - * APIs to png_warning. - * Otherwise the calls are mapped to png_error. - */ - -/* Section 2: type definitions, including structures and compile time - * constants. - * See pngconf.h for base types that vary by machine/system - */ - -/* This triggers a compiler error in png.c, if png.c and png.h - * do not agree upon the version number. - */ -typedef char* png_libpng_version_1_5_2; - -/* Three color definitions. The order of the red, green, and blue, (and the - * exact size) is not important, although the size of the fields need to - * be png_byte or png_uint_16 (as defined below). - */ -typedef struct png_color_struct -{ - png_byte red; - png_byte green; - png_byte blue; -} png_color; -typedef png_color FAR * png_colorp; -typedef PNG_CONST png_color FAR * png_const_colorp; -typedef png_color FAR * FAR * png_colorpp; - -typedef struct png_color_16_struct -{ - png_byte index; /* used for palette files */ - png_uint_16 red; /* for use in red green blue files */ - png_uint_16 green; - png_uint_16 blue; - png_uint_16 gray; /* for use in grayscale files */ -} png_color_16; -typedef png_color_16 FAR * png_color_16p; -typedef PNG_CONST png_color_16 FAR * png_const_color_16p; -typedef png_color_16 FAR * FAR * png_color_16pp; - -typedef struct png_color_8_struct -{ - png_byte red; /* for use in red green blue files */ - png_byte green; - png_byte blue; - png_byte gray; /* for use in grayscale files */ - png_byte alpha; /* for alpha channel files */ -} png_color_8; -typedef png_color_8 FAR * png_color_8p; -typedef PNG_CONST png_color_8 FAR * png_const_color_8p; -typedef png_color_8 FAR * FAR * png_color_8pp; - -/* - * The following two structures are used for the in-core representation - * of sPLT chunks. - */ -typedef struct png_sPLT_entry_struct -{ - png_uint_16 red; - png_uint_16 green; - png_uint_16 blue; - png_uint_16 alpha; - png_uint_16 frequency; -} png_sPLT_entry; -typedef png_sPLT_entry FAR * png_sPLT_entryp; -typedef PNG_CONST png_sPLT_entry FAR * png_const_sPLT_entryp; -typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp; - -/* When the depth of the sPLT palette is 8 bits, the color and alpha samples - * occupy the LSB of their respective members, and the MSB of each member - * is zero-filled. The frequency member always occupies the full 16 bits. - */ - -typedef struct png_sPLT_struct -{ - png_charp name; /* palette name */ - png_byte depth; /* depth of palette samples */ - png_sPLT_entryp entries; /* palette entries */ - png_int_32 nentries; /* number of palette entries */ -} png_sPLT_t; -typedef png_sPLT_t FAR * png_sPLT_tp; -typedef PNG_CONST png_sPLT_t FAR * png_const_sPLT_tp; -typedef png_sPLT_t FAR * FAR * png_sPLT_tpp; - -#ifdef PNG_TEXT_SUPPORTED -/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file, - * and whether that contents is compressed or not. The "key" field - * points to a regular zero-terminated C string. The "text", "lang", and - * "lang_key" fields can be regular C strings, empty strings, or NULL pointers. - * However, the * structure returned by png_get_text() will always contain - * regular zero-terminated C strings (possibly empty), never NULL pointers, - * so they can be safely used in printf() and other string-handling functions. - */ -typedef struct png_text_struct -{ - int compression; /* compression value: - -1: tEXt, none - 0: zTXt, deflate - 1: iTXt, none - 2: iTXt, deflate */ - png_charp key; /* keyword, 1-79 character description of "text" */ - png_charp text; /* comment, may be an empty string (ie "") - or a NULL pointer */ - png_size_t text_length; /* length of the text string */ - png_size_t itxt_length; /* length of the itxt string */ - png_charp lang; /* language code, 0-79 characters - or a NULL pointer */ - png_charp lang_key; /* keyword translated UTF-8 string, 0 or more - chars or a NULL pointer */ -} png_text; -typedef png_text FAR * png_textp; -typedef PNG_CONST png_text FAR * png_const_textp; -typedef png_text FAR * FAR * png_textpp; -#endif - -/* Supported compression types for text in PNG files (tEXt, and zTXt). - * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */ -#define PNG_TEXT_COMPRESSION_NONE_WR -3 -#define PNG_TEXT_COMPRESSION_zTXt_WR -2 -#define PNG_TEXT_COMPRESSION_NONE -1 -#define PNG_TEXT_COMPRESSION_zTXt 0 -#define PNG_ITXT_COMPRESSION_NONE 1 -#define PNG_ITXT_COMPRESSION_zTXt 2 -#define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */ - -/* png_time is a way to hold the time in an machine independent way. - * Two conversions are provided, both from time_t and struct tm. There - * is no portable way to convert to either of these structures, as far - * as I know. If you know of a portable way, send it to me. As a side - * note - PNG has always been Year 2000 compliant! - */ -typedef struct png_time_struct -{ - png_uint_16 year; /* full year, as in, 1995 */ - png_byte month; /* month of year, 1 - 12 */ - png_byte day; /* day of month, 1 - 31 */ - png_byte hour; /* hour of day, 0 - 23 */ - png_byte minute; /* minute of hour, 0 - 59 */ - png_byte second; /* second of minute, 0 - 60 (for leap seconds) */ -} png_time; -typedef png_time FAR * png_timep; -typedef PNG_CONST png_time FAR * png_const_timep; -typedef png_time FAR * FAR * png_timepp; - -#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \ - defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED) -/* png_unknown_chunk is a structure to hold queued chunks for which there is - * no specific support. The idea is that we can use this to queue - * up private chunks for output even though the library doesn't actually - * know about their semantics. - */ -typedef struct png_unknown_chunk_t -{ - png_byte name[5]; - png_byte *data; - png_size_t size; - - /* libpng-using applications should NOT directly modify this byte. */ - png_byte location; /* mode of operation at read time */ -} -png_unknown_chunk; -typedef png_unknown_chunk FAR * png_unknown_chunkp; -typedef PNG_CONST png_unknown_chunk FAR * png_const_unknown_chunkp; -typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp; -#endif - -typedef struct png_info_def png_info; -typedef png_info FAR * png_infop; -typedef PNG_CONST png_info FAR * png_const_infop; -typedef png_info FAR * FAR * png_infopp; - -/* Maximum positive integer used in PNG is (2^31)-1 */ -#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL) -#define PNG_UINT_32_MAX ((png_uint_32)(-1)) -#define PNG_SIZE_MAX ((png_size_t)(-1)) - -/* These are constants for fixed point values encoded in the - * PNG specification manner (x100000) - */ -#define PNG_FP_1 100000 -#define PNG_FP_HALF 50000 - -/* These describe the color_type field in png_info. */ -/* color type masks */ -#define PNG_COLOR_MASK_PALETTE 1 -#define PNG_COLOR_MASK_COLOR 2 -#define PNG_COLOR_MASK_ALPHA 4 - -/* color types. Note that not all combinations are legal */ -#define PNG_COLOR_TYPE_GRAY 0 -#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE) -#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR) -#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA) -#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA) -/* aliases */ -#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA -#define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA - -/* This is for compression type. PNG 1.0-1.2 only define the single type. */ -#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */ -#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE - -/* This is for filter type. PNG 1.0-1.2 only define the single type. */ -#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */ -#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */ -#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE - -/* These are for the interlacing type. These values should NOT be changed. */ -#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */ -#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */ -#define PNG_INTERLACE_LAST 2 /* Not a valid value */ - -/* These are for the oFFs chunk. These values should NOT be changed. */ -#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */ -#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */ -#define PNG_OFFSET_LAST 2 /* Not a valid value */ - -/* These are for the pCAL chunk. These values should NOT be changed. */ -#define PNG_EQUATION_LINEAR 0 /* Linear transformation */ -#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */ -#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */ -#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */ -#define PNG_EQUATION_LAST 4 /* Not a valid value */ - -/* These are for the sCAL chunk. These values should NOT be changed. */ -#define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */ -#define PNG_SCALE_METER 1 /* meters per pixel */ -#define PNG_SCALE_RADIAN 2 /* radians per pixel */ -#define PNG_SCALE_LAST 3 /* Not a valid value */ - -/* These are for the pHYs chunk. These values should NOT be changed. */ -#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */ -#define PNG_RESOLUTION_METER 1 /* pixels/meter */ -#define PNG_RESOLUTION_LAST 2 /* Not a valid value */ - -/* These are for the sRGB chunk. These values should NOT be changed. */ -#define PNG_sRGB_INTENT_PERCEPTUAL 0 -#define PNG_sRGB_INTENT_RELATIVE 1 -#define PNG_sRGB_INTENT_SATURATION 2 -#define PNG_sRGB_INTENT_ABSOLUTE 3 -#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */ - -/* This is for text chunks */ -#define PNG_KEYWORD_MAX_LENGTH 79 - -/* Maximum number of entries in PLTE/sPLT/tRNS arrays */ -#define PNG_MAX_PALETTE_LENGTH 256 - -/* These determine if an ancillary chunk's data has been successfully read - * from the PNG header, or if the application has filled in the corresponding - * data in the info_struct to be written into the output file. The values - * of the PNG_INFO_ defines should NOT be changed. - */ -#define PNG_INFO_gAMA 0x0001 -#define PNG_INFO_sBIT 0x0002 -#define PNG_INFO_cHRM 0x0004 -#define PNG_INFO_PLTE 0x0008 -#define PNG_INFO_tRNS 0x0010 -#define PNG_INFO_bKGD 0x0020 -#define PNG_INFO_hIST 0x0040 -#define PNG_INFO_pHYs 0x0080 -#define PNG_INFO_oFFs 0x0100 -#define PNG_INFO_tIME 0x0200 -#define PNG_INFO_pCAL 0x0400 -#define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */ -#define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */ -#define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */ -#define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */ -#define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */ - -/* This is used for the transformation routines, as some of them - * change these values for the row. It also should enable using - * the routines for other purposes. - */ -typedef struct png_row_info_struct -{ - png_uint_32 width; /* width of row */ - png_size_t rowbytes; /* number of bytes in row */ - png_byte color_type; /* color type of row */ - png_byte bit_depth; /* bit depth of row */ - png_byte channels; /* number of channels (1, 2, 3, or 4) */ - png_byte pixel_depth; /* bits per pixel (depth * channels) */ -} png_row_info; - -typedef png_row_info FAR * png_row_infop; -typedef png_row_info FAR * FAR * png_row_infopp; - -/* These are the function types for the I/O functions and for the functions - * that allow the user to override the default I/O functions with his or her - * own. The png_error_ptr type should match that of user-supplied warning - * and error functions, while the png_rw_ptr type should match that of the - * user read/write data functions. Note that the 'write' function must not - * modify the buffer it is passed. The 'read' function, on the other hand, is - * expected to return the read data in the buffer. - */ -typedef struct png_struct_def png_struct; -typedef PNG_CONST png_struct FAR * png_const_structp; -typedef png_struct FAR * png_structp; - -typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp)); -typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t)); -typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp)); -typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32, - int)); -typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32, - int)); - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop)); -typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop)); - -/* The following callback receives png_uint_32 row_number, int pass for the - * png_bytep data of the row. When transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep, - png_uint_32, int)); -#endif - -#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ - defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) -typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop, - png_bytep)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp, - png_unknown_chunkp)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp)); -#endif - -#ifdef PNG_SETJMP_SUPPORTED -/* This must match the function definition in , and the - * application must include this before png.h to obtain the definition - * of jmp_buf. The function is required to be PNG_NORETURN. (Note that - * PNG_PTR_NORETURN is used here because current versions of the Microsoft - * C compiler do not support the PNG_NORETURN attribute on a pointer.) - * - * If you get a type warning from the compiler when linking against this line - * then your compiler has 'longjmp' that does not match the requirements of the - * compiler that built libpng. You will have to write a wrapper function for - * your compiler's longjmp and call png_set_longjmp_fn directly (not via the - * png_jmpbuf macro.) - * - * If you get a warning here while building the library you will need to make - * changes to ensure that pnglibconf.h records the calling convention used by - * your compiler. This may be very difficult - try using a different compiler - * to build the library! - */ -typedef PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), - PNG_PTR_NORETURN); -#endif - -/* Transform masks for the high-level interface */ -#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */ -#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */ -#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */ -#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */ -#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */ -#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */ -#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */ -#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */ -#define PNG_TRANSFORM_BGR 0x0080 /* read and write */ -#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */ -#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */ -#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */ -#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* write only */ -/* Added to libpng-1.2.34 */ -#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER -#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */ -/* Added to libpng-1.4.0 */ -#define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */ - -/* Flags for MNG supported features */ -#define PNG_FLAG_MNG_EMPTY_PLTE 0x01 -#define PNG_FLAG_MNG_FILTER_64 0x04 -#define PNG_ALL_MNG_FEATURES 0x05 - -/* NOTE: prior to 1.5 these functions had no 'API' style declaration, - * this allowed the zlib default functions to be used on Windows - * platforms. In 1.5 the zlib default malloc (which just calls malloc and - * ignores the first argument) should be completely compatible with the - * following. - */ -typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp, - png_alloc_size_t)); -typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp)); - -typedef png_struct FAR * FAR * png_structpp; - -/* Section 3: exported functions - * Here are the function definitions most commonly used. This is not - * the place to find out how to use libpng. See libpng-manual.txt for the - * full explanation, see example.c for the summary. This just provides - * a simple one line description of the use of each function. - * - * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in - * pngconf.h and in the *.dfn files in the scripts directory. - * - * PNG_EXPORT(ordinal, type, name, (args)); - * - * ordinal: ordinal that is used while building - * *.def files. The ordinal value is only - * relevant when preprocessing png.h with - * the *.dfn files for building symbol table - * entries, and are removed by pngconf.h. - * type: return type of the function - * name: function name - * args: function arguments, with types - * - * When we wish to append attributes to a function prototype we use - * the PNG_EXPORTA() macro instead. - * - * PNG_EXPORTA(ordinal, type, name, (args), attributes); - * - * ordinal, type, name, and args: same as in PNG_EXPORT(). - * attributes: function attributes - */ - -/* Returns the version number of the library */ -PNG_EXPORT(1, png_uint_32, png_access_version_number, (void)); - -/* Tell lib we have already handled the first magic bytes. - * Handling more than 8 bytes from the beginning of the file is an error. - */ -PNG_EXPORT(2, void, png_set_sig_bytes, (png_structp png_ptr, int num_bytes)); - -/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a - * PNG file. Returns zero if the supplied bytes match the 8-byte PNG - * signature, and non-zero otherwise. Having num_to_check == 0 or - * start > 7 will always fail (ie return non-zero). - */ -PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start, - png_size_t num_to_check)); - -/* Simple signature checking function. This is the same as calling - * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). - */ -#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n)) - -/* Allocate and initialize png_ptr struct for reading, and any other memory. */ -PNG_EXPORTA(4, png_structp, png_create_read_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warn_fn), - PNG_ALLOCATED); - -/* Allocate and initialize png_ptr struct for writing, and any other memory */ -PNG_EXPORTA(5, png_structp, png_create_write_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn), - PNG_ALLOCATED); - -PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size, - (png_const_structp png_ptr)); - -PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structp png_ptr, - png_size_t size)); - -/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp - * match up. - */ -#ifdef PNG_SETJMP_SUPPORTED -/* This function returns the jmp_buf built in to *png_ptr. It must be - * supplied with an appropriate 'longjmp' function to use on that jmp_buf - * unless the default error function is overridden in which case NULL is - * acceptable. The size of the jmp_buf is checked against the actual size - * allocated by the library - the call will return NULL on a mismatch - * indicating an ABI mismatch. - */ -PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structp png_ptr, - png_longjmp_ptr longjmp_fn, size_t jmp_buf_size)); -# define png_jmpbuf(png_ptr) \ - (*png_set_longjmp_fn((png_ptr), longjmp, sizeof (jmp_buf))) -#else -# define png_jmpbuf(png_ptr) \ - (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP) -#endif -/* This function should be used by libpng applications in place of - * longjmp(png_ptr->jmpbuf, val). If longjmp_fn() has been set, it - * will use it; otherwise it will call PNG_ABORT(). This function was - * added in libpng-1.5.0. - */ -PNG_EXPORTA(9, void, png_longjmp, (png_structp png_ptr, int val), - PNG_NORETURN); - -#ifdef PNG_READ_SUPPORTED -/* Reset the compression stream */ -PNG_EXPORT(10, int, png_reset_zstream, (png_structp png_ptr)); -#endif - -/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */ -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(11, png_structp, png_create_read_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -PNG_EXPORTA(12, png_structp, png_create_write_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -#endif - -/* Write the PNG file signature. */ -PNG_EXPORT(13, void, png_write_sig, (png_structp png_ptr)); - -/* Write a PNG chunk - size, type, (optional) data, CRC. */ -PNG_EXPORT(14, void, png_write_chunk, (png_structp png_ptr, png_const_bytep - chunk_name, png_const_bytep data, png_size_t length)); - -/* Write the start of a PNG chunk - length and chunk name. */ -PNG_EXPORT(15, void, png_write_chunk_start, (png_structp png_ptr, - png_const_bytep chunk_name, png_uint_32 length)); - -/* Write the data of a PNG chunk started with png_write_chunk_start(). */ -PNG_EXPORT(16, void, png_write_chunk_data, (png_structp png_ptr, - png_const_bytep data, png_size_t length)); - -/* Finish a chunk started with png_write_chunk_start() (includes CRC). */ -PNG_EXPORT(17, void, png_write_chunk_end, (png_structp png_ptr)); - -/* Allocate and initialize the info structure */ -PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_structp png_ptr), - PNG_ALLOCATED); - -PNG_EXPORT(19, void, png_info_init_3, (png_infopp info_ptr, - png_size_t png_info_struct_size)); - -/* Writes all the PNG information before the image. */ -PNG_EXPORT(20, void, png_write_info_before_PLTE, - (png_structp png_ptr, png_infop info_ptr)); -PNG_EXPORT(21, void, png_write_info, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the information before the actual image data. */ -PNG_EXPORT(22, void, png_read_info, - (png_structp png_ptr, png_infop info_ptr)); -#endif - -#ifdef PNG_TIME_RFC1123_SUPPORTED -PNG_EXPORT(23, png_const_charp, png_convert_to_rfc1123, - (png_structp png_ptr, - png_const_timep ptime)); -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED -/* Convert from a struct tm to png_time */ -PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime, - PNG_CONST struct tm FAR * ttime)); - -/* Convert from time_t to png_time. Uses gmtime() */ -PNG_EXPORT(25, void, png_convert_from_time_t, - (png_timep ptime, time_t ttime)); -#endif /* PNG_CONVERT_tIME_SUPPORTED */ - -#ifdef PNG_READ_EXPAND_SUPPORTED -/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */ -PNG_EXPORT(26, void, png_set_expand, (png_structp png_ptr)); -PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structp png_ptr)); -PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structp png_ptr)); -PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_EXPAND_16_SUPPORTED -/* Expand to 16 bit channels, forces conversion of palette to RGB and expansion - * of a tRNS chunk if present. - */ -PNG_EXPORT(221, void, png_set_expand_16, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) -/* Use blue, green, red order for pixels. */ -PNG_EXPORT(30, void, png_set_bgr, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED -/* Expand the grayscale to 24-bit RGB if necessary. */ -PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED -/* Reduce RGB to grayscale. */ -PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structp png_ptr, - int error_action, double red, double green)); -PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structp png_ptr, - int error_action, png_fixed_point red, png_fixed_point green)); - -PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structp - png_ptr)); -#endif - -PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth, - png_colorp palette)); - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED -PNG_EXPORT(36, void, png_set_strip_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) -PNG_EXPORT(37, void, png_set_swap_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) -PNG_EXPORT(38, void, png_set_invert_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) -/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */ -PNG_EXPORT(39, void, png_set_filler, (png_structp png_ptr, png_uint_32 filler, - int flags)); -/* The values of the PNG_FILLER_ defines should NOT be changed */ -# define PNG_FILLER_BEFORE 0 -# define PNG_FILLER_AFTER 1 -/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ -PNG_EXPORT(40, void, png_set_add_alpha, - (png_structp png_ptr, png_uint_32 filler, - int flags)); -#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */ - -#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) -/* Swap bytes in 16-bit depth files. */ -PNG_EXPORT(41, void, png_set_swap, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) -/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */ -PNG_EXPORT(42, void, png_set_packing, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \ - defined(PNG_WRITE_PACKSWAP_SUPPORTED) -/* Swap packing order of pixels in bytes. */ -PNG_EXPORT(43, void, png_set_packswap, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) -/* Converts files to legal bit depths. */ -PNG_EXPORT(44, void, png_set_shift, (png_structp png_ptr, png_const_color_8p - true_bits)); -#endif - -#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ - defined(PNG_WRITE_INTERLACING_SUPPORTED) -/* Have the code handle the interlacing. Returns the number of passes. - * MUST be called before png_read_update_info or png_start_read_image, - * otherwise it will not have the desired effect. Note that it is still - * necessary to call png_read_row or png_read_rows png_get_image_height - * times for each pass. -*/ -PNG_EXPORT(45, int, png_set_interlace_handling, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) -/* Invert monochrome files */ -PNG_EXPORT(46, void, png_set_invert_mono, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_BACKGROUND_SUPPORTED -/* Handle alpha and tRNS by replacing with a background color. */ -PNG_FP_EXPORT(47, void, png_set_background, (png_structp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, double background_gamma)); -PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, png_fixed_point background_gamma)); -#endif -#ifdef PNG_READ_BACKGROUND_SUPPORTED -# define PNG_BACKGROUND_GAMMA_UNKNOWN 0 -# define PNG_BACKGROUND_GAMMA_SCREEN 1 -# define PNG_BACKGROUND_GAMMA_FILE 2 -# define PNG_BACKGROUND_GAMMA_UNIQUE 3 -#endif - -#ifdef PNG_READ_16_TO_8_SUPPORTED -/* Strip the second byte of information from a 16-bit depth file. */ -PNG_EXPORT(48, void, png_set_strip_16, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_QUANTIZE_SUPPORTED -/* Turn on quantizing, and reduce the palette to the number of colors - * available. - */ -PNG_EXPORT(49, void, png_set_quantize, - (png_structp png_ptr, png_colorp palette, - int num_palette, int maximum_colors, png_const_uint_16p histogram, - int full_quantize)); -#endif - -#ifdef PNG_READ_GAMMA_SUPPORTED -/* The threshold on gamma processing is configurable but hard-wired into the - * library. The following is the floating point variant. - */ -#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001) - -/* Handle gamma correction. Screen_gamma=(display_exponent) */ -PNG_FP_EXPORT(50, void, png_set_gamma, - (png_structp png_ptr, double screen_gamma, - double default_file_gamma)); -PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structp png_ptr, - png_fixed_point screen_gamma, png_fixed_point default_file_gamma)); -#endif - -#ifdef PNG_WRITE_FLUSH_SUPPORTED -/* Set how many lines between output flushes - 0 for no flushing */ -PNG_EXPORT(51, void, png_set_flush, (png_structp png_ptr, int nrows)); -/* Flush the current PNG output buffer */ -PNG_EXPORT(52, void, png_write_flush, (png_structp png_ptr)); -#endif - -/* Optional update palette with requested transformations */ -PNG_EXPORT(53, void, png_start_read_image, (png_structp png_ptr)); - -/* Optional call to update the users info structure */ -PNG_EXPORT(54, void, png_read_update_info, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read one or more rows of image data. */ -PNG_EXPORT(55, void, png_read_rows, (png_structp png_ptr, png_bytepp row, - png_bytepp display_row, png_uint_32 num_rows)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read a row of data. */ -PNG_EXPORT(56, void, png_read_row, (png_structp png_ptr, png_bytep row, - png_bytep display_row)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the whole image into memory at once. */ -PNG_EXPORT(57, void, png_read_image, (png_structp png_ptr, png_bytepp image)); -#endif - -/* Write a row of image data */ -PNG_EXPORT(58, void, png_write_row, - (png_structp png_ptr, png_const_bytep row)); - -/* Write a few rows of image data: (*row) is not written; however, the type - * is declared as writeable to maintain compatibility with previous versions - * of libpng and to allow the 'display_row' array from read_rows to be passed - * unchanged to write_rows. - */ -PNG_EXPORT(59, void, png_write_rows, (png_structp png_ptr, png_bytepp row, - png_uint_32 num_rows)); - -/* Write the image data */ -PNG_EXPORT(60, void, png_write_image, - (png_structp png_ptr, png_bytepp image)); - -/* Write the end of the PNG file. */ -PNG_EXPORT(61, void, png_write_end, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the end of the PNG file. */ -PNG_EXPORT(62, void, png_read_end, (png_structp png_ptr, png_infop info_ptr)); -#endif - -/* Free any memory associated with the png_info_struct */ -PNG_EXPORT(63, void, png_destroy_info_struct, (png_structp png_ptr, - png_infopp info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr)); - -/* Set the libpng method of handling chunk CRC errors */ -PNG_EXPORT(66, void, png_set_crc_action, - (png_structp png_ptr, int crit_action, int ancil_action)); - -/* Values for png_set_crc_action() say how to handle CRC errors in - * ancillary and critical chunks, and whether to use the data contained - * therein. Note that it is impossible to "discard" data in a critical - * chunk. For versions prior to 0.90, the action was always error/quit, - * whereas in version 0.90 and later, the action for CRC errors in ancillary - * chunks is warn/discard. These values should NOT be changed. - * - * value action:critical action:ancillary - */ -#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */ -#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */ -#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */ -#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */ -#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */ -#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */ - -/* These functions give the user control over the scan-line filtering in - * libpng and the compression methods used by zlib. These functions are - * mainly useful for testing, as the defaults should work with most users. - * Those users who are tight on memory or want faster performance at the - * expense of compression can modify them. See the compression library - * header file (zlib.h) for an explination of the compression functions. - */ - -/* Set the filtering method(s) used by libpng. Currently, the only valid - * value for "method" is 0. - */ -PNG_EXPORT(67, void, png_set_filter, - (png_structp png_ptr, int method, int filters)); - -/* Flags for png_set_filter() to say which filters to use. The flags - * are chosen so that they don't conflict with real filter types - * below, in case they are supplied instead of the #defined constants. - * These values should NOT be changed. - */ -#define PNG_NO_FILTERS 0x00 -#define PNG_FILTER_NONE 0x08 -#define PNG_FILTER_SUB 0x10 -#define PNG_FILTER_UP 0x20 -#define PNG_FILTER_AVG 0x40 -#define PNG_FILTER_PAETH 0x80 -#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \ - PNG_FILTER_AVG | PNG_FILTER_PAETH) - -/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now. - * These defines should NOT be changed. - */ -#define PNG_FILTER_VALUE_NONE 0 -#define PNG_FILTER_VALUE_SUB 1 -#define PNG_FILTER_VALUE_UP 2 -#define PNG_FILTER_VALUE_AVG 3 -#define PNG_FILTER_VALUE_PAETH 4 -#define PNG_FILTER_VALUE_LAST 5 - -#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* EXPERIMENTAL */ -/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_ - * defines, either the default (minimum-sum-of-absolute-differences), or - * the experimental method (weighted-minimum-sum-of-absolute-differences). - * - * Weights are factors >= 1.0, indicating how important it is to keep the - * filter type consistent between rows. Larger numbers mean the current - * filter is that many times as likely to be the same as the "num_weights" - * previous filters. This is cumulative for each previous row with a weight. - * There needs to be "num_weights" values in "filter_weights", or it can be - * NULL if the weights aren't being specified. Weights have no influence on - * the selection of the first row filter. Well chosen weights can (in theory) - * improve the compression for a given image. - * - * Costs are factors >= 1.0 indicating the relative decoding costs of a - * filter type. Higher costs indicate more decoding expense, and are - * therefore less likely to be selected over a filter with lower computational - * costs. There needs to be a value in "filter_costs" for each valid filter - * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't - * setting the costs. Costs try to improve the speed of decompression without - * unduly increasing the compressed image size. - * - * A negative weight or cost indicates the default value is to be used, and - * values in the range [0.0, 1.0) indicate the value is to remain unchanged. - * The default values for both weights and costs are currently 1.0, but may - * change if good general weighting/cost heuristics can be found. If both - * the weights and costs are set to 1.0, this degenerates the WEIGHTED method - * to the UNWEIGHTED method, but with added encoding time/computation. - */ -PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structp png_ptr, - int heuristic_method, int num_weights, png_const_doublep filter_weights, - png_const_doublep filter_costs)); -PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed, - (png_structp png_ptr, - int heuristic_method, int num_weights, png_const_fixed_point_p - filter_weights, png_const_fixed_point_p filter_costs)); -#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */ - -/* Heuristic used for row filter selection. These defines should NOT be - * changed. - */ -#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */ -#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */ -#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */ -#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */ - -/* Set the library compression level. Currently, valid values range from - * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 - * (0 - no compression, 9 - "maximal" compression). Note that tests have - * shown that zlib compression levels 3-6 usually perform as well as level 9 - * for PNG images, and do considerably fewer caclulations. In the future, - * these values may not correspond directly to the zlib compression levels. - */ -PNG_EXPORT(69, void, png_set_compression_level, - (png_structp png_ptr, int level)); - -PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structp png_ptr, - int mem_level)); - -PNG_EXPORT(71, void, png_set_compression_strategy, (png_structp png_ptr, - int strategy)); - -PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structp png_ptr, - int window_bits)); - -PNG_EXPORT(73, void, png_set_compression_method, (png_structp png_ptr, - int method)); - -/* These next functions are called for input/output, memory, and error - * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c, - * and call standard C I/O routines such as fread(), fwrite(), and - * fprintf(). These functions can be made to use other I/O routines - * at run time for those applications that need to handle I/O in a - * different manner by calling png_set_???_fn(). See libpng-manual.txt for - * more information. - */ - -#ifdef PNG_STDIO_SUPPORTED -/* Initialize the input/output for the PNG file to the default functions. */ -PNG_EXPORT(74, void, png_init_io, (png_structp png_ptr, png_FILE_p fp)); -#endif - -/* Replace the (error and abort), and warning functions with user - * supplied functions. If no messages are to be printed you must still - * write and use replacement functions. The replacement error_fn should - * still do a longjmp to the last setjmp location if you are using this - * method of error handling. If error_fn or warning_fn is NULL, the - * default function will be used. - */ - -PNG_EXPORT(75, void, png_set_error_fn, - (png_structp png_ptr, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warning_fn)); - -/* Return the user pointer associated with the error functions */ -PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structp png_ptr)); - -/* Replace the default data output functions with a user supplied one(s). - * If buffered output is not used, then output_flush_fn can be set to NULL. - * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time - * output_flush_fn will be ignored (and thus can be NULL). - * It is probably a mistake to use NULL for output_flush_fn if - * write_data_fn is not also NULL unless you have built libpng with - * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's - * default flush function, which uses the standard *FILE structure, will - * be used. - */ -PNG_EXPORT(77, void, png_set_write_fn, (png_structp png_ptr, png_voidp io_ptr, - png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)); - -/* Replace the default data input function with a user supplied one. */ -PNG_EXPORT(78, void, png_set_read_fn, (png_structp png_ptr, png_voidp io_ptr, - png_rw_ptr read_data_fn)); - -/* Return the user pointer associated with the I/O functions */ -PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_structp png_ptr)); - -PNG_EXPORT(80, void, png_set_read_status_fn, (png_structp png_ptr, - png_read_status_ptr read_row_fn)); - -PNG_EXPORT(81, void, png_set_write_status_fn, (png_structp png_ptr, - png_write_status_ptr write_row_fn)); - -#ifdef PNG_USER_MEM_SUPPORTED -/* Replace the default memory allocation functions with user supplied one(s). */ -PNG_EXPORT(82, void, png_set_mem_fn, (png_structp png_ptr, png_voidp mem_ptr, - png_malloc_ptr malloc_fn, png_free_ptr free_fn)); -/* Return the user pointer associated with the memory functions */ -PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structp png_ptr)); -#endif - -#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structp png_ptr, - png_user_transform_ptr read_user_transform_fn)); -#endif - -#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structp png_ptr, - png_user_transform_ptr write_user_transform_fn)); -#endif - -#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED -PNG_EXPORT(86, void, png_set_user_transform_info, (png_structp png_ptr, - png_voidp user_transform_ptr, int user_transform_depth, - int user_transform_channels)); -/* Return the user pointer associated with the user transform functions */ -PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr, - (png_const_structp png_ptr)); -#endif - -#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED -/* Return information about the row currently being processed. Note that these - * APIs do not fail but will return unexpected results if called outside a user - * transform callback. Also note that when transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structp)); -PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structp)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structp png_ptr, - png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); -PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structp png_ptr)); -#endif - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -/* Sets the function callbacks for the push reader, and a pointer to a - * user-defined structure available to the callback functions. - */ -PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structp png_ptr, - png_voidp progressive_ptr, png_progressive_info_ptr info_fn, - png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn)); - -/* Returns the user pointer associated with the push read functions */ -PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, (png_const_structp png_ptr)); - -/* Function to be called when data becomes available */ -PNG_EXPORT(92, void, png_process_data, - (png_structp png_ptr, png_infop info_ptr, - png_bytep buffer, png_size_t buffer_size)); - -/* A function which may be called *only* within png_process_data to stop the - * processing of any more data. The function returns the number of bytes - * remaining, excluding any that libpng has cached internally. A subsequent - * call to png_process_data must supply these bytes again. If the argument - * 'save' is set to true the routine will first save all the pending data and - * will always return 0. - */ -PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structp, int save)); - -/* A function which may be called *only* outside (after) a call to - * png_process_data. It returns the number of bytes of data to skip in the - * input. Normally it will return 0, but if it returns a non-zero value the - * application must skip than number of bytes of input data and pass the - * following data to the next call to png_process_data. - */ -PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structp)); - -/* Function that combines rows. 'new_row' is a flag that should come from - * the callback and be non-NULL if anything needs to be done; the library - * stores its own version of the new data internally and ignores the passed - * in value. - */ -PNG_EXPORT(93, void, png_progressive_combine_row, (png_structp png_ptr, - png_bytep old_row, png_const_bytep new_row)); -#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ - -PNG_EXPORTA(94, png_voidp, png_malloc, - (png_structp png_ptr, png_alloc_size_t size), - PNG_ALLOCATED); -/* Added at libpng version 1.4.0 */ -PNG_EXPORTA(95, png_voidp, png_calloc, - (png_structp png_ptr, png_alloc_size_t size), - PNG_ALLOCATED); - -/* Added at libpng version 1.2.4 */ -PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_structp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Frees a pointer allocated by png_malloc() */ -PNG_EXPORT(97, void, png_free, (png_structp png_ptr, png_voidp ptr)); - -/* Free data that was allocated internally */ -PNG_EXPORT(98, void, png_free_data, - (png_structp png_ptr, png_infop info_ptr, png_uint_32 free_me, int num)); - -/* Reassign responsibility for freeing existing data, whether allocated - * by libpng or by the application */ -PNG_EXPORT(99, void, png_data_freer, - (png_structp png_ptr, png_infop info_ptr, int freer, png_uint_32 mask)); - -/* Assignments for png_data_freer */ -#define PNG_DESTROY_WILL_FREE_DATA 1 -#define PNG_SET_WILL_FREE_DATA 1 -#define PNG_USER_WILL_FREE_DATA 2 -/* Flags for png_ptr->free_me and info_ptr->free_me */ -#define PNG_FREE_HIST 0x0008 -#define PNG_FREE_ICCP 0x0010 -#define PNG_FREE_SPLT 0x0020 -#define PNG_FREE_ROWS 0x0040 -#define PNG_FREE_PCAL 0x0080 -#define PNG_FREE_SCAL 0x0100 -#define PNG_FREE_UNKN 0x0200 -#define PNG_FREE_LIST 0x0400 -#define PNG_FREE_PLTE 0x1000 -#define PNG_FREE_TRNS 0x2000 -#define PNG_FREE_TEXT 0x4000 -#define PNG_FREE_ALL 0x7fff -#define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */ - -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_structp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); -PNG_EXPORT(101, void, png_free_default, (png_structp png_ptr, png_voidp ptr)); -#endif - -#ifdef PNG_ERROR_TEXT_SUPPORTED -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(102, void, png_error, - (png_structp png_ptr, png_const_charp error_message), - PNG_NORETURN); - -/* The same, but the chunk name is prepended to the error string. */ -PNG_EXPORTA(103, void, png_chunk_error, (png_structp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -#else -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(104, void, png_err, (png_structp png_ptr), PNG_NORETURN); -#endif - -/* Non-fatal error in libpng. Can continue, but may have a problem. */ -PNG_EXPORT(105, void, png_warning, (png_structp png_ptr, - png_const_charp warning_message)); - -/* Non-fatal error in libpng, chunk name is prepended to message. */ -PNG_EXPORT(106, void, png_chunk_warning, (png_structp png_ptr, - png_const_charp warning_message)); - -#ifdef PNG_BENIGN_ERRORS_SUPPORTED -/* Benign error in libpng. Can continue, but may have a problem. - * User can choose whether to handle as a fatal error or as a warning. */ -# undef png_benign_error -PNG_EXPORT(107, void, png_benign_error, (png_structp png_ptr, - png_const_charp warning_message)); - -/* Same, chunk name is prepended to message. */ -# undef png_chunk_benign_error -PNG_EXPORT(108, void, png_chunk_benign_error, (png_structp png_ptr, - png_const_charp warning_message)); - -PNG_EXPORT(109, void, png_set_benign_errors, - (png_structp png_ptr, int allowed)); -#else -# ifdef PNG_ALLOW_BENIGN_ERRORS -# define png_benign_error png_warning -# define png_chunk_benign_error png_chunk_warning -# else -# define png_benign_error png_error -# define png_chunk_benign_error png_chunk_error -# endif -#endif - -/* The png_set_ functions are for storing values in the png_info_struct. - * Similarly, the png_get_ calls are used to read values from the - * png_info_struct, either storing the parameters in the passed variables, or - * setting pointers into the png_info_struct where the data is stored. The - * png_get_ functions return a non-zero value if the data was available - * in info_ptr, or return zero and do not change any of the parameters if the - * data was not available. - * - * These functions should be used instead of directly accessing png_info - * to avoid problems with future changes in the size and internal layout of - * png_info_struct. - */ -/* Returns "flag" if chunk data is valid in info_ptr. */ -PNG_EXPORT(110, png_uint_32, png_get_valid, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_32 flag)); - -/* Returns number of bytes needed to hold a transformed row. */ -PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* Returns row_pointers, which is an array of pointers to scanlines that was - * returned from png_read_png(). - */ -PNG_EXPORT(112, png_bytepp, png_get_rows, - (png_const_structp png_ptr, png_const_infop info_ptr)); -/* Set row_pointers, which is an array of pointers to scanlines for use - * by png_write_png(). - */ -PNG_EXPORT(113, void, png_set_rows, (png_structp png_ptr, - png_infop info_ptr, png_bytepp row_pointers)); -#endif - -/* Returns number of color channels in image. */ -PNG_EXPORT(114, png_byte, png_get_channels, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -#ifdef PNG_EASY_ACCESS_SUPPORTED -/* Returns image width in pixels. */ -PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image height in pixels. */ -PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image bit_depth. */ -PNG_EXPORT(117, png_byte, png_get_bit_depth, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns image color_type. */ -PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image filter_type. */ -PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image interlace_type. */ -PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image compression_type. */ -PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image resolution in pixels per meter, from pHYs chunk data. */ -PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns pixel aspect ratio, computed from pHYs chunk data. */ -PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ -PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(128, png_int_32, png_get_x_offset_microns, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(129, png_int_32, png_get_y_offset_microns, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -#endif /* PNG_EASY_ACCESS_SUPPORTED */ - -/* Returns pointer to signature string read from PNG header */ -PNG_EXPORT(130, png_const_bytep, png_get_signature, - (png_const_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(131, png_uint_32, png_get_bKGD, - (png_const_structp png_ptr, png_infop info_ptr, - png_color_16p *background)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(132, void, png_set_bKGD, (png_structp png_ptr, png_infop info_ptr, - png_const_color_16p background)); -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structp png_ptr, - png_const_infop info_ptr, double *white_x, double *white_y, double *red_x, - double *red_y, double *green_x, double *green_y, double *blue_x, - double *blue_y)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* Otherwise not implemented */ -PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed, - (png_const_structp png_ptr, - png_const_infop info_ptr, png_fixed_point *int_white_x, - png_fixed_point *int_white_y, png_fixed_point *int_red_x, - png_fixed_point *int_red_y, png_fixed_point *int_green_x, - png_fixed_point *int_green_y, png_fixed_point *int_blue_x, - png_fixed_point *int_blue_y)); -#endif -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(135, void, png_set_cHRM, - (png_structp png_ptr, png_infop info_ptr, - double white_x, double white_y, double red_x, double red_y, double green_x, - double green_y, double blue_x, double blue_y)); -PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_structp png_ptr, - png_infop info_ptr, png_fixed_point int_white_x, - png_fixed_point int_white_y, png_fixed_point int_red_x, - png_fixed_point int_red_y, png_fixed_point int_green_x, - png_fixed_point int_green_y, png_fixed_point int_blue_x, - png_fixed_point int_blue_y)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, - (png_const_structp png_ptr, png_const_infop info_ptr, - double *file_gamma)); -PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_fixed_point *int_file_gamma)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(139, void, png_set_gAMA, (png_structp png_ptr, - png_infop info_ptr, double file_gamma)); -PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_structp png_ptr, - png_infop info_ptr, png_fixed_point int_file_gamma)); -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(141, png_uint_32, png_get_hIST, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_16p *hist)); -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(142, void, png_set_hIST, (png_structp png_ptr, - png_infop info_ptr, png_const_uint_16p hist)); -#endif - -PNG_EXPORT(143, png_uint_32, png_get_IHDR, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, - int *interlace_method, int *compression_method, int *filter_method)); - -PNG_EXPORT(144, void, png_set_IHDR, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, - int interlace_method, int compression_method, int filter_method)); - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(145, png_uint_32, png_get_oFFs, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)); -#endif - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(146, void, png_set_oFFs, - (png_structp png_ptr, png_infop info_ptr, - png_int_32 offset_x, png_int_32 offset_y, int unit_type)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(147, png_uint_32, png_get_pCAL, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, - int *nparams, - png_charp *units, png_charpp *params)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(148, void, png_set_pCAL, (png_structp png_ptr, - png_infop info_ptr, - png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type, - int nparams, png_const_charp units, png_charpp params)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(149, png_uint_32, png_get_pHYs, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(150, void, png_set_pHYs, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 res_x, png_uint_32 res_y, int unit_type)); -#endif - -PNG_EXPORT(151, png_uint_32, png_get_PLTE, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_colorp *palette, int *num_palette)); - -PNG_EXPORT(152, void, png_set_PLTE, - (png_structp png_ptr, png_infop info_ptr, - png_const_colorp palette, int num_palette)); - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(153, png_uint_32, png_get_sBIT, - (png_const_structp png_ptr, png_infop info_ptr, - png_color_8p *sig_bit)); -#endif - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(154, void, png_set_sBIT, - (png_structp png_ptr, png_infop info_ptr, png_const_color_8p sig_bit)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structp png_ptr, - png_const_infop info_ptr, int *file_srgb_intent)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(156, void, png_set_sRGB, - (png_structp png_ptr, png_infop info_ptr, int srgb_intent)); -PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_structp png_ptr, - png_infop info_ptr, int srgb_intent)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(158, png_uint_32, png_get_iCCP, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_charpp name, int *compression_type, png_bytepp profile, - png_uint_32 *proflen)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(159, void, png_set_iCCP, - (png_structp png_ptr, png_infop info_ptr, - png_const_charp name, int compression_type, png_const_bytep profile, - png_uint_32 proflen)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(160, png_uint_32, png_get_sPLT, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_sPLT_tpp entries)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(161, void, png_set_sPLT, - (png_structp png_ptr, png_infop info_ptr, - png_const_sPLT_tp entries, int nentries)); -#endif - -#ifdef PNG_TEXT_SUPPORTED -/* png_get_text also returns the number of text chunks in *num_text */ -PNG_EXPORT(162, png_uint_32, png_get_text, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_textp *text_ptr, int *num_text)); -#endif - -/* Note while png_set_text() will accept a structure whose text, - * language, and translated keywords are NULL pointers, the structure - * returned by png_get_text will always contain regular - * zero-terminated C strings. They might be empty strings but - * they will never be NULL pointers. - */ - -#ifdef PNG_TEXT_SUPPORTED -PNG_EXPORT(163, void, png_set_text, - (png_structp png_ptr, png_infop info_ptr, - png_const_textp text_ptr, int num_text)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(164, png_uint_32, png_get_tIME, - (png_const_structp png_ptr, png_infop info_ptr, png_timep *mod_time)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(165, void, png_set_tIME, - (png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(166, png_uint_32, png_get_tRNS, - (png_const_structp png_ptr, png_infop info_ptr, - png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(167, void, png_set_tRNS, - (png_structp png_ptr, png_infop info_ptr, - png_const_bytep trans_alpha, int num_trans, - png_const_color_16p trans_color)); -#endif - -#ifdef PNG_sCAL_SUPPORTED -PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL, - (png_const_structp png_ptr, png_const_infop info_ptr, - int *unit, double *width, double *height)); -#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED -/* NOTE: this API is currently implemented using floating point arithmetic, - * consequently it can only be used on systems with floating point support. - * In any case the range of values supported by png_fixed_point is small and it - * is highly recommended that png_get_sCAL_s be used instead. - */ -PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed, - (png_structp png_ptr, png_const_infop info_ptr, int *unit, - png_fixed_point *width, - png_fixed_point *height)); -#endif -PNG_EXPORT(169, png_uint_32, png_get_sCAL_s, - (png_const_structp png_ptr, png_const_infop info_ptr, - int *unit, png_charpp swidth, png_charpp sheight)); - -PNG_FP_EXPORT(170, void, png_set_sCAL, - (png_structp png_ptr, png_infop info_ptr, - int unit, double width, double height)); -PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_structp png_ptr, - png_infop info_ptr, int unit, png_fixed_point width, - png_fixed_point height)); -PNG_EXPORT(171, void, png_set_sCAL_s, - (png_structp png_ptr, png_infop info_ptr, - int unit, png_const_charp swidth, png_const_charp sheight)); -#endif /* PNG_sCAL_SUPPORTED */ - -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED -/* Provide a list of chunks and how they are to be handled, if the built-in - handling or default unknown chunk handling is not desired. Any chunks not - listed will be handled in the default manner. The IHDR and IEND chunks - must not be listed. - keep = 0: follow default behaviour - = 1: do not keep - = 2: keep only if safe-to-copy - = 3: keep even if unsafe-to-copy -*/ -PNG_EXPORT(172, void, png_set_keep_unknown_chunks, - (png_structp png_ptr, int keep, - png_const_bytep chunk_list, int num_chunks)); -PNG_EXPORT(173, int, png_handle_as_unknown, (png_structp png_ptr, - png_const_bytep chunk_name)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -PNG_EXPORT(174, void, png_set_unknown_chunks, (png_structp png_ptr, - png_infop info_ptr, png_const_unknown_chunkp unknowns, - int num_unknowns)); -PNG_EXPORT(175, void, png_set_unknown_chunk_location, - (png_structp png_ptr, png_infop info_ptr, int chunk, int location)); -PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structp png_ptr, - png_const_infop info_ptr, png_unknown_chunkpp entries)); -#endif - -/* Png_free_data() will turn off the "valid" flag for anything it frees. - * If you need to turn it off for a chunk that your application has freed, - * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); - */ -PNG_EXPORT(177, void, png_set_invalid, - (png_structp png_ptr, png_infop info_ptr, int mask)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* The "params" pointer is currently not used and is for future expansion. */ -PNG_EXPORT(178, void, png_read_png, (png_structp png_ptr, png_infop info_ptr, - int transforms, png_voidp params)); -PNG_EXPORT(179, void, png_write_png, (png_structp png_ptr, png_infop info_ptr, - int transforms, png_voidp params)); -#endif - -PNG_EXPORT(180, png_const_charp, png_get_copyright, - (png_const_structp png_ptr)); -PNG_EXPORT(181, png_const_charp, png_get_header_ver, - (png_const_structp png_ptr)); -PNG_EXPORT(182, png_const_charp, png_get_header_version, - (png_const_structp png_ptr)); -PNG_EXPORT(183, png_const_charp, png_get_libpng_ver, - (png_const_structp png_ptr)); - -#ifdef PNG_MNG_FEATURES_SUPPORTED -PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structp png_ptr, - png_uint_32 mng_features_permitted)); -#endif - -/* For use in png_set_keep_unknown, added to version 1.2.6 */ -#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 -#define PNG_HANDLE_CHUNK_NEVER 1 -#define PNG_HANDLE_CHUNK_IF_SAFE 2 -#define PNG_HANDLE_CHUNK_ALWAYS 3 - -/* Strip the prepended error numbers ("#nnn ") from error and warning - * messages before passing them to the error or warning handler. - */ -#ifdef PNG_ERROR_NUMBERS_SUPPORTED -PNG_EXPORT(185, void, png_set_strip_error_numbers, - (png_structp png_ptr, - png_uint_32 strip_mode)); -#endif - -/* Added in libpng-1.2.6 */ -#ifdef PNG_SET_USER_LIMITS_SUPPORTED -PNG_EXPORT(186, void, png_set_user_limits, (png_structp png_ptr, - png_uint_32 user_width_max, png_uint_32 user_height_max)); -PNG_EXPORT(187, png_uint_32, png_get_user_width_max, - (png_const_structp png_ptr)); -PNG_EXPORT(188, png_uint_32, png_get_user_height_max, - (png_const_structp png_ptr)); -/* Added in libpng-1.4.0 */ -PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structp png_ptr, - png_uint_32 user_chunk_cache_max)); -PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max, - (png_const_structp png_ptr)); -/* Added in libpng-1.4.1 */ -PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structp png_ptr, - png_alloc_size_t user_chunk_cache_max)); -PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max, - (png_const_structp png_ptr)); -#endif - -#if defined(PNG_INCH_CONVERSIONS_SUPPORTED) -PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_FP_EXPORT(196, float, png_get_x_offset_inches, - (png_const_structp png_ptr, png_const_infop info_ptr)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed, - (png_structp png_ptr, png_const_infop info_ptr)); -#endif - -PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structp png_ptr, - png_const_infop info_ptr)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed, - (png_structp png_ptr, png_const_infop info_ptr)); -#endif - -# ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structp png_ptr, - png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -# endif /* PNG_pHYs_SUPPORTED */ -#endif /* PNG_INCH_CONVERSIONS_SUPPORTED */ - -/* Added in libpng-1.4.0 */ -#ifdef PNG_IO_STATE_SUPPORTED -PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_structp png_ptr)); - -PNG_EXPORTA(200, png_const_bytep, png_get_io_chunk_name, - (png_structp png_ptr), PNG_DEPRECATED); -PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type, - (png_const_structp png_ptr)); - -/* The flags returned by png_get_io_state() are the following: */ -# define PNG_IO_NONE 0x0000 /* no I/O at this moment */ -# define PNG_IO_READING 0x0001 /* currently reading */ -# define PNG_IO_WRITING 0x0002 /* currently writing */ -# define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */ -# define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */ -# define PNG_IO_CHUNK_DATA 0x0040 /* currently at the chunk data */ -# define PNG_IO_CHUNK_CRC 0x0080 /* currently at the chunk crc */ -# define PNG_IO_MASK_OP 0x000f /* current operation: reading/writing */ -# define PNG_IO_MASK_LOC 0x00f0 /* current location: sig/hdr/data/crc */ -#endif /* ?PNG_IO_STATE_SUPPORTED */ - -/* Interlace support. The following macros are always defined so that if - * libpng interlace handling is turned off the macros may be used to handle - * interlaced images within the application. - */ -#define PNG_INTERLACE_ADAM7_PASSES 7 - -/* Two macros to return the first row and first column of the original, - * full, image which appears in a given pass. 'pass' is in the range 0 - * to 6 and the result is in the range 0 to 7. - */ -#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7) -#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7) - -/* Two macros to help evaluate the number of rows or columns in each - * pass. This is expressed as a shift - effectively log2 of the number or - * rows or columns in each 8x8 tile of the original image. - */ -#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) -#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) - -/* Hence two macros to determine the number of rows or columns in a given - * pass of an image given its height or width. In fact these macros may - * return non-zero even though the sub-image is empty, because the other - * dimension may be empty for a small image. - */ -#define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) -#define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) - -/* For the reader row callbacks (both progressive and sequential) it is - * necessary to find the row in the output image given a row in an interlaced - * image, so two more macros: - */ -#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \ - (((yIn)<>(((7-(off))-(pass))<<2)) & 0xFU) | \ - ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U)) - -#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ - ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) -#define PNG_COL_IN_INTERLACE_PASS(x, pass) \ - ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) - -#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED -/* With these routines we avoid an integer divide, which will be slower on - * most machines. However, it does take more operations than the corresponding - * divide method, so it may be slower on a few RISC systems. There are two - * shifts (by 8 or 16 bits) and an addition, versus a single integer divide. - * - * Note that the rounding factors are NOT supposed to be the same! 128 and - * 32768 are correct for the NODIV code; 127 and 32767 are correct for the - * standard method. - * - * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ] - */ - - /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */ - -# define png_composite(composite, fg, alpha, bg) \ - { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \ - * (png_uint_16)(alpha) \ - + (png_uint_16)(bg)*(png_uint_16)(255 \ - - (png_uint_16)(alpha)) + (png_uint_16)128); \ - (composite) = (png_byte)((temp + (temp >> 8)) >> 8); } - -# define png_composite_16(composite, fg, alpha, bg) \ - { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) \ - * (png_uint_32)(alpha) \ - + (png_uint_32)(bg)*(png_uint_32)(65535L \ - - (png_uint_32)(alpha)) + (png_uint_32)32768L); \ - (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); } - -#else /* Standard method using integer division */ - -# define png_composite(composite, fg, alpha, bg) \ - (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \ - (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \ - (png_uint_16)127) / 255) - -# define png_composite_16(composite, fg, alpha, bg) \ - (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \ - (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \ - (png_uint_32)32767) / (png_uint_32)65535L) -#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */ - -#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf)); -PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf)); -PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf)); -#endif - -PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_structp png_ptr, - png_const_bytep buf)); -/* No png_get_int_16 -- may be added if there's a real need for it. */ - -/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i)); -#endif -#ifdef PNG_SAVE_INT_32_SUPPORTED -PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i)); -#endif - -/* Place a 16-bit number into a buffer in PNG byte order. - * The parameter is declared unsigned int, not png_uint_16, - * just to avoid potential problems on pre-ANSI C compilers. - */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i)); -/* No png_save_int_16 -- may be added if there's a real need for it. */ -#endif - -#ifdef PNG_USE_READ_MACROS -/* Inline macros to do direct reads of bytes from the input buffer. - * The png_get_int_32() routine assumes we are using two's complement - * format for negative values, which is almost certainly true. - */ -# define png_get_uint_32(buf) \ - (((png_uint_32)(*(buf)) << 24) + \ - ((png_uint_32)(*((buf) + 1)) << 16) + \ - ((png_uint_32)(*((buf) + 2)) << 8) + \ - ((png_uint_32)(*((buf) + 3)))) - - /* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the - * function) incorrectly returned a value of type png_uint_32. - */ -# define png_get_uint_16(buf) \ - ((png_uint_16) \ - (((unsigned int)(*(buf)) << 8) + \ - ((unsigned int)(*((buf) + 1))))) - -# define png_get_int_32(buf) \ - ((png_int_32)((*(buf) & 0x80) \ - ? -((png_int_32)((png_get_uint_32(buf) ^ 0xffffffffL) + 1)) \ - : (png_int_32)png_get_uint_32(buf))) -#endif - -/* Maintainer: Put new public prototypes here ^, in libpng.3, and project - * defs - */ - -/* The last ordinal number (this is the *last* one already used; the next - * one to use is one more than this.) Maintainer, remember to add an entry to - * scripts/symbols.def as well. - */ -#ifdef PNG_EXPORT_LAST_ORDINAL - PNG_EXPORT_LAST_ORDINAL(221); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* PNG_VERSION_INFO_ONLY */ -/* Do not put anything past this line */ -#endif /* PNG_H */ diff --git a/cdeps/win32/pngconf.h b/cdeps/win32/pngconf.h deleted file mode 100755 index 084de8ef..00000000 --- a/cdeps/win32/pngconf.h +++ /dev/null @@ -1,649 +0,0 @@ - -/* pngconf.h - machine configurable file for libpng - * - * libpng version 1.5.2 - March 31, 2011 - * - * Copyright (c) 1998-2011 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license. - * For conditions of distribution and use, see the disclaimer - * and license in png.h - * - */ - -/* Any machine specific code is near the front of this file, so if you - * are configuring libpng for a machine, you may want to read the section - * starting here down to where it starts to typedef png_color, png_text, - * and png_info. - */ - -#ifndef PNGCONF_H -#define PNGCONF_H - -#ifndef PNG_BUILDING_SYMBOL_TABLE -/* PNG_NO_LIMITS_H may be used to turn off the use of the standard C - * definition file for machine specific limits, this may impact the - * correctness of the definitons below (see uses of INT_MAX). - */ -# ifndef PNG_NO_LIMITS_H -# include -# endif - -/* For the memory copy APIs (i.e. the standard definitions of these), - * because this file defines png_memcpy and so on the base APIs must - * be defined here. - */ -# ifdef BSD -# include -# else -# include -# endif - -/* For png_FILE_p - this provides the standard definition of a - * FILE - */ -# ifdef PNG_STDIO_SUPPORTED -# include -# endif -#endif - -/* This controls optimization of the reading of 16 and 32 bit values - * from PNG files. It can be set on a per-app-file basis - it - * just changes whether a macro is used to the function is called. - * The library builder sets the default, if read functions are not - * built into the library the macro implementation is forced on. - */ -#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED -# define PNG_USE_READ_MACROS -#endif -#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS) -# if PNG_DEFAULT_READ_MACROS -# define PNG_USE_READ_MACROS -# endif -#endif - -/* COMPILER SPECIFIC OPTIONS. - * - * These options are provided so that a variety of difficult compilers - * can be used. Some are fixed at build time (e.g. PNG_API_RULE - * below) but still have compiler specific implementations, others - * may be changed on a per-file basis when compiling against libpng. - */ - -/* The PNGARG macro protects us against machines that don't have function - * prototypes (ie K&R style headers). If your compiler does not handle - * function prototypes, define this macro and use the included ansi2knr. - * I've always been able to use _NO_PROTO as the indicator, but you may - * need to drag the empty declaration out in front of here, or change the - * ifdef to suit your own needs. - */ -#ifndef PNGARG - -# ifdef OF /* zlib prototype munger */ -# define PNGARG(arglist) OF(arglist) -# else - -# ifdef _NO_PROTO -# define PNGARG(arglist) () -# else -# define PNGARG(arglist) arglist -# endif /* _NO_PROTO */ - -# endif /* OF */ - -#endif /* PNGARG */ - -/* Function calling conventions. - * ============================= - * Normally it is not necessary to specify to the compiler how to call - * a function - it just does it - however on x86 systems derived from - * Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems - * and some others) there are multiple ways to call a function and the - * default can be changed on the compiler command line. For this reason - * libpng specifies the calling convention of every exported function and - * every function called via a user supplied function pointer. This is - * done in this file by defining the following macros: - * - * PNGAPI Calling convention for exported functions. - * PNGCBAPI Calling convention for user provided (callback) functions. - * PNGCAPI Calling convention used by the ANSI-C library (required - * for longjmp callbacks and sometimes used internally to - * specify the calling convention for zlib). - * - * These macros should never be overridden. If it is necessary to - * change calling convention in a private build this can be done - * by setting PNG_API_RULE (which defaults to 0) to one of the values - * below to select the correct 'API' variants. - * - * PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout. - * This is correct in every known environment. - * PNG_API_RULE=1 Use the operating system convention for PNGAPI and - * the 'C' calling convention (from PNGCAPI) for - * callbacks (PNGCBAPI). This is no longer required - * in any known environment - if it has to be used - * please post an explanation of the problem to the - * libpng mailing list. - * - * These cases only differ if the operating system does not use the C - * calling convention, at present this just means the above cases - * (x86 DOS/Windows sytems) and, even then, this does not apply to - * Cygwin running on those systems. - * - * Note that the value must be defined in pnglibconf.h so that what - * the application uses to call the library matches the conventions - * set when building the library. - */ - -/* Symbol export - * ============= - * When building a shared library it is almost always necessary to tell - * the compiler which symbols to export. The png.h macro 'PNG_EXPORT' - * is used to mark the symbols. On some systems these symbols can be - * extracted at link time and need no special processing by the compiler, - * on other systems the symbols are flagged by the compiler and just - * the declaration requires a special tag applied (unfortunately) in a - * compiler dependent way. Some systems can do either. - * - * A small number of older systems also require a symbol from a DLL to - * be flagged to the program that calls it. This is a problem because - * we do not know in the header file included by application code that - * the symbol will come from a shared library, as opposed to a statically - * linked one. For this reason the application must tell us by setting - * the magic flag PNG_USE_DLL to turn on the special processing before - * it includes png.h. - * - * Four additional macros are used to make this happen: - * - * PNG_IMPEXP The magic (if any) to cause a symbol to be exported from - * the build or imported if PNG_USE_DLL is set - compiler - * and system specific. - * - * PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to - * 'type', compiler specific. - * - * PNG_DLL_EXPORT Set to the magic to use during a libpng build to - * make a symbol exported from the DLL. - * - * PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come - * from a DLL - used to define PNG_IMPEXP when - * PNG_USE_DLL is set. - */ - -/* System specific discovery. - * ========================== - * This code is used at build time to find PNG_IMPEXP, the API settings - * and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL - * import processing is possible. On Windows/x86 systems it also sets - * compiler-specific macros to the values required to change the calling - * conventions of the various functions. - */ -#if ( defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\ - defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) ) &&\ - ( defined(_X86_) || defined(_X64_) || defined(_M_IX86) ||\ - defined(_M_X64) || defined(_M_IA64) ) - /* Windows system (DOS doesn't support DLLs) running on x86/x64. Includes - * builds under Cygwin or MinGW. Also includes Watcom builds but these need - * special treatment because they are not compatible with GCC or Visual C - * because of different calling conventions. - */ -# if PNG_API_RULE == 2 - /* If this line results in an error, either because __watcall is not - * understood or because of a redefine just below you cannot use *this* - * build of the library with the compiler you are using. *This* build was - * build using Watcom and applications must also be built using Watcom! - */ -# define PNGCAPI __watcall -# endif - -# if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800)) -# define PNGCAPI __cdecl -# if PNG_API_RULE == 1 -# define PNGAPI __stdcall -# endif -# else - /* An older compiler, or one not detected (erroneously) above, - * if necessary override on the command line to get the correct - * variants for the compiler. - */ -# ifndef PNGCAPI -# define PNGCAPI _cdecl -# endif -# if PNG_API_RULE == 1 && !defined(PNGAPI) -# define PNGAPI _stdcall -# endif -# endif /* compiler/api */ - /* NOTE: PNGCBAPI always defaults to PNGCAPI. */ - -# if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD) - ERROR: PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed -# endif - -# if (defined(_MSC_VER) && _MSC_VER < 800) ||\ - (defined(__BORLANDC__) && __BORLANDC__ < 0x500) - /* older Borland and MSC - * compilers used '__export' and required this to be after - * the type. - */ -# ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) type PNG_IMPEXP -# endif -# define PNG_DLL_EXPORT __export -# else /* newer compiler */ -# define PNG_DLL_EXPORT __declspec(dllexport) -# ifndef PNG_DLL_IMPORT -# define PNG_DLL_IMPORT __declspec(dllimport) -# endif -# endif /* compiler */ - -#else /* !Windows/x86 */ -# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__) -# define PNGAPI _System -# else /* !Windows/x86 && !OS/2 */ - /* Use the defaults, or define PNG*API on the command line (but - * this will have to be done for every compile!) - */ -# endif /* other system, !OS/2 */ -#endif /* !Windows/x86 */ - -/* Now do all the defaulting . */ -#ifndef PNGCAPI -# define PNGCAPI -#endif -#ifndef PNGCBAPI -# define PNGCBAPI PNGCAPI -#endif -#ifndef PNGAPI -# define PNGAPI PNGCAPI -#endif - -/* The default for PNG_IMPEXP depends on whether the library is - * being built or used. - */ -#ifndef PNG_IMPEXP -# ifdef PNGLIB_BUILD - /* Building the library */ -# if (defined(DLL_EXPORT)/*from libtool*/ ||\ - defined(_WINDLL) || defined(_DLL) || defined(__DLL__) ||\ - defined(_USRDLL) ||\ - defined(PNG_BUILD_DLL)) && defined(PNG_DLL_EXPORT) - /* Building a DLL. */ -# define PNG_IMPEXP PNG_DLL_EXPORT -# endif /* DLL */ -# else - /* Using the library */ -# if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT) - /* This forces use of a DLL, disallowing static linking */ -# define PNG_IMPEXP PNG_DLL_IMPORT -# endif -# endif - -# ifndef PNG_IMPEXP -# define PNG_IMPEXP -# endif -#endif - -/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat - * 'attributes' as a storage class - the attributes go at the start of the - * function definition, and attributes are always appended regardless of the - * compiler. This considerably simplifies these macros but may cause problems - * if any compilers both need function attributes and fail to handle them as - * a storage class (this is unlikely.) - */ -#ifndef PNG_FUNCTION -# define PNG_FUNCTION(type, name, args, attributes) attributes type name args -#endif - -#ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) PNG_IMPEXP type -#endif - - /* The ordinal value is only relevant when preprocessing png.h for symbol - * table entries, so we discard it here. See the .dfn files in the - * scripts directory. - */ -#ifndef PNG_EXPORTA - -# define PNG_EXPORTA(ordinal, type, name, args, attributes)\ - PNG_FUNCTION(PNG_EXPORT_TYPE(type),(PNGAPI name),PNGARG(args), \ - extern attributes) -#endif - -/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument, - * so make something non-empty to satisfy the requirement: - */ -#define PNG_EMPTY /*empty list*/ - -#define PNG_EXPORT(ordinal, type, name, args)\ - PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY) - -/* Use PNG_REMOVED to comment out a removed interface. */ -#ifndef PNG_REMOVED -# define PNG_REMOVED(ordinal, type, name, args, attributes) -#endif - -#ifndef PNG_CALLBACK -# define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args) -#endif - -/* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. - * - * Added at libpng-1.2.41. - */ - -#ifndef PNG_NO_PEDANTIC_WARNINGS -# ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED -# define PNG_PEDANTIC_WARNINGS_SUPPORTED -# endif -#endif - -#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED - /* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. Added at libpng - * version 1.2.41. - */ -# if defined(__GNUC__) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# ifndef PNG_PTR_NORETURN - /* It's not enough to have the compiler be the correct compiler at - * this point - it's necessary for the library (which defines - * the type of the library longjmp) to also be the GNU library. - * This is because many systems use the GNU compiler with a - * non-GNU libc implementation. Min/GW headers are also compatible - * with GCC as well as uclibc, so it seems best to exclude known - * problem libcs here rather than just including known libcs. - * - * NOTE: this relies on the only use of PNG_PTR_NORETURN being with - * the system longjmp. If the same type is used elsewhere then this - * will need to be changed. - */ -# if !defined(__CYGWIN__) -# define PNG_PTR_NORETURN __attribute__((__noreturn__)) -# endif -# endif -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif - - /* This specifically protects structure members that should only be - * accessed from within the library, therefore should be empty during - * a library build. - */ -# ifndef PNGLIB_BUILD -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT __attribute__((__deprecated__)) -# endif -# ifndef PNG_PRIVATE -# if 0 /* Doesn't work so we use deprecated instead*/ -# define PNG_PRIVATE \ - __attribute__((warning("This function is not exported by libpng."))) -# else -# define PNG_PRIVATE \ - __attribute__((__deprecated__)) -# endif -# endif -# endif /* PNGLIB_BUILD */ -# endif /* __GNUC__ */ - -# if defined(_MSC_VER) && (_MSC_VER >= 1300) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* not supported */ -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __declspec(noreturn) -# endif -# ifndef PNG_PTR_NORETURN -# define PNG_PTR_NORETURN /* not supported */ -# endif -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __declspec(restrict) -# endif - - /* This specifically protects structure members that should only be - * accessed from within the library, therefore should be empty during - * a library build. - */ -# ifndef PNGLIB_BUILD -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __declspec(deprecated) -# endif -# ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT __declspec(deprecated) -# endif -# ifndef PNG_PRIVATE -# define PNG_PRIVATE __declspec(deprecated) -# endif -# endif /* PNGLIB_BUILD */ -# endif /* _MSC_VER */ -#endif /* PNG_PEDANTIC_WARNINGS */ - -#ifndef PNG_DEPRECATED -# define PNG_DEPRECATED /* Use of this function is deprecated */ -#endif -#ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* The result of this function must be checked */ -#endif -#ifndef PNG_NORETURN -# define PNG_NORETURN /* This function does not return */ -#endif -#ifndef PNG_PTR_NORETURN -# define PNG_PTR_NORETURN /* This function does not return */ -#endif -#ifndef PNG_ALLOCATED -# define PNG_ALLOCATED /* The result of the function is new memory */ -#endif -#ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT /* Access to this struct member is deprecated */ -#endif -#ifndef PNG_PRIVATE -# define PNG_PRIVATE /* This is a private libpng function */ -#endif -#ifndef PNG_FP_EXPORT /* A floating point API. */ -# ifdef PNG_FLOATING_POINT_SUPPORTED -# define PNG_FP_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args) -# else /* No floating point APIs */ -# define PNG_FP_EXPORT(ordinal, type, name, args) -# endif -#endif -#ifndef PNG_FIXED_EXPORT /* A fixed point API. */ -# ifdef PNG_FIXED_POINT_SUPPORTED -# define PNG_FIXED_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args) -# else /* No fixed point APIs */ -# define PNG_FIXED_EXPORT(ordinal, type, name, args) -# endif -#endif - -/* The following uses const char * instead of char * for error - * and warning message functions, so some compilers won't complain. - * If you do not want to use const, define PNG_NO_CONST here. - * - * This should not change how the APIs are called, so it can be done - * on a per-file basis in the application. - */ -#ifndef PNG_CONST -# ifndef PNG_NO_CONST -# define PNG_CONST const -# else -# define PNG_CONST -# endif -#endif - -/* Some typedefs to get us started. These should be safe on most of the - * common platforms. The typedefs should be at least as large as the - * numbers suggest (a png_uint_32 must be at least 32 bits long), but they - * don't have to be exactly that size. Some compilers dislike passing - * unsigned shorts as function parameters, so you may be better off using - * unsigned int for png_uint_16. - */ - -#if defined(INT_MAX) && (INT_MAX > 0x7ffffffeL) -typedef unsigned int png_uint_32; -typedef int png_int_32; -#else -typedef unsigned long png_uint_32; -typedef long png_int_32; -#endif -typedef unsigned short png_uint_16; -typedef short png_int_16; -typedef unsigned char png_byte; - -#ifdef PNG_NO_SIZE_T -typedef unsigned int png_size_t; -#else -typedef size_t png_size_t; -#endif -#define png_sizeof(x) (sizeof (x)) - -/* The following is needed for medium model support. It cannot be in the - * pngpriv.h header. Needs modification for other compilers besides - * MSC. Model independent support declares all arrays and pointers to be - * large using the far keyword. The zlib version used must also support - * model independent data. As of version zlib 1.0.4, the necessary changes - * have been made in zlib. The USE_FAR_KEYWORD define triggers other - * changes that are needed. (Tim Wegner) - */ - -/* Separate compiler dependencies (problem here is that zlib.h always - * defines FAR. (SJT) - */ -#ifdef __BORLANDC__ -# if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__) -# define LDATA 1 -# else -# define LDATA 0 -# endif - /* GRR: why is Cygwin in here? Cygwin is not Borland C... */ -# if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__) -# define PNG_MAX_MALLOC_64K /* only used in build */ -# if (LDATA != 1) -# ifndef FAR -# define FAR __far -# endif -# define USE_FAR_KEYWORD -# endif /* LDATA != 1 */ - /* Possibly useful for moving data out of default segment. - * Uncomment it if you want. Could also define FARDATA as - * const if your compiler supports it. (SJT) -# define FARDATA FAR - */ -# endif /* __WIN32__, __FLAT__, __CYGWIN__ */ -#endif /* __BORLANDC__ */ - - -/* Suggest testing for specific compiler first before testing for - * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM, - * making reliance oncertain keywords suspect. (SJT) - */ - -/* MSC Medium model */ -#ifdef FAR -# ifdef M_I86MM -# define USE_FAR_KEYWORD -# define FARDATA FAR -# include -# endif -#endif - -/* SJT: default case */ -#ifndef FAR -# define FAR -#endif - -/* At this point FAR is always defined */ -#ifndef FARDATA -# define FARDATA -#endif - -/* Typedef for floating-point numbers that are converted - * to fixed-point with a multiple of 100,000, e.g., gamma - */ -typedef png_int_32 png_fixed_point; - -/* Add typedefs for pointers */ -typedef void FAR * png_voidp; -typedef PNG_CONST void FAR * png_const_voidp; -typedef png_byte FAR * png_bytep; -typedef PNG_CONST png_byte FAR * png_const_bytep; -typedef png_uint_32 FAR * png_uint_32p; -typedef PNG_CONST png_uint_32 FAR * png_const_uint_32p; -typedef png_int_32 FAR * png_int_32p; -typedef PNG_CONST png_int_32 FAR * png_const_int_32p; -typedef png_uint_16 FAR * png_uint_16p; -typedef PNG_CONST png_uint_16 FAR * png_const_uint_16p; -typedef png_int_16 FAR * png_int_16p; -typedef PNG_CONST png_int_16 FAR * png_const_int_16p; -typedef char FAR * png_charp; -typedef PNG_CONST char FAR * png_const_charp; -typedef png_fixed_point FAR * png_fixed_point_p; -typedef PNG_CONST png_fixed_point FAR * png_const_fixed_point_p; -typedef png_size_t FAR * png_size_tp; -typedef PNG_CONST png_size_t FAR * png_const_size_tp; - -#ifdef PNG_STDIO_SUPPORTED -typedef FILE * png_FILE_p; -#endif - -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double FAR * png_doublep; -typedef PNG_CONST double FAR * png_const_doublep; -#endif - -/* Pointers to pointers; i.e. arrays */ -typedef png_byte FAR * FAR * png_bytepp; -typedef png_uint_32 FAR * FAR * png_uint_32pp; -typedef png_int_32 FAR * FAR * png_int_32pp; -typedef png_uint_16 FAR * FAR * png_uint_16pp; -typedef png_int_16 FAR * FAR * png_int_16pp; -typedef PNG_CONST char FAR * FAR * png_const_charpp; -typedef char FAR * FAR * png_charpp; -typedef png_fixed_point FAR * FAR * png_fixed_point_pp; -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double FAR * FAR * png_doublepp; -#endif - -/* Pointers to pointers to pointers; i.e., pointer to array */ -typedef char FAR * FAR * FAR * png_charppp; - -/* png_alloc_size_t is guaranteed to be no smaller than png_size_t, - * and no smaller than png_uint_32. Casts from png_size_t or png_uint_32 - * to png_alloc_size_t are not necessary; in fact, it is recommended - * not to use them at all so that the compiler can complain when something - * turns out to be problematic. - * Casts in the other direction (from png_alloc_size_t to png_size_t or - * png_uint_32) should be explicitly applied; however, we do not expect - * to encounter practical situations that require such conversions. - */ -#if defined(__TURBOC__) && !defined(__FLAT__) - typedef unsigned long png_alloc_size_t; -#else -# if defined(_MSC_VER) && defined(MAXSEG_64K) - typedef unsigned long png_alloc_size_t; -# else - /* This is an attempt to detect an old Windows system where (int) is - * actually 16 bits, in that case png_malloc must have an argument with a - * bigger size to accomodate the requirements of the library. - */ -# if (defined(_Windows) || defined(_WINDOWS) || defined(_WINDOWS_)) && \ - (!defined(INT_MAX) || INT_MAX <= 0x7ffffffeL) - typedef DWORD png_alloc_size_t; -# else - typedef png_size_t png_alloc_size_t; -# endif -# endif -#endif - -#endif /* PNGCONF_H */ diff --git a/cdeps/win32/pnglibconf.h b/cdeps/win32/pnglibconf.h deleted file mode 100755 index e36ee348..00000000 --- a/cdeps/win32/pnglibconf.h +++ /dev/null @@ -1,181 +0,0 @@ - -/* libpng STANDARD API DEFINITION */ - -/* pnglibconf.h - library build configuration */ - -/* libpng version 1.5.0 - last changed on February 11, 2011 */ - -/* Copyright (c) 1998-2011 Glenn Randers-Pehrson */ - -/* This code is released under the libpng license. */ -/* For conditions of distribution and use, see the disclaimer */ -/* and license in png.h */ - -/* pnglibconf.h */ -/* Derived from: scripts/pnglibconf.dfa */ -/* If you edit this file by hand you must obey the rules expressed in */ -/* pnglibconf.dfa with respect to the dependencies between the following */ -/* symbols. It is much better to generate a new file using */ -/* scripts/libpngconf.mak */ - -#ifndef PNGLCONF_H -#define PNGLCONF_H -/* settings */ -#define PNG_API_RULE 0 -#define PNG_CALLOC_SUPPORTED -#define PNG_COST_SHIFT 3 -#define PNG_DEFAULT_READ_MACROS 1 -#define PNG_GAMMA_THRESHOLD_FIXED 5000 -#define PNG_MAX_GAMMA_8 11 -#define PNG_QUANTIZE_BLUE_BITS 5 -#define PNG_QUANTIZE_GREEN_BITS 5 -#define PNG_QUANTIZE_RED_BITS 5 -#define PNG_sCAL_PRECISION 5 -#define PNG_USER_CHUNK_CACHE_MAX 0 -#define PNG_USER_CHUNK_MALLOC_MAX 0 -#define PNG_USER_HEIGHT_MAX 1000000L -#define PNG_USER_WIDTH_MAX 1000000L -#define PNG_WEIGHT_SHIFT 8 -#define PNG_ZBUF_SIZE 8192 -/* end of settings */ -/* options */ -#define PNG_16BIT_SUPPORTED -#define PNG_ALIGN_MEMORY_SUPPORTED -#define PNG_BENIGN_ERRORS_SUPPORTED -#define PNG_bKGD_SUPPORTED -#define PNG_CHECK_cHRM_SUPPORTED -#define PNG_cHRM_SUPPORTED -#define PNG_CONSOLE_IO_SUPPORTED -#define PNG_CONVERT_tIME_SUPPORTED -#define PNG_EASY_ACCESS_SUPPORTED -#define PNG_ERROR_TEXT_SUPPORTED -#define PNG_FIXED_POINT_SUPPORTED -#define PNG_FLOATING_ARITHMETIC_SUPPORTED -#define PNG_FLOATING_POINT_SUPPORTED -#define PNG_gAMA_SUPPORTED -#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED -#define PNG_hIST_SUPPORTED -#define PNG_iCCP_SUPPORTED -#define PNG_INCH_CONVERSIONS_SUPPORTED -#define PNG_INFO_IMAGE_SUPPORTED -#define PNG_IO_STATE_SUPPORTED -#define PNG_iTXt_SUPPORTED -#define PNG_MNG_FEATURES_SUPPORTED -#define PNG_oFFs_SUPPORTED -#define PNG_pCAL_SUPPORTED -#define PNG_pHYs_SUPPORTED -#define PNG_POINTER_INDEXING_SUPPORTED -#define PNG_PROGRESSIVE_READ_SUPPORTED -#define PNG_READ_16BIT_SUPPORTED -#define PNG_READ_16_TO_8_SUPPORTED -#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_READ_BACKGROUND_SUPPORTED -#define PNG_READ_BGR_SUPPORTED -#define PNG_READ_bKGD_SUPPORTED -#define PNG_READ_cHRM_SUPPORTED -#define PNG_READ_COMPOSITE_NODIV_SUPPORTED -#define PNG_READ_EXPAND_16_SUPPORTED -#define PNG_READ_EXPAND_SUPPORTED -#define PNG_READ_FILLER_SUPPORTED -#define PNG_READ_gAMA_SUPPORTED -#define PNG_READ_GAMMA_SUPPORTED -#define PNG_READ_GRAY_TO_RGB_SUPPORTED -#define PNG_READ_hIST_SUPPORTED -#define PNG_READ_iCCP_SUPPORTED -#define PNG_READ_INTERLACING_SUPPORTED -#define PNG_READ_INT_FUNCTIONS_SUPPORTED -#define PNG_READ_INVERT_ALPHA_SUPPORTED -#define PNG_READ_INVERT_SUPPORTED -#define PNG_READ_iTXt_SUPPORTED -#define PNG_READ_oFFs_SUPPORTED -#define PNG_READ_OPT_PLTE_SUPPORTED -#define PNG_READ_PACK_SUPPORTED -#define PNG_READ_PACKSWAP_SUPPORTED -#define PNG_READ_pCAL_SUPPORTED -#define PNG_READ_pHYs_SUPPORTED -#define PNG_READ_QUANTIZE_SUPPORTED -#define PNG_READ_RGB_TO_GRAY_SUPPORTED -#define PNG_READ_sBIT_SUPPORTED -#define PNG_READ_sCAL_SUPPORTED -#define PNG_READ_SHIFT_SUPPORTED -#define PNG_READ_sPLT_SUPPORTED -#define PNG_READ_sRGB_SUPPORTED -#define PNG_READ_STRIP_ALPHA_SUPPORTED -#define PNG_READ_SUPPORTED -#define PNG_READ_SWAP_ALPHA_SUPPORTED -#define PNG_READ_SWAP_SUPPORTED -#define PNG_READ_tEXt_SUPPORTED -#define PNG_READ_TEXT_SUPPORTED -#define PNG_READ_tIME_SUPPORTED -#define PNG_READ_TRANSFORMS_SUPPORTED -#define PNG_READ_tRNS_SUPPORTED -#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_READ_USER_CHUNKS_SUPPORTED -#define PNG_READ_USER_TRANSFORM_SUPPORTED -#define PNG_READ_zTXt_SUPPORTED -#define PNG_SAVE_INT_32_SUPPORTED -#define PNG_sBIT_SUPPORTED -#define PNG_sCAL_SUPPORTED -#define PNG_SEQUENTIAL_READ_SUPPORTED -#define PNG_SET_CHUNK_CACHE_LIMIT_SUPPORTED -#define PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED -#define PNG_SETJMP_SUPPORTED -#define PNG_SET_USER_LIMITS_SUPPORTED -#define PNG_sPLT_SUPPORTED -#define PNG_sRGB_SUPPORTED -#define PNG_STDIO_SUPPORTED -#define PNG_tEXt_SUPPORTED -#define PNG_TEXT_SUPPORTED -#define PNG_TIME_RFC1123_SUPPORTED -#define PNG_tIME_SUPPORTED -#define PNG_tRNS_SUPPORTED -#define PNG_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_USER_CHUNKS_SUPPORTED -#define PNG_USER_LIMITS_SUPPORTED -#define PNG_USER_MEM_SUPPORTED -#define PNG_USER_TRANSFORM_INFO_SUPPORTED -#define PNG_USER_TRANSFORM_PTR_SUPPORTED -#define PNG_WARNINGS_SUPPORTED -#define PNG_WRITE_16BIT_SUPPORTED -#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_WRITE_BGR_SUPPORTED -#define PNG_WRITE_bKGD_SUPPORTED -#define PNG_WRITE_cHRM_SUPPORTED -#define PNG_WRITE_FILLER_SUPPORTED -#define PNG_WRITE_FILTER_SUPPORTED -#define PNG_WRITE_FLUSH_SUPPORTED -#define PNG_WRITE_gAMA_SUPPORTED -#define PNG_WRITE_hIST_SUPPORTED -#define PNG_WRITE_iCCP_SUPPORTED -#define PNG_WRITE_INTERLACING_SUPPORTED -#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED -#define PNG_WRITE_INVERT_ALPHA_SUPPORTED -#define PNG_WRITE_INVERT_SUPPORTED -#define PNG_WRITE_iTXt_SUPPORTED -#define PNG_WRITE_oFFs_SUPPORTED -#define PNG_WRITE_PACK_SUPPORTED -#define PNG_WRITE_PACKSWAP_SUPPORTED -#define PNG_WRITE_pCAL_SUPPORTED -#define PNG_WRITE_pHYs_SUPPORTED -#define PNG_WRITE_sBIT_SUPPORTED -#define PNG_WRITE_sCAL_SUPPORTED -#define PNG_WRITE_SHIFT_SUPPORTED -#define PNG_WRITE_sPLT_SUPPORTED -#define PNG_WRITE_sRGB_SUPPORTED -#define PNG_WRITE_SUPPORTED -#define PNG_WRITE_SWAP_ALPHA_SUPPORTED -#define PNG_WRITE_SWAP_SUPPORTED -#define PNG_WRITE_tEXt_SUPPORTED -#define PNG_WRITE_TEXT_SUPPORTED -#define PNG_WRITE_tIME_SUPPORTED -#define PNG_WRITE_TRANSFORMS_SUPPORTED -#define PNG_WRITE_tRNS_SUPPORTED -#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_WRITE_USER_TRANSFORM_SUPPORTED -#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED -#define PNG_WRITE_zTXt_SUPPORTED -#define PNG_zTXt_SUPPORTED -/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ -/*#undef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED*/ -/* end of options */ -#endif /* PNGLCONF_H */ diff --git a/cdeps/win32/zconf.h b/cdeps/win32/zconf.h deleted file mode 100755 index 02ce56c4..00000000 --- a/cdeps/win32/zconf.h +++ /dev/null @@ -1,428 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# define uncompress z_uncompress -# define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# define gzFile z_gzFile -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef STDC -# include /* for off_t */ -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -#endif - -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 -# define z_off64_t off64_t -#else -# define z_off64_t z_off_t -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/cdeps/win32/zlib.h b/cdeps/win32/zlib.h deleted file mode 100755 index bfbba83e..00000000 --- a/cdeps/win32/zlib.h +++ /dev/null @@ -1,1613 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.5, April 19th, 2010 - - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.5" -#define ZLIB_VERNUM 0x1250 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 5 -#define ZLIB_VER_SUBREVISION 0 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use in the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). Some - output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed code - block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the stream - are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect the - compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the - exact value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit() does not process any header information -- that is deferred - until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing will - resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained, so applications that need that information should - instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by the - caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as - fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The - strategy parameter only affects the compression ratio but not the - correctness of the compressed output even if it is not set appropriately. - Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler - decoder for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. The - stream will keep the same compression level and any other attributes that - may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression level is changed, the input available so far is - compressed with the old level (and may be flushed); the new level will take - effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to be - compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if - strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - int windowBits)); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above or -1 << 16 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When any - of extra, name, or comment are not Z_NULL and the respective field is not - present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the normal - behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) Upon exit, destLen - is the actual size of the uncompressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef voidp gzFile; /* opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - - Opens a gzip (.gz) file for reading or writing. The mode parameter is as - in fopen ("rb" or "wb") but can also include a compression level ("wb9") or - a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only - compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' - for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen associates a gzFile with the file descriptor fd. File descriptors - are obtained from calls like open, dup, creat, pipe or fileno (if the file - has been previously opened with fopen). The mode parameter is as in gzopen. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -/* - Set the internal buffer size used by this library's functions. The - default buffer size is 8192 bytes. This function must be called after - gzopen() or gzdopen(), and before any other calls that read or write the - file. The buffer memory allocation is always deferred to the first read or - write. Two buffers are allocated, either both of the specified size when - writing, or one of the specified size and the other twice that size when - reading. A larger buffer size of, for example, 64K or 128K bytes will - noticeably increase the speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. -*/ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes written or 0 in case of - error. -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the arguments to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or 0 in case of error. The number of - uncompressed bytes written is limited to 8191, or one less than the buffer - size given to gzbuffer(). The caller should assure that this limit is not - exceeded. If it is exceeded, then gzprintf() will return an error (0) with - nothing written. In this case, there may also be a buffer overflow with - unpredictable consequences, which is possible only if zlib was compiled with - the insecure functions sprintf() or vsprintf() because the secure snprintf() - or vsnprintf() functions were not available. This can be determined using - zlibCompileFlags(). -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or a - newline character is read and transferred to buf, or an end-of-file - condition is encountered. If any characters are read or if len == 1, the - string is terminated with a null character. If no characters are read due - to an end-of-file or len < 1, then the buffer is left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If there was an error, the contents at - buf are indeterminate. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read as the first character - on the next read. At least one character of push-back is allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter flush - is as in the deflate() function. The return value is the zlib error number - (see function gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatented gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); - - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - - Returns the starting position for the next gzread or gzwrite on the given - compressed file. This position represents a number of bytes in the - uncompressed data stream, and is zero when starting, even if appending or - reading a gzip stream from the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - - Returns the current offset in the file being read or written. This offset - includes the count of bytes that precede the gzip stream, for example when - appending or when using gzdopen() for reading. When reading, the offset - does not include as yet unused buffered input. This information can be used - for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns true (1) if the end-of-file indicator has been set while reading, - false (0) otherwise. Note that the end-of-file indicator is set only if the - read tried to go past the end of the input, but came up short. Therefore, - just like feof(), gzeof() may return false even if there is no more data to - read, in the event that the last read request was for the exact number of - bytes remaining in the input file. This will happen if the input file size - is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file and - deallocates the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); -ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the given - compressed file. errnum is set to zlib error number. If an error occurred - in the file system and not in the compression library, errnum is set to - Z_ERRNO and the application may consult errno to get the exact error code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is Z_NULL, this function returns the - required initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -#endif - -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifdef _LARGEFILE64_SOURCE - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -#endif - -/* hack for buggy compilers */ -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; -#endif - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); -ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/cdeps/win64/libpng.a b/cdeps/win64/libpng.a deleted file mode 100644 index 6eaea0d2..00000000 Binary files a/cdeps/win64/libpng.a and /dev/null differ diff --git a/cdeps/win64/png.h b/cdeps/win64/png.h deleted file mode 100755 index 9e9b46c0..00000000 --- a/cdeps/win64/png.h +++ /dev/null @@ -1,2309 +0,0 @@ - -/* png.h - header file for PNG reference library - * - * libpng version 1.5.2 - March 31, 2011 - * Copyright (c) 1998-2011 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license (See LICENSE, below) - * - * Authors and maintainers: - * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat - * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger - * libpng versions 0.97, January 1998, through 1.5.2 - March 31, 2011: Glenn - * See also "Contributing Authors", below. - * - * Note about libpng version numbers: - * - * Due to various miscommunications, unforeseen code incompatibilities - * and occasional factors outside the authors' control, version numbering - * on the library has not always been consistent and straightforward. - * The following table summarizes matters since version 0.89c, which was - * the first widely used release: - * - * source png.h png.h shared-lib - * version string int version - * ------- ------ ----- ---------- - * 0.89c "1.0 beta 3" 0.89 89 1.0.89 - * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90] - * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95] - * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96] - * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97] - * 0.97c 0.97 97 2.0.97 - * 0.98 0.98 98 2.0.98 - * 0.99 0.99 98 2.0.99 - * 0.99a-m 0.99 99 2.0.99 - * 1.00 1.00 100 2.1.0 [100 should be 10000] - * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000] - * 1.0.1 png.h string is 10001 2.1.0 - * 1.0.1a-e identical to the 10002 from here on, the shared library - * 1.0.2 source version) 10002 is 2.V where V is the source code - * 1.0.2a-b 10003 version, except as noted. - * 1.0.3 10003 - * 1.0.3a-d 10004 - * 1.0.4 10004 - * 1.0.4a-f 10005 - * 1.0.5 (+ 2 patches) 10005 - * 1.0.5a-d 10006 - * 1.0.5e-r 10100 (not source compatible) - * 1.0.5s-v 10006 (not binary compatible) - * 1.0.6 (+ 3 patches) 10006 (still binary incompatible) - * 1.0.6d-f 10007 (still binary incompatible) - * 1.0.6g 10007 - * 1.0.6h 10007 10.6h (testing xy.z so-numbering) - * 1.0.6i 10007 10.6i - * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0) - * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible) - * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible) - * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible) - * 1.0.7 1 10007 (still compatible) - * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4 - * 1.0.8rc1 1 10008 2.1.0.8rc1 - * 1.0.8 1 10008 2.1.0.8 - * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6 - * 1.0.9rc1 1 10009 2.1.0.9rc1 - * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10 - * 1.0.9rc2 1 10009 2.1.0.9rc2 - * 1.0.9 1 10009 2.1.0.9 - * 1.0.10beta1 1 10010 2.1.0.10beta1 - * 1.0.10rc1 1 10010 2.1.0.10rc1 - * 1.0.10 1 10010 2.1.0.10 - * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3 - * 1.0.11rc1 1 10011 2.1.0.11rc1 - * 1.0.11 1 10011 2.1.0.11 - * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2 - * 1.0.12rc1 2 10012 2.1.0.12rc1 - * 1.0.12 2 10012 2.1.0.12 - * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned) - * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2 - * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5 - * 1.2.0rc1 3 10200 3.1.2.0rc1 - * 1.2.0 3 10200 3.1.2.0 - * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4 - * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2 - * 1.2.1 3 10201 3.1.2.1 - * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6 - * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1 - * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1 - * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1 - * 1.0.13 10 10013 10.so.0.1.0.13 - * 1.2.2 12 10202 12.so.0.1.2.2 - * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6 - * 1.2.3 12 10203 12.so.0.1.2.3 - * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3 - * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1 - * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1 - * 1.0.14 10 10014 10.so.0.1.0.14 - * 1.2.4 13 10204 12.so.0.1.2.4 - * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2 - * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3 - * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3 - * 1.0.15 10 10015 10.so.0.1.0.15 - * 1.2.5 13 10205 12.so.0.1.2.5 - * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4 - * 1.0.16 10 10016 10.so.0.1.0.16 - * 1.2.6 13 10206 12.so.0.1.2.6 - * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2 - * 1.0.17rc1 10 10017 12.so.0.1.0.17rc1 - * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1 - * 1.0.17 10 10017 12.so.0.1.0.17 - * 1.2.7 13 10207 12.so.0.1.2.7 - * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5 - * 1.0.18rc1-5 10 10018 12.so.0.1.0.18rc1-5 - * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5 - * 1.0.18 10 10018 12.so.0.1.0.18 - * 1.2.8 13 10208 12.so.0.1.2.8 - * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3 - * 1.2.9beta4-11 13 10209 12.so.0.9[.0] - * 1.2.9rc1 13 10209 12.so.0.9[.0] - * 1.2.9 13 10209 12.so.0.9[.0] - * 1.2.10beta1-7 13 10210 12.so.0.10[.0] - * 1.2.10rc1-2 13 10210 12.so.0.10[.0] - * 1.2.10 13 10210 12.so.0.10[.0] - * 1.4.0beta1-5 14 10400 14.so.0.0[.0] - * 1.2.11beta1-4 13 10211 12.so.0.11[.0] - * 1.4.0beta7-8 14 10400 14.so.0.0[.0] - * 1.2.11 13 10211 12.so.0.11[.0] - * 1.2.12 13 10212 12.so.0.12[.0] - * 1.4.0beta9-14 14 10400 14.so.0.0[.0] - * 1.2.13 13 10213 12.so.0.13[.0] - * 1.4.0beta15-36 14 10400 14.so.0.0[.0] - * 1.4.0beta37-87 14 10400 14.so.14.0[.0] - * 1.4.0rc01 14 10400 14.so.14.0[.0] - * 1.4.0beta88-109 14 10400 14.so.14.0[.0] - * 1.4.0rc02-08 14 10400 14.so.14.0[.0] - * 1.4.0 14 10400 14.so.14.0[.0] - * 1.4.1beta01-03 14 10401 14.so.14.1[.0] - * 1.4.1rc01 14 10401 14.so.14.1[.0] - * 1.4.1beta04-12 14 10401 14.so.14.1[.0] - * 1.4.1 14 10401 14.so.14.1[.0] - * 1.4.2 14 10402 14.so.14.2[.0] - * 1.4.3 14 10403 14.so.14.3[.0] - * 1.4.4 14 10404 14.so.14.4[.0] - * 1.5.0beta01-58 15 10500 15.so.15.0[.0] - * 1.5.0rc01-07 15 10500 15.so.15.0[.0] - * 1.5.0 15 10500 15.so.15.0[.0] - * 1.5.1beta01-11 15 10501 15.so.15.1[.0] - * 1.5.1rc01-02 15 10501 15.so.15.1[.0] - * 1.5.1 15 10501 15.so.15.1[.0] - * 1.5.2beta01-03 15 10502 15.so.15.2[.0] - * 1.5.2rc01-03 15 10502 15.so.15.2[.0] - * 1.5.2 15 10502 15.so.15.2[.0] - * - * Henceforth the source version will match the shared-library major - * and minor numbers; the shared-library major version number will be - * used for changes in backward compatibility, as it is intended. The - * PNG_LIBPNG_VER macro, which is not used within libpng but is available - * for applications, is an unsigned integer of the form xyyzz corresponding - * to the source version x.y.z (leading zeros in y and z). Beta versions - * were given the previous public release number plus a letter, until - * version 1.0.6j; from then on they were given the upcoming public - * release number plus "betaNN" or "rcN". - * - * Binary incompatibility exists only when applications make direct access - * to the info_ptr or png_ptr members through png.h, and the compiled - * application is loaded with a different version of the library. - * - * DLLNUM will change each time there are forward or backward changes - * in binary compatibility (e.g., when a new feature is added). - * - * See libpng-manual.txt or libpng.3 for more information. The PNG - * specification is available as a W3C Recommendation and as an ISO - * Specification, -# endif - - /* Need the time information for converting tIME chunks, it - * defines struct tm: - */ -# ifdef PNG_CONVERT_tIME_SUPPORTED - /* "time.h" functions are not supported on all operating systems */ -# include -# endif -# endif - -/* Machine specific configuration. */ -# include "pngconf.h" -#endif - -/* - * Added at libpng-1.2.8 - * - * Ref MSDN: Private as priority over Special - * VS_FF_PRIVATEBUILD File *was not* built using standard release - * procedures. If this value is given, the StringFileInfo block must - * contain a PrivateBuild string. - * - * VS_FF_SPECIALBUILD File *was* built by the original company using - * standard release procedures but is a variation of the standard - * file of the same version number. If this value is given, the - * StringFileInfo block must contain a SpecialBuild string. - */ - -#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */ -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE) -#else -# ifdef PNG_LIBPNG_SPECIALBUILD -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL) -# else -# define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE) -# endif -#endif - -#ifndef PNG_VERSION_INFO_ONLY - -/* Inhibit C++ name-mangling for libpng functions but not for system calls. */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Version information for C files, stored in png.c. This had better match - * the version above. - */ -#define png_libpng_ver png_get_header_ver(NULL) - -/* This file is arranged in several sections: - * - * 1. Any configuration options that can be specified by for the application - * code when it is built. (Build time configuration is in pnglibconf.h) - * 2. Type definitions (base types are defined in pngconf.h), structure - * definitions. - * 3. Exported library functions. - * - * The library source code has additional files (principally pngpriv.h) that - * allow configuration of the library. - */ -/* Section 1: run time configuration - * See pnglibconf.h for build time configuration - * - * Run time configuration allows the application to choose between - * implementations of certain arithmetic APIs. The default is set - * at build time and recorded in pnglibconf.h, but it is safe to - * override these (and only these) settings. Note that this won't - * change what the library does, only application code, and the - * settings can (and probably should) be made on a per-file basis - * by setting the #defines before including png.h - * - * Use macros to read integers from PNG data or use the exported - * functions? - * PNG_USE_READ_MACROS: use the macros (see below) Note that - * the macros evaluate their argument multiple times. - * PNG_NO_USE_READ_MACROS: call the relevant library function. - * - * Use the alternative algorithm for compositing alpha samples that - * does not use division? - * PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division' - * algorithm. - * PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm. - * - * How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is - * false? - * PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error - * APIs to png_warning. - * Otherwise the calls are mapped to png_error. - */ - -/* Section 2: type definitions, including structures and compile time - * constants. - * See pngconf.h for base types that vary by machine/system - */ - -/* This triggers a compiler error in png.c, if png.c and png.h - * do not agree upon the version number. - */ -typedef char* png_libpng_version_1_5_2; - -/* Three color definitions. The order of the red, green, and blue, (and the - * exact size) is not important, although the size of the fields need to - * be png_byte or png_uint_16 (as defined below). - */ -typedef struct png_color_struct -{ - png_byte red; - png_byte green; - png_byte blue; -} png_color; -typedef png_color FAR * png_colorp; -typedef PNG_CONST png_color FAR * png_const_colorp; -typedef png_color FAR * FAR * png_colorpp; - -typedef struct png_color_16_struct -{ - png_byte index; /* used for palette files */ - png_uint_16 red; /* for use in red green blue files */ - png_uint_16 green; - png_uint_16 blue; - png_uint_16 gray; /* for use in grayscale files */ -} png_color_16; -typedef png_color_16 FAR * png_color_16p; -typedef PNG_CONST png_color_16 FAR * png_const_color_16p; -typedef png_color_16 FAR * FAR * png_color_16pp; - -typedef struct png_color_8_struct -{ - png_byte red; /* for use in red green blue files */ - png_byte green; - png_byte blue; - png_byte gray; /* for use in grayscale files */ - png_byte alpha; /* for alpha channel files */ -} png_color_8; -typedef png_color_8 FAR * png_color_8p; -typedef PNG_CONST png_color_8 FAR * png_const_color_8p; -typedef png_color_8 FAR * FAR * png_color_8pp; - -/* - * The following two structures are used for the in-core representation - * of sPLT chunks. - */ -typedef struct png_sPLT_entry_struct -{ - png_uint_16 red; - png_uint_16 green; - png_uint_16 blue; - png_uint_16 alpha; - png_uint_16 frequency; -} png_sPLT_entry; -typedef png_sPLT_entry FAR * png_sPLT_entryp; -typedef PNG_CONST png_sPLT_entry FAR * png_const_sPLT_entryp; -typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp; - -/* When the depth of the sPLT palette is 8 bits, the color and alpha samples - * occupy the LSB of their respective members, and the MSB of each member - * is zero-filled. The frequency member always occupies the full 16 bits. - */ - -typedef struct png_sPLT_struct -{ - png_charp name; /* palette name */ - png_byte depth; /* depth of palette samples */ - png_sPLT_entryp entries; /* palette entries */ - png_int_32 nentries; /* number of palette entries */ -} png_sPLT_t; -typedef png_sPLT_t FAR * png_sPLT_tp; -typedef PNG_CONST png_sPLT_t FAR * png_const_sPLT_tp; -typedef png_sPLT_t FAR * FAR * png_sPLT_tpp; - -#ifdef PNG_TEXT_SUPPORTED -/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file, - * and whether that contents is compressed or not. The "key" field - * points to a regular zero-terminated C string. The "text", "lang", and - * "lang_key" fields can be regular C strings, empty strings, or NULL pointers. - * However, the * structure returned by png_get_text() will always contain - * regular zero-terminated C strings (possibly empty), never NULL pointers, - * so they can be safely used in printf() and other string-handling functions. - */ -typedef struct png_text_struct -{ - int compression; /* compression value: - -1: tEXt, none - 0: zTXt, deflate - 1: iTXt, none - 2: iTXt, deflate */ - png_charp key; /* keyword, 1-79 character description of "text" */ - png_charp text; /* comment, may be an empty string (ie "") - or a NULL pointer */ - png_size_t text_length; /* length of the text string */ - png_size_t itxt_length; /* length of the itxt string */ - png_charp lang; /* language code, 0-79 characters - or a NULL pointer */ - png_charp lang_key; /* keyword translated UTF-8 string, 0 or more - chars or a NULL pointer */ -} png_text; -typedef png_text FAR * png_textp; -typedef PNG_CONST png_text FAR * png_const_textp; -typedef png_text FAR * FAR * png_textpp; -#endif - -/* Supported compression types for text in PNG files (tEXt, and zTXt). - * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */ -#define PNG_TEXT_COMPRESSION_NONE_WR -3 -#define PNG_TEXT_COMPRESSION_zTXt_WR -2 -#define PNG_TEXT_COMPRESSION_NONE -1 -#define PNG_TEXT_COMPRESSION_zTXt 0 -#define PNG_ITXT_COMPRESSION_NONE 1 -#define PNG_ITXT_COMPRESSION_zTXt 2 -#define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */ - -/* png_time is a way to hold the time in an machine independent way. - * Two conversions are provided, both from time_t and struct tm. There - * is no portable way to convert to either of these structures, as far - * as I know. If you know of a portable way, send it to me. As a side - * note - PNG has always been Year 2000 compliant! - */ -typedef struct png_time_struct -{ - png_uint_16 year; /* full year, as in, 1995 */ - png_byte month; /* month of year, 1 - 12 */ - png_byte day; /* day of month, 1 - 31 */ - png_byte hour; /* hour of day, 0 - 23 */ - png_byte minute; /* minute of hour, 0 - 59 */ - png_byte second; /* second of minute, 0 - 60 (for leap seconds) */ -} png_time; -typedef png_time FAR * png_timep; -typedef PNG_CONST png_time FAR * png_const_timep; -typedef png_time FAR * FAR * png_timepp; - -#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \ - defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED) -/* png_unknown_chunk is a structure to hold queued chunks for which there is - * no specific support. The idea is that we can use this to queue - * up private chunks for output even though the library doesn't actually - * know about their semantics. - */ -typedef struct png_unknown_chunk_t -{ - png_byte name[5]; - png_byte *data; - png_size_t size; - - /* libpng-using applications should NOT directly modify this byte. */ - png_byte location; /* mode of operation at read time */ -} -png_unknown_chunk; -typedef png_unknown_chunk FAR * png_unknown_chunkp; -typedef PNG_CONST png_unknown_chunk FAR * png_const_unknown_chunkp; -typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp; -#endif - -typedef struct png_info_def png_info; -typedef png_info FAR * png_infop; -typedef PNG_CONST png_info FAR * png_const_infop; -typedef png_info FAR * FAR * png_infopp; - -/* Maximum positive integer used in PNG is (2^31)-1 */ -#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL) -#define PNG_UINT_32_MAX ((png_uint_32)(-1)) -#define PNG_SIZE_MAX ((png_size_t)(-1)) - -/* These are constants for fixed point values encoded in the - * PNG specification manner (x100000) - */ -#define PNG_FP_1 100000 -#define PNG_FP_HALF 50000 - -/* These describe the color_type field in png_info. */ -/* color type masks */ -#define PNG_COLOR_MASK_PALETTE 1 -#define PNG_COLOR_MASK_COLOR 2 -#define PNG_COLOR_MASK_ALPHA 4 - -/* color types. Note that not all combinations are legal */ -#define PNG_COLOR_TYPE_GRAY 0 -#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE) -#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR) -#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA) -#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA) -/* aliases */ -#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA -#define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA - -/* This is for compression type. PNG 1.0-1.2 only define the single type. */ -#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */ -#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE - -/* This is for filter type. PNG 1.0-1.2 only define the single type. */ -#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */ -#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */ -#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE - -/* These are for the interlacing type. These values should NOT be changed. */ -#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */ -#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */ -#define PNG_INTERLACE_LAST 2 /* Not a valid value */ - -/* These are for the oFFs chunk. These values should NOT be changed. */ -#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */ -#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */ -#define PNG_OFFSET_LAST 2 /* Not a valid value */ - -/* These are for the pCAL chunk. These values should NOT be changed. */ -#define PNG_EQUATION_LINEAR 0 /* Linear transformation */ -#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */ -#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */ -#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */ -#define PNG_EQUATION_LAST 4 /* Not a valid value */ - -/* These are for the sCAL chunk. These values should NOT be changed. */ -#define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */ -#define PNG_SCALE_METER 1 /* meters per pixel */ -#define PNG_SCALE_RADIAN 2 /* radians per pixel */ -#define PNG_SCALE_LAST 3 /* Not a valid value */ - -/* These are for the pHYs chunk. These values should NOT be changed. */ -#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */ -#define PNG_RESOLUTION_METER 1 /* pixels/meter */ -#define PNG_RESOLUTION_LAST 2 /* Not a valid value */ - -/* These are for the sRGB chunk. These values should NOT be changed. */ -#define PNG_sRGB_INTENT_PERCEPTUAL 0 -#define PNG_sRGB_INTENT_RELATIVE 1 -#define PNG_sRGB_INTENT_SATURATION 2 -#define PNG_sRGB_INTENT_ABSOLUTE 3 -#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */ - -/* This is for text chunks */ -#define PNG_KEYWORD_MAX_LENGTH 79 - -/* Maximum number of entries in PLTE/sPLT/tRNS arrays */ -#define PNG_MAX_PALETTE_LENGTH 256 - -/* These determine if an ancillary chunk's data has been successfully read - * from the PNG header, or if the application has filled in the corresponding - * data in the info_struct to be written into the output file. The values - * of the PNG_INFO_ defines should NOT be changed. - */ -#define PNG_INFO_gAMA 0x0001 -#define PNG_INFO_sBIT 0x0002 -#define PNG_INFO_cHRM 0x0004 -#define PNG_INFO_PLTE 0x0008 -#define PNG_INFO_tRNS 0x0010 -#define PNG_INFO_bKGD 0x0020 -#define PNG_INFO_hIST 0x0040 -#define PNG_INFO_pHYs 0x0080 -#define PNG_INFO_oFFs 0x0100 -#define PNG_INFO_tIME 0x0200 -#define PNG_INFO_pCAL 0x0400 -#define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */ -#define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */ -#define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */ -#define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */ -#define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */ - -/* This is used for the transformation routines, as some of them - * change these values for the row. It also should enable using - * the routines for other purposes. - */ -typedef struct png_row_info_struct -{ - png_uint_32 width; /* width of row */ - png_size_t rowbytes; /* number of bytes in row */ - png_byte color_type; /* color type of row */ - png_byte bit_depth; /* bit depth of row */ - png_byte channels; /* number of channels (1, 2, 3, or 4) */ - png_byte pixel_depth; /* bits per pixel (depth * channels) */ -} png_row_info; - -typedef png_row_info FAR * png_row_infop; -typedef png_row_info FAR * FAR * png_row_infopp; - -/* These are the function types for the I/O functions and for the functions - * that allow the user to override the default I/O functions with his or her - * own. The png_error_ptr type should match that of user-supplied warning - * and error functions, while the png_rw_ptr type should match that of the - * user read/write data functions. Note that the 'write' function must not - * modify the buffer it is passed. The 'read' function, on the other hand, is - * expected to return the read data in the buffer. - */ -typedef struct png_struct_def png_struct; -typedef PNG_CONST png_struct FAR * png_const_structp; -typedef png_struct FAR * png_structp; - -typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp)); -typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t)); -typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp)); -typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32, - int)); -typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32, - int)); - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop)); -typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop)); - -/* The following callback receives png_uint_32 row_number, int pass for the - * png_bytep data of the row. When transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep, - png_uint_32, int)); -#endif - -#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ - defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) -typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop, - png_bytep)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp, - png_unknown_chunkp)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp)); -#endif - -#ifdef PNG_SETJMP_SUPPORTED -/* This must match the function definition in , and the - * application must include this before png.h to obtain the definition - * of jmp_buf. The function is required to be PNG_NORETURN. (Note that - * PNG_PTR_NORETURN is used here because current versions of the Microsoft - * C compiler do not support the PNG_NORETURN attribute on a pointer.) - * - * If you get a type warning from the compiler when linking against this line - * then your compiler has 'longjmp' that does not match the requirements of the - * compiler that built libpng. You will have to write a wrapper function for - * your compiler's longjmp and call png_set_longjmp_fn directly (not via the - * png_jmpbuf macro.) - * - * If you get a warning here while building the library you will need to make - * changes to ensure that pnglibconf.h records the calling convention used by - * your compiler. This may be very difficult - try using a different compiler - * to build the library! - */ -typedef PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), - PNG_PTR_NORETURN); -#endif - -/* Transform masks for the high-level interface */ -#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */ -#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */ -#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */ -#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */ -#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */ -#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */ -#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */ -#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */ -#define PNG_TRANSFORM_BGR 0x0080 /* read and write */ -#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */ -#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */ -#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */ -#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* write only */ -/* Added to libpng-1.2.34 */ -#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER -#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */ -/* Added to libpng-1.4.0 */ -#define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */ - -/* Flags for MNG supported features */ -#define PNG_FLAG_MNG_EMPTY_PLTE 0x01 -#define PNG_FLAG_MNG_FILTER_64 0x04 -#define PNG_ALL_MNG_FEATURES 0x05 - -/* NOTE: prior to 1.5 these functions had no 'API' style declaration, - * this allowed the zlib default functions to be used on Windows - * platforms. In 1.5 the zlib default malloc (which just calls malloc and - * ignores the first argument) should be completely compatible with the - * following. - */ -typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp, - png_alloc_size_t)); -typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp)); - -typedef png_struct FAR * FAR * png_structpp; - -/* Section 3: exported functions - * Here are the function definitions most commonly used. This is not - * the place to find out how to use libpng. See libpng-manual.txt for the - * full explanation, see example.c for the summary. This just provides - * a simple one line description of the use of each function. - * - * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in - * pngconf.h and in the *.dfn files in the scripts directory. - * - * PNG_EXPORT(ordinal, type, name, (args)); - * - * ordinal: ordinal that is used while building - * *.def files. The ordinal value is only - * relevant when preprocessing png.h with - * the *.dfn files for building symbol table - * entries, and are removed by pngconf.h. - * type: return type of the function - * name: function name - * args: function arguments, with types - * - * When we wish to append attributes to a function prototype we use - * the PNG_EXPORTA() macro instead. - * - * PNG_EXPORTA(ordinal, type, name, (args), attributes); - * - * ordinal, type, name, and args: same as in PNG_EXPORT(). - * attributes: function attributes - */ - -/* Returns the version number of the library */ -PNG_EXPORT(1, png_uint_32, png_access_version_number, (void)); - -/* Tell lib we have already handled the first magic bytes. - * Handling more than 8 bytes from the beginning of the file is an error. - */ -PNG_EXPORT(2, void, png_set_sig_bytes, (png_structp png_ptr, int num_bytes)); - -/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a - * PNG file. Returns zero if the supplied bytes match the 8-byte PNG - * signature, and non-zero otherwise. Having num_to_check == 0 or - * start > 7 will always fail (ie return non-zero). - */ -PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start, - png_size_t num_to_check)); - -/* Simple signature checking function. This is the same as calling - * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). - */ -#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n)) - -/* Allocate and initialize png_ptr struct for reading, and any other memory. */ -PNG_EXPORTA(4, png_structp, png_create_read_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warn_fn), - PNG_ALLOCATED); - -/* Allocate and initialize png_ptr struct for writing, and any other memory */ -PNG_EXPORTA(5, png_structp, png_create_write_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn), - PNG_ALLOCATED); - -PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size, - (png_const_structp png_ptr)); - -PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structp png_ptr, - png_size_t size)); - -/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp - * match up. - */ -#ifdef PNG_SETJMP_SUPPORTED -/* This function returns the jmp_buf built in to *png_ptr. It must be - * supplied with an appropriate 'longjmp' function to use on that jmp_buf - * unless the default error function is overridden in which case NULL is - * acceptable. The size of the jmp_buf is checked against the actual size - * allocated by the library - the call will return NULL on a mismatch - * indicating an ABI mismatch. - */ -PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structp png_ptr, - png_longjmp_ptr longjmp_fn, size_t jmp_buf_size)); -# define png_jmpbuf(png_ptr) \ - (*png_set_longjmp_fn((png_ptr), longjmp, sizeof (jmp_buf))) -#else -# define png_jmpbuf(png_ptr) \ - (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP) -#endif -/* This function should be used by libpng applications in place of - * longjmp(png_ptr->jmpbuf, val). If longjmp_fn() has been set, it - * will use it; otherwise it will call PNG_ABORT(). This function was - * added in libpng-1.5.0. - */ -PNG_EXPORTA(9, void, png_longjmp, (png_structp png_ptr, int val), - PNG_NORETURN); - -#ifdef PNG_READ_SUPPORTED -/* Reset the compression stream */ -PNG_EXPORT(10, int, png_reset_zstream, (png_structp png_ptr)); -#endif - -/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */ -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(11, png_structp, png_create_read_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -PNG_EXPORTA(12, png_structp, png_create_write_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -#endif - -/* Write the PNG file signature. */ -PNG_EXPORT(13, void, png_write_sig, (png_structp png_ptr)); - -/* Write a PNG chunk - size, type, (optional) data, CRC. */ -PNG_EXPORT(14, void, png_write_chunk, (png_structp png_ptr, png_const_bytep - chunk_name, png_const_bytep data, png_size_t length)); - -/* Write the start of a PNG chunk - length and chunk name. */ -PNG_EXPORT(15, void, png_write_chunk_start, (png_structp png_ptr, - png_const_bytep chunk_name, png_uint_32 length)); - -/* Write the data of a PNG chunk started with png_write_chunk_start(). */ -PNG_EXPORT(16, void, png_write_chunk_data, (png_structp png_ptr, - png_const_bytep data, png_size_t length)); - -/* Finish a chunk started with png_write_chunk_start() (includes CRC). */ -PNG_EXPORT(17, void, png_write_chunk_end, (png_structp png_ptr)); - -/* Allocate and initialize the info structure */ -PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_structp png_ptr), - PNG_ALLOCATED); - -PNG_EXPORT(19, void, png_info_init_3, (png_infopp info_ptr, - png_size_t png_info_struct_size)); - -/* Writes all the PNG information before the image. */ -PNG_EXPORT(20, void, png_write_info_before_PLTE, - (png_structp png_ptr, png_infop info_ptr)); -PNG_EXPORT(21, void, png_write_info, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the information before the actual image data. */ -PNG_EXPORT(22, void, png_read_info, - (png_structp png_ptr, png_infop info_ptr)); -#endif - -#ifdef PNG_TIME_RFC1123_SUPPORTED -PNG_EXPORT(23, png_const_charp, png_convert_to_rfc1123, - (png_structp png_ptr, - png_const_timep ptime)); -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED -/* Convert from a struct tm to png_time */ -PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime, - PNG_CONST struct tm FAR * ttime)); - -/* Convert from time_t to png_time. Uses gmtime() */ -PNG_EXPORT(25, void, png_convert_from_time_t, - (png_timep ptime, time_t ttime)); -#endif /* PNG_CONVERT_tIME_SUPPORTED */ - -#ifdef PNG_READ_EXPAND_SUPPORTED -/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */ -PNG_EXPORT(26, void, png_set_expand, (png_structp png_ptr)); -PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structp png_ptr)); -PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structp png_ptr)); -PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_EXPAND_16_SUPPORTED -/* Expand to 16 bit channels, forces conversion of palette to RGB and expansion - * of a tRNS chunk if present. - */ -PNG_EXPORT(221, void, png_set_expand_16, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) -/* Use blue, green, red order for pixels. */ -PNG_EXPORT(30, void, png_set_bgr, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED -/* Expand the grayscale to 24-bit RGB if necessary. */ -PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED -/* Reduce RGB to grayscale. */ -PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structp png_ptr, - int error_action, double red, double green)); -PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structp png_ptr, - int error_action, png_fixed_point red, png_fixed_point green)); - -PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structp - png_ptr)); -#endif - -PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth, - png_colorp palette)); - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED -PNG_EXPORT(36, void, png_set_strip_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) -PNG_EXPORT(37, void, png_set_swap_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) -PNG_EXPORT(38, void, png_set_invert_alpha, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) -/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */ -PNG_EXPORT(39, void, png_set_filler, (png_structp png_ptr, png_uint_32 filler, - int flags)); -/* The values of the PNG_FILLER_ defines should NOT be changed */ -# define PNG_FILLER_BEFORE 0 -# define PNG_FILLER_AFTER 1 -/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ -PNG_EXPORT(40, void, png_set_add_alpha, - (png_structp png_ptr, png_uint_32 filler, - int flags)); -#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */ - -#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) -/* Swap bytes in 16-bit depth files. */ -PNG_EXPORT(41, void, png_set_swap, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) -/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */ -PNG_EXPORT(42, void, png_set_packing, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \ - defined(PNG_WRITE_PACKSWAP_SUPPORTED) -/* Swap packing order of pixels in bytes. */ -PNG_EXPORT(43, void, png_set_packswap, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) -/* Converts files to legal bit depths. */ -PNG_EXPORT(44, void, png_set_shift, (png_structp png_ptr, png_const_color_8p - true_bits)); -#endif - -#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ - defined(PNG_WRITE_INTERLACING_SUPPORTED) -/* Have the code handle the interlacing. Returns the number of passes. - * MUST be called before png_read_update_info or png_start_read_image, - * otherwise it will not have the desired effect. Note that it is still - * necessary to call png_read_row or png_read_rows png_get_image_height - * times for each pass. -*/ -PNG_EXPORT(45, int, png_set_interlace_handling, (png_structp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) -/* Invert monochrome files */ -PNG_EXPORT(46, void, png_set_invert_mono, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_BACKGROUND_SUPPORTED -/* Handle alpha and tRNS by replacing with a background color. */ -PNG_FP_EXPORT(47, void, png_set_background, (png_structp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, double background_gamma)); -PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, png_fixed_point background_gamma)); -#endif -#ifdef PNG_READ_BACKGROUND_SUPPORTED -# define PNG_BACKGROUND_GAMMA_UNKNOWN 0 -# define PNG_BACKGROUND_GAMMA_SCREEN 1 -# define PNG_BACKGROUND_GAMMA_FILE 2 -# define PNG_BACKGROUND_GAMMA_UNIQUE 3 -#endif - -#ifdef PNG_READ_16_TO_8_SUPPORTED -/* Strip the second byte of information from a 16-bit depth file. */ -PNG_EXPORT(48, void, png_set_strip_16, (png_structp png_ptr)); -#endif - -#ifdef PNG_READ_QUANTIZE_SUPPORTED -/* Turn on quantizing, and reduce the palette to the number of colors - * available. - */ -PNG_EXPORT(49, void, png_set_quantize, - (png_structp png_ptr, png_colorp palette, - int num_palette, int maximum_colors, png_const_uint_16p histogram, - int full_quantize)); -#endif - -#ifdef PNG_READ_GAMMA_SUPPORTED -/* The threshold on gamma processing is configurable but hard-wired into the - * library. The following is the floating point variant. - */ -#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001) - -/* Handle gamma correction. Screen_gamma=(display_exponent) */ -PNG_FP_EXPORT(50, void, png_set_gamma, - (png_structp png_ptr, double screen_gamma, - double default_file_gamma)); -PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structp png_ptr, - png_fixed_point screen_gamma, png_fixed_point default_file_gamma)); -#endif - -#ifdef PNG_WRITE_FLUSH_SUPPORTED -/* Set how many lines between output flushes - 0 for no flushing */ -PNG_EXPORT(51, void, png_set_flush, (png_structp png_ptr, int nrows)); -/* Flush the current PNG output buffer */ -PNG_EXPORT(52, void, png_write_flush, (png_structp png_ptr)); -#endif - -/* Optional update palette with requested transformations */ -PNG_EXPORT(53, void, png_start_read_image, (png_structp png_ptr)); - -/* Optional call to update the users info structure */ -PNG_EXPORT(54, void, png_read_update_info, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read one or more rows of image data. */ -PNG_EXPORT(55, void, png_read_rows, (png_structp png_ptr, png_bytepp row, - png_bytepp display_row, png_uint_32 num_rows)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read a row of data. */ -PNG_EXPORT(56, void, png_read_row, (png_structp png_ptr, png_bytep row, - png_bytep display_row)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the whole image into memory at once. */ -PNG_EXPORT(57, void, png_read_image, (png_structp png_ptr, png_bytepp image)); -#endif - -/* Write a row of image data */ -PNG_EXPORT(58, void, png_write_row, - (png_structp png_ptr, png_const_bytep row)); - -/* Write a few rows of image data: (*row) is not written; however, the type - * is declared as writeable to maintain compatibility with previous versions - * of libpng and to allow the 'display_row' array from read_rows to be passed - * unchanged to write_rows. - */ -PNG_EXPORT(59, void, png_write_rows, (png_structp png_ptr, png_bytepp row, - png_uint_32 num_rows)); - -/* Write the image data */ -PNG_EXPORT(60, void, png_write_image, - (png_structp png_ptr, png_bytepp image)); - -/* Write the end of the PNG file. */ -PNG_EXPORT(61, void, png_write_end, - (png_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the end of the PNG file. */ -PNG_EXPORT(62, void, png_read_end, (png_structp png_ptr, png_infop info_ptr)); -#endif - -/* Free any memory associated with the png_info_struct */ -PNG_EXPORT(63, void, png_destroy_info_struct, (png_structp png_ptr, - png_infopp info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr)); - -/* Set the libpng method of handling chunk CRC errors */ -PNG_EXPORT(66, void, png_set_crc_action, - (png_structp png_ptr, int crit_action, int ancil_action)); - -/* Values for png_set_crc_action() say how to handle CRC errors in - * ancillary and critical chunks, and whether to use the data contained - * therein. Note that it is impossible to "discard" data in a critical - * chunk. For versions prior to 0.90, the action was always error/quit, - * whereas in version 0.90 and later, the action for CRC errors in ancillary - * chunks is warn/discard. These values should NOT be changed. - * - * value action:critical action:ancillary - */ -#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */ -#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */ -#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */ -#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */ -#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */ -#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */ - -/* These functions give the user control over the scan-line filtering in - * libpng and the compression methods used by zlib. These functions are - * mainly useful for testing, as the defaults should work with most users. - * Those users who are tight on memory or want faster performance at the - * expense of compression can modify them. See the compression library - * header file (zlib.h) for an explination of the compression functions. - */ - -/* Set the filtering method(s) used by libpng. Currently, the only valid - * value for "method" is 0. - */ -PNG_EXPORT(67, void, png_set_filter, - (png_structp png_ptr, int method, int filters)); - -/* Flags for png_set_filter() to say which filters to use. The flags - * are chosen so that they don't conflict with real filter types - * below, in case they are supplied instead of the #defined constants. - * These values should NOT be changed. - */ -#define PNG_NO_FILTERS 0x00 -#define PNG_FILTER_NONE 0x08 -#define PNG_FILTER_SUB 0x10 -#define PNG_FILTER_UP 0x20 -#define PNG_FILTER_AVG 0x40 -#define PNG_FILTER_PAETH 0x80 -#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \ - PNG_FILTER_AVG | PNG_FILTER_PAETH) - -/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now. - * These defines should NOT be changed. - */ -#define PNG_FILTER_VALUE_NONE 0 -#define PNG_FILTER_VALUE_SUB 1 -#define PNG_FILTER_VALUE_UP 2 -#define PNG_FILTER_VALUE_AVG 3 -#define PNG_FILTER_VALUE_PAETH 4 -#define PNG_FILTER_VALUE_LAST 5 - -#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* EXPERIMENTAL */ -/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_ - * defines, either the default (minimum-sum-of-absolute-differences), or - * the experimental method (weighted-minimum-sum-of-absolute-differences). - * - * Weights are factors >= 1.0, indicating how important it is to keep the - * filter type consistent between rows. Larger numbers mean the current - * filter is that many times as likely to be the same as the "num_weights" - * previous filters. This is cumulative for each previous row with a weight. - * There needs to be "num_weights" values in "filter_weights", or it can be - * NULL if the weights aren't being specified. Weights have no influence on - * the selection of the first row filter. Well chosen weights can (in theory) - * improve the compression for a given image. - * - * Costs are factors >= 1.0 indicating the relative decoding costs of a - * filter type. Higher costs indicate more decoding expense, and are - * therefore less likely to be selected over a filter with lower computational - * costs. There needs to be a value in "filter_costs" for each valid filter - * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't - * setting the costs. Costs try to improve the speed of decompression without - * unduly increasing the compressed image size. - * - * A negative weight or cost indicates the default value is to be used, and - * values in the range [0.0, 1.0) indicate the value is to remain unchanged. - * The default values for both weights and costs are currently 1.0, but may - * change if good general weighting/cost heuristics can be found. If both - * the weights and costs are set to 1.0, this degenerates the WEIGHTED method - * to the UNWEIGHTED method, but with added encoding time/computation. - */ -PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structp png_ptr, - int heuristic_method, int num_weights, png_const_doublep filter_weights, - png_const_doublep filter_costs)); -PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed, - (png_structp png_ptr, - int heuristic_method, int num_weights, png_const_fixed_point_p - filter_weights, png_const_fixed_point_p filter_costs)); -#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */ - -/* Heuristic used for row filter selection. These defines should NOT be - * changed. - */ -#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */ -#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */ -#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */ -#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */ - -/* Set the library compression level. Currently, valid values range from - * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 - * (0 - no compression, 9 - "maximal" compression). Note that tests have - * shown that zlib compression levels 3-6 usually perform as well as level 9 - * for PNG images, and do considerably fewer caclulations. In the future, - * these values may not correspond directly to the zlib compression levels. - */ -PNG_EXPORT(69, void, png_set_compression_level, - (png_structp png_ptr, int level)); - -PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structp png_ptr, - int mem_level)); - -PNG_EXPORT(71, void, png_set_compression_strategy, (png_structp png_ptr, - int strategy)); - -PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structp png_ptr, - int window_bits)); - -PNG_EXPORT(73, void, png_set_compression_method, (png_structp png_ptr, - int method)); - -/* These next functions are called for input/output, memory, and error - * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c, - * and call standard C I/O routines such as fread(), fwrite(), and - * fprintf(). These functions can be made to use other I/O routines - * at run time for those applications that need to handle I/O in a - * different manner by calling png_set_???_fn(). See libpng-manual.txt for - * more information. - */ - -#ifdef PNG_STDIO_SUPPORTED -/* Initialize the input/output for the PNG file to the default functions. */ -PNG_EXPORT(74, void, png_init_io, (png_structp png_ptr, png_FILE_p fp)); -#endif - -/* Replace the (error and abort), and warning functions with user - * supplied functions. If no messages are to be printed you must still - * write and use replacement functions. The replacement error_fn should - * still do a longjmp to the last setjmp location if you are using this - * method of error handling. If error_fn or warning_fn is NULL, the - * default function will be used. - */ - -PNG_EXPORT(75, void, png_set_error_fn, - (png_structp png_ptr, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warning_fn)); - -/* Return the user pointer associated with the error functions */ -PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structp png_ptr)); - -/* Replace the default data output functions with a user supplied one(s). - * If buffered output is not used, then output_flush_fn can be set to NULL. - * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time - * output_flush_fn will be ignored (and thus can be NULL). - * It is probably a mistake to use NULL for output_flush_fn if - * write_data_fn is not also NULL unless you have built libpng with - * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's - * default flush function, which uses the standard *FILE structure, will - * be used. - */ -PNG_EXPORT(77, void, png_set_write_fn, (png_structp png_ptr, png_voidp io_ptr, - png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)); - -/* Replace the default data input function with a user supplied one. */ -PNG_EXPORT(78, void, png_set_read_fn, (png_structp png_ptr, png_voidp io_ptr, - png_rw_ptr read_data_fn)); - -/* Return the user pointer associated with the I/O functions */ -PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_structp png_ptr)); - -PNG_EXPORT(80, void, png_set_read_status_fn, (png_structp png_ptr, - png_read_status_ptr read_row_fn)); - -PNG_EXPORT(81, void, png_set_write_status_fn, (png_structp png_ptr, - png_write_status_ptr write_row_fn)); - -#ifdef PNG_USER_MEM_SUPPORTED -/* Replace the default memory allocation functions with user supplied one(s). */ -PNG_EXPORT(82, void, png_set_mem_fn, (png_structp png_ptr, png_voidp mem_ptr, - png_malloc_ptr malloc_fn, png_free_ptr free_fn)); -/* Return the user pointer associated with the memory functions */ -PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structp png_ptr)); -#endif - -#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structp png_ptr, - png_user_transform_ptr read_user_transform_fn)); -#endif - -#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structp png_ptr, - png_user_transform_ptr write_user_transform_fn)); -#endif - -#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED -PNG_EXPORT(86, void, png_set_user_transform_info, (png_structp png_ptr, - png_voidp user_transform_ptr, int user_transform_depth, - int user_transform_channels)); -/* Return the user pointer associated with the user transform functions */ -PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr, - (png_const_structp png_ptr)); -#endif - -#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED -/* Return information about the row currently being processed. Note that these - * APIs do not fail but will return unexpected results if called outside a user - * transform callback. Also note that when transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structp)); -PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structp)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structp png_ptr, - png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); -PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structp png_ptr)); -#endif - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -/* Sets the function callbacks for the push reader, and a pointer to a - * user-defined structure available to the callback functions. - */ -PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structp png_ptr, - png_voidp progressive_ptr, png_progressive_info_ptr info_fn, - png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn)); - -/* Returns the user pointer associated with the push read functions */ -PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, (png_const_structp png_ptr)); - -/* Function to be called when data becomes available */ -PNG_EXPORT(92, void, png_process_data, - (png_structp png_ptr, png_infop info_ptr, - png_bytep buffer, png_size_t buffer_size)); - -/* A function which may be called *only* within png_process_data to stop the - * processing of any more data. The function returns the number of bytes - * remaining, excluding any that libpng has cached internally. A subsequent - * call to png_process_data must supply these bytes again. If the argument - * 'save' is set to true the routine will first save all the pending data and - * will always return 0. - */ -PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structp, int save)); - -/* A function which may be called *only* outside (after) a call to - * png_process_data. It returns the number of bytes of data to skip in the - * input. Normally it will return 0, but if it returns a non-zero value the - * application must skip than number of bytes of input data and pass the - * following data to the next call to png_process_data. - */ -PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structp)); - -/* Function that combines rows. 'new_row' is a flag that should come from - * the callback and be non-NULL if anything needs to be done; the library - * stores its own version of the new data internally and ignores the passed - * in value. - */ -PNG_EXPORT(93, void, png_progressive_combine_row, (png_structp png_ptr, - png_bytep old_row, png_const_bytep new_row)); -#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ - -PNG_EXPORTA(94, png_voidp, png_malloc, - (png_structp png_ptr, png_alloc_size_t size), - PNG_ALLOCATED); -/* Added at libpng version 1.4.0 */ -PNG_EXPORTA(95, png_voidp, png_calloc, - (png_structp png_ptr, png_alloc_size_t size), - PNG_ALLOCATED); - -/* Added at libpng version 1.2.4 */ -PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_structp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Frees a pointer allocated by png_malloc() */ -PNG_EXPORT(97, void, png_free, (png_structp png_ptr, png_voidp ptr)); - -/* Free data that was allocated internally */ -PNG_EXPORT(98, void, png_free_data, - (png_structp png_ptr, png_infop info_ptr, png_uint_32 free_me, int num)); - -/* Reassign responsibility for freeing existing data, whether allocated - * by libpng or by the application */ -PNG_EXPORT(99, void, png_data_freer, - (png_structp png_ptr, png_infop info_ptr, int freer, png_uint_32 mask)); - -/* Assignments for png_data_freer */ -#define PNG_DESTROY_WILL_FREE_DATA 1 -#define PNG_SET_WILL_FREE_DATA 1 -#define PNG_USER_WILL_FREE_DATA 2 -/* Flags for png_ptr->free_me and info_ptr->free_me */ -#define PNG_FREE_HIST 0x0008 -#define PNG_FREE_ICCP 0x0010 -#define PNG_FREE_SPLT 0x0020 -#define PNG_FREE_ROWS 0x0040 -#define PNG_FREE_PCAL 0x0080 -#define PNG_FREE_SCAL 0x0100 -#define PNG_FREE_UNKN 0x0200 -#define PNG_FREE_LIST 0x0400 -#define PNG_FREE_PLTE 0x1000 -#define PNG_FREE_TRNS 0x2000 -#define PNG_FREE_TEXT 0x4000 -#define PNG_FREE_ALL 0x7fff -#define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */ - -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_structp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); -PNG_EXPORT(101, void, png_free_default, (png_structp png_ptr, png_voidp ptr)); -#endif - -#ifdef PNG_ERROR_TEXT_SUPPORTED -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(102, void, png_error, - (png_structp png_ptr, png_const_charp error_message), - PNG_NORETURN); - -/* The same, but the chunk name is prepended to the error string. */ -PNG_EXPORTA(103, void, png_chunk_error, (png_structp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -#else -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(104, void, png_err, (png_structp png_ptr), PNG_NORETURN); -#endif - -/* Non-fatal error in libpng. Can continue, but may have a problem. */ -PNG_EXPORT(105, void, png_warning, (png_structp png_ptr, - png_const_charp warning_message)); - -/* Non-fatal error in libpng, chunk name is prepended to message. */ -PNG_EXPORT(106, void, png_chunk_warning, (png_structp png_ptr, - png_const_charp warning_message)); - -#ifdef PNG_BENIGN_ERRORS_SUPPORTED -/* Benign error in libpng. Can continue, but may have a problem. - * User can choose whether to handle as a fatal error or as a warning. */ -# undef png_benign_error -PNG_EXPORT(107, void, png_benign_error, (png_structp png_ptr, - png_const_charp warning_message)); - -/* Same, chunk name is prepended to message. */ -# undef png_chunk_benign_error -PNG_EXPORT(108, void, png_chunk_benign_error, (png_structp png_ptr, - png_const_charp warning_message)); - -PNG_EXPORT(109, void, png_set_benign_errors, - (png_structp png_ptr, int allowed)); -#else -# ifdef PNG_ALLOW_BENIGN_ERRORS -# define png_benign_error png_warning -# define png_chunk_benign_error png_chunk_warning -# else -# define png_benign_error png_error -# define png_chunk_benign_error png_chunk_error -# endif -#endif - -/* The png_set_ functions are for storing values in the png_info_struct. - * Similarly, the png_get_ calls are used to read values from the - * png_info_struct, either storing the parameters in the passed variables, or - * setting pointers into the png_info_struct where the data is stored. The - * png_get_ functions return a non-zero value if the data was available - * in info_ptr, or return zero and do not change any of the parameters if the - * data was not available. - * - * These functions should be used instead of directly accessing png_info - * to avoid problems with future changes in the size and internal layout of - * png_info_struct. - */ -/* Returns "flag" if chunk data is valid in info_ptr. */ -PNG_EXPORT(110, png_uint_32, png_get_valid, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_32 flag)); - -/* Returns number of bytes needed to hold a transformed row. */ -PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* Returns row_pointers, which is an array of pointers to scanlines that was - * returned from png_read_png(). - */ -PNG_EXPORT(112, png_bytepp, png_get_rows, - (png_const_structp png_ptr, png_const_infop info_ptr)); -/* Set row_pointers, which is an array of pointers to scanlines for use - * by png_write_png(). - */ -PNG_EXPORT(113, void, png_set_rows, (png_structp png_ptr, - png_infop info_ptr, png_bytepp row_pointers)); -#endif - -/* Returns number of color channels in image. */ -PNG_EXPORT(114, png_byte, png_get_channels, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -#ifdef PNG_EASY_ACCESS_SUPPORTED -/* Returns image width in pixels. */ -PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image height in pixels. */ -PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image bit_depth. */ -PNG_EXPORT(117, png_byte, png_get_bit_depth, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns image color_type. */ -PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image filter_type. */ -PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image interlace_type. */ -PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image compression_type. */ -PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structp png_ptr, - png_const_infop info_ptr)); - -/* Returns image resolution in pixels per meter, from pHYs chunk data. */ -PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns pixel aspect ratio, computed from pHYs chunk data. */ -PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ -PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(128, png_int_32, png_get_x_offset_microns, - (png_const_structp png_ptr, png_const_infop info_ptr)); -PNG_EXPORT(129, png_int_32, png_get_y_offset_microns, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -#endif /* PNG_EASY_ACCESS_SUPPORTED */ - -/* Returns pointer to signature string read from PNG header */ -PNG_EXPORT(130, png_const_bytep, png_get_signature, - (png_const_structp png_ptr, png_infop info_ptr)); - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(131, png_uint_32, png_get_bKGD, - (png_const_structp png_ptr, png_infop info_ptr, - png_color_16p *background)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(132, void, png_set_bKGD, (png_structp png_ptr, png_infop info_ptr, - png_const_color_16p background)); -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structp png_ptr, - png_const_infop info_ptr, double *white_x, double *white_y, double *red_x, - double *red_y, double *green_x, double *green_y, double *blue_x, - double *blue_y)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* Otherwise not implemented */ -PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed, - (png_const_structp png_ptr, - png_const_infop info_ptr, png_fixed_point *int_white_x, - png_fixed_point *int_white_y, png_fixed_point *int_red_x, - png_fixed_point *int_red_y, png_fixed_point *int_green_x, - png_fixed_point *int_green_y, png_fixed_point *int_blue_x, - png_fixed_point *int_blue_y)); -#endif -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(135, void, png_set_cHRM, - (png_structp png_ptr, png_infop info_ptr, - double white_x, double white_y, double red_x, double red_y, double green_x, - double green_y, double blue_x, double blue_y)); -PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_structp png_ptr, - png_infop info_ptr, png_fixed_point int_white_x, - png_fixed_point int_white_y, png_fixed_point int_red_x, - png_fixed_point int_red_y, png_fixed_point int_green_x, - png_fixed_point int_green_y, png_fixed_point int_blue_x, - png_fixed_point int_blue_y)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, - (png_const_structp png_ptr, png_const_infop info_ptr, - double *file_gamma)); -PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_fixed_point *int_file_gamma)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(139, void, png_set_gAMA, (png_structp png_ptr, - png_infop info_ptr, double file_gamma)); -PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_structp png_ptr, - png_infop info_ptr, png_fixed_point int_file_gamma)); -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(141, png_uint_32, png_get_hIST, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_16p *hist)); -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(142, void, png_set_hIST, (png_structp png_ptr, - png_infop info_ptr, png_const_uint_16p hist)); -#endif - -PNG_EXPORT(143, png_uint_32, png_get_IHDR, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, - int *interlace_method, int *compression_method, int *filter_method)); - -PNG_EXPORT(144, void, png_set_IHDR, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, - int interlace_method, int compression_method, int filter_method)); - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(145, png_uint_32, png_get_oFFs, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)); -#endif - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(146, void, png_set_oFFs, - (png_structp png_ptr, png_infop info_ptr, - png_int_32 offset_x, png_int_32 offset_y, int unit_type)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(147, png_uint_32, png_get_pCAL, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, - int *nparams, - png_charp *units, png_charpp *params)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(148, void, png_set_pCAL, (png_structp png_ptr, - png_infop info_ptr, - png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type, - int nparams, png_const_charp units, png_charpp params)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(149, png_uint_32, png_get_pHYs, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(150, void, png_set_pHYs, - (png_structp png_ptr, png_infop info_ptr, - png_uint_32 res_x, png_uint_32 res_y, int unit_type)); -#endif - -PNG_EXPORT(151, png_uint_32, png_get_PLTE, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_colorp *palette, int *num_palette)); - -PNG_EXPORT(152, void, png_set_PLTE, - (png_structp png_ptr, png_infop info_ptr, - png_const_colorp palette, int num_palette)); - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(153, png_uint_32, png_get_sBIT, - (png_const_structp png_ptr, png_infop info_ptr, - png_color_8p *sig_bit)); -#endif - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(154, void, png_set_sBIT, - (png_structp png_ptr, png_infop info_ptr, png_const_color_8p sig_bit)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structp png_ptr, - png_const_infop info_ptr, int *file_srgb_intent)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(156, void, png_set_sRGB, - (png_structp png_ptr, png_infop info_ptr, int srgb_intent)); -PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_structp png_ptr, - png_infop info_ptr, int srgb_intent)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(158, png_uint_32, png_get_iCCP, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_charpp name, int *compression_type, png_bytepp profile, - png_uint_32 *proflen)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(159, void, png_set_iCCP, - (png_structp png_ptr, png_infop info_ptr, - png_const_charp name, int compression_type, png_const_bytep profile, - png_uint_32 proflen)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(160, png_uint_32, png_get_sPLT, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_sPLT_tpp entries)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(161, void, png_set_sPLT, - (png_structp png_ptr, png_infop info_ptr, - png_const_sPLT_tp entries, int nentries)); -#endif - -#ifdef PNG_TEXT_SUPPORTED -/* png_get_text also returns the number of text chunks in *num_text */ -PNG_EXPORT(162, png_uint_32, png_get_text, - (png_const_structp png_ptr, png_const_infop info_ptr, - png_textp *text_ptr, int *num_text)); -#endif - -/* Note while png_set_text() will accept a structure whose text, - * language, and translated keywords are NULL pointers, the structure - * returned by png_get_text will always contain regular - * zero-terminated C strings. They might be empty strings but - * they will never be NULL pointers. - */ - -#ifdef PNG_TEXT_SUPPORTED -PNG_EXPORT(163, void, png_set_text, - (png_structp png_ptr, png_infop info_ptr, - png_const_textp text_ptr, int num_text)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(164, png_uint_32, png_get_tIME, - (png_const_structp png_ptr, png_infop info_ptr, png_timep *mod_time)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(165, void, png_set_tIME, - (png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(166, png_uint_32, png_get_tRNS, - (png_const_structp png_ptr, png_infop info_ptr, - png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(167, void, png_set_tRNS, - (png_structp png_ptr, png_infop info_ptr, - png_const_bytep trans_alpha, int num_trans, - png_const_color_16p trans_color)); -#endif - -#ifdef PNG_sCAL_SUPPORTED -PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL, - (png_const_structp png_ptr, png_const_infop info_ptr, - int *unit, double *width, double *height)); -#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED -/* NOTE: this API is currently implemented using floating point arithmetic, - * consequently it can only be used on systems with floating point support. - * In any case the range of values supported by png_fixed_point is small and it - * is highly recommended that png_get_sCAL_s be used instead. - */ -PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed, - (png_structp png_ptr, png_const_infop info_ptr, int *unit, - png_fixed_point *width, - png_fixed_point *height)); -#endif -PNG_EXPORT(169, png_uint_32, png_get_sCAL_s, - (png_const_structp png_ptr, png_const_infop info_ptr, - int *unit, png_charpp swidth, png_charpp sheight)); - -PNG_FP_EXPORT(170, void, png_set_sCAL, - (png_structp png_ptr, png_infop info_ptr, - int unit, double width, double height)); -PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_structp png_ptr, - png_infop info_ptr, int unit, png_fixed_point width, - png_fixed_point height)); -PNG_EXPORT(171, void, png_set_sCAL_s, - (png_structp png_ptr, png_infop info_ptr, - int unit, png_const_charp swidth, png_const_charp sheight)); -#endif /* PNG_sCAL_SUPPORTED */ - -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED -/* Provide a list of chunks and how they are to be handled, if the built-in - handling or default unknown chunk handling is not desired. Any chunks not - listed will be handled in the default manner. The IHDR and IEND chunks - must not be listed. - keep = 0: follow default behaviour - = 1: do not keep - = 2: keep only if safe-to-copy - = 3: keep even if unsafe-to-copy -*/ -PNG_EXPORT(172, void, png_set_keep_unknown_chunks, - (png_structp png_ptr, int keep, - png_const_bytep chunk_list, int num_chunks)); -PNG_EXPORT(173, int, png_handle_as_unknown, (png_structp png_ptr, - png_const_bytep chunk_name)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -PNG_EXPORT(174, void, png_set_unknown_chunks, (png_structp png_ptr, - png_infop info_ptr, png_const_unknown_chunkp unknowns, - int num_unknowns)); -PNG_EXPORT(175, void, png_set_unknown_chunk_location, - (png_structp png_ptr, png_infop info_ptr, int chunk, int location)); -PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structp png_ptr, - png_const_infop info_ptr, png_unknown_chunkpp entries)); -#endif - -/* Png_free_data() will turn off the "valid" flag for anything it frees. - * If you need to turn it off for a chunk that your application has freed, - * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); - */ -PNG_EXPORT(177, void, png_set_invalid, - (png_structp png_ptr, png_infop info_ptr, int mask)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* The "params" pointer is currently not used and is for future expansion. */ -PNG_EXPORT(178, void, png_read_png, (png_structp png_ptr, png_infop info_ptr, - int transforms, png_voidp params)); -PNG_EXPORT(179, void, png_write_png, (png_structp png_ptr, png_infop info_ptr, - int transforms, png_voidp params)); -#endif - -PNG_EXPORT(180, png_const_charp, png_get_copyright, - (png_const_structp png_ptr)); -PNG_EXPORT(181, png_const_charp, png_get_header_ver, - (png_const_structp png_ptr)); -PNG_EXPORT(182, png_const_charp, png_get_header_version, - (png_const_structp png_ptr)); -PNG_EXPORT(183, png_const_charp, png_get_libpng_ver, - (png_const_structp png_ptr)); - -#ifdef PNG_MNG_FEATURES_SUPPORTED -PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structp png_ptr, - png_uint_32 mng_features_permitted)); -#endif - -/* For use in png_set_keep_unknown, added to version 1.2.6 */ -#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 -#define PNG_HANDLE_CHUNK_NEVER 1 -#define PNG_HANDLE_CHUNK_IF_SAFE 2 -#define PNG_HANDLE_CHUNK_ALWAYS 3 - -/* Strip the prepended error numbers ("#nnn ") from error and warning - * messages before passing them to the error or warning handler. - */ -#ifdef PNG_ERROR_NUMBERS_SUPPORTED -PNG_EXPORT(185, void, png_set_strip_error_numbers, - (png_structp png_ptr, - png_uint_32 strip_mode)); -#endif - -/* Added in libpng-1.2.6 */ -#ifdef PNG_SET_USER_LIMITS_SUPPORTED -PNG_EXPORT(186, void, png_set_user_limits, (png_structp png_ptr, - png_uint_32 user_width_max, png_uint_32 user_height_max)); -PNG_EXPORT(187, png_uint_32, png_get_user_width_max, - (png_const_structp png_ptr)); -PNG_EXPORT(188, png_uint_32, png_get_user_height_max, - (png_const_structp png_ptr)); -/* Added in libpng-1.4.0 */ -PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structp png_ptr, - png_uint_32 user_chunk_cache_max)); -PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max, - (png_const_structp png_ptr)); -/* Added in libpng-1.4.1 */ -PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structp png_ptr, - png_alloc_size_t user_chunk_cache_max)); -PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max, - (png_const_structp png_ptr)); -#endif - -#if defined(PNG_INCH_CONVERSIONS_SUPPORTED) -PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch, - (png_const_structp png_ptr, png_const_infop info_ptr)); - -PNG_FP_EXPORT(196, float, png_get_x_offset_inches, - (png_const_structp png_ptr, png_const_infop info_ptr)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed, - (png_structp png_ptr, png_const_infop info_ptr)); -#endif - -PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structp png_ptr, - png_const_infop info_ptr)); -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed, - (png_structp png_ptr, png_const_infop info_ptr)); -#endif - -# ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structp png_ptr, - png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -# endif /* PNG_pHYs_SUPPORTED */ -#endif /* PNG_INCH_CONVERSIONS_SUPPORTED */ - -/* Added in libpng-1.4.0 */ -#ifdef PNG_IO_STATE_SUPPORTED -PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_structp png_ptr)); - -PNG_EXPORTA(200, png_const_bytep, png_get_io_chunk_name, - (png_structp png_ptr), PNG_DEPRECATED); -PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type, - (png_const_structp png_ptr)); - -/* The flags returned by png_get_io_state() are the following: */ -# define PNG_IO_NONE 0x0000 /* no I/O at this moment */ -# define PNG_IO_READING 0x0001 /* currently reading */ -# define PNG_IO_WRITING 0x0002 /* currently writing */ -# define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */ -# define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */ -# define PNG_IO_CHUNK_DATA 0x0040 /* currently at the chunk data */ -# define PNG_IO_CHUNK_CRC 0x0080 /* currently at the chunk crc */ -# define PNG_IO_MASK_OP 0x000f /* current operation: reading/writing */ -# define PNG_IO_MASK_LOC 0x00f0 /* current location: sig/hdr/data/crc */ -#endif /* ?PNG_IO_STATE_SUPPORTED */ - -/* Interlace support. The following macros are always defined so that if - * libpng interlace handling is turned off the macros may be used to handle - * interlaced images within the application. - */ -#define PNG_INTERLACE_ADAM7_PASSES 7 - -/* Two macros to return the first row and first column of the original, - * full, image which appears in a given pass. 'pass' is in the range 0 - * to 6 and the result is in the range 0 to 7. - */ -#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7) -#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7) - -/* Two macros to help evaluate the number of rows or columns in each - * pass. This is expressed as a shift - effectively log2 of the number or - * rows or columns in each 8x8 tile of the original image. - */ -#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) -#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) - -/* Hence two macros to determine the number of rows or columns in a given - * pass of an image given its height or width. In fact these macros may - * return non-zero even though the sub-image is empty, because the other - * dimension may be empty for a small image. - */ -#define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) -#define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) - -/* For the reader row callbacks (both progressive and sequential) it is - * necessary to find the row in the output image given a row in an interlaced - * image, so two more macros: - */ -#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \ - (((yIn)<>(((7-(off))-(pass))<<2)) & 0xFU) | \ - ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U)) - -#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ - ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) -#define PNG_COL_IN_INTERLACE_PASS(x, pass) \ - ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) - -#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED -/* With these routines we avoid an integer divide, which will be slower on - * most machines. However, it does take more operations than the corresponding - * divide method, so it may be slower on a few RISC systems. There are two - * shifts (by 8 or 16 bits) and an addition, versus a single integer divide. - * - * Note that the rounding factors are NOT supposed to be the same! 128 and - * 32768 are correct for the NODIV code; 127 and 32767 are correct for the - * standard method. - * - * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ] - */ - - /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */ - -# define png_composite(composite, fg, alpha, bg) \ - { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \ - * (png_uint_16)(alpha) \ - + (png_uint_16)(bg)*(png_uint_16)(255 \ - - (png_uint_16)(alpha)) + (png_uint_16)128); \ - (composite) = (png_byte)((temp + (temp >> 8)) >> 8); } - -# define png_composite_16(composite, fg, alpha, bg) \ - { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) \ - * (png_uint_32)(alpha) \ - + (png_uint_32)(bg)*(png_uint_32)(65535L \ - - (png_uint_32)(alpha)) + (png_uint_32)32768L); \ - (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); } - -#else /* Standard method using integer division */ - -# define png_composite(composite, fg, alpha, bg) \ - (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \ - (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \ - (png_uint_16)127) / 255) - -# define png_composite_16(composite, fg, alpha, bg) \ - (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \ - (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \ - (png_uint_32)32767) / (png_uint_32)65535L) -#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */ - -#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf)); -PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf)); -PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf)); -#endif - -PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_structp png_ptr, - png_const_bytep buf)); -/* No png_get_int_16 -- may be added if there's a real need for it. */ - -/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i)); -#endif -#ifdef PNG_SAVE_INT_32_SUPPORTED -PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i)); -#endif - -/* Place a 16-bit number into a buffer in PNG byte order. - * The parameter is declared unsigned int, not png_uint_16, - * just to avoid potential problems on pre-ANSI C compilers. - */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i)); -/* No png_save_int_16 -- may be added if there's a real need for it. */ -#endif - -#ifdef PNG_USE_READ_MACROS -/* Inline macros to do direct reads of bytes from the input buffer. - * The png_get_int_32() routine assumes we are using two's complement - * format for negative values, which is almost certainly true. - */ -# define png_get_uint_32(buf) \ - (((png_uint_32)(*(buf)) << 24) + \ - ((png_uint_32)(*((buf) + 1)) << 16) + \ - ((png_uint_32)(*((buf) + 2)) << 8) + \ - ((png_uint_32)(*((buf) + 3)))) - - /* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the - * function) incorrectly returned a value of type png_uint_32. - */ -# define png_get_uint_16(buf) \ - ((png_uint_16) \ - (((unsigned int)(*(buf)) << 8) + \ - ((unsigned int)(*((buf) + 1))))) - -# define png_get_int_32(buf) \ - ((png_int_32)((*(buf) & 0x80) \ - ? -((png_int_32)((png_get_uint_32(buf) ^ 0xffffffffL) + 1)) \ - : (png_int_32)png_get_uint_32(buf))) -#endif - -/* Maintainer: Put new public prototypes here ^, in libpng.3, and project - * defs - */ - -/* The last ordinal number (this is the *last* one already used; the next - * one to use is one more than this.) Maintainer, remember to add an entry to - * scripts/symbols.def as well. - */ -#ifdef PNG_EXPORT_LAST_ORDINAL - PNG_EXPORT_LAST_ORDINAL(221); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* PNG_VERSION_INFO_ONLY */ -/* Do not put anything past this line */ -#endif /* PNG_H */ diff --git a/cdeps/win64/pngconf.h b/cdeps/win64/pngconf.h deleted file mode 100755 index 084de8ef..00000000 --- a/cdeps/win64/pngconf.h +++ /dev/null @@ -1,649 +0,0 @@ - -/* pngconf.h - machine configurable file for libpng - * - * libpng version 1.5.2 - March 31, 2011 - * - * Copyright (c) 1998-2011 Glenn Randers-Pehrson - * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) - * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) - * - * This code is released under the libpng license. - * For conditions of distribution and use, see the disclaimer - * and license in png.h - * - */ - -/* Any machine specific code is near the front of this file, so if you - * are configuring libpng for a machine, you may want to read the section - * starting here down to where it starts to typedef png_color, png_text, - * and png_info. - */ - -#ifndef PNGCONF_H -#define PNGCONF_H - -#ifndef PNG_BUILDING_SYMBOL_TABLE -/* PNG_NO_LIMITS_H may be used to turn off the use of the standard C - * definition file for machine specific limits, this may impact the - * correctness of the definitons below (see uses of INT_MAX). - */ -# ifndef PNG_NO_LIMITS_H -# include -# endif - -/* For the memory copy APIs (i.e. the standard definitions of these), - * because this file defines png_memcpy and so on the base APIs must - * be defined here. - */ -# ifdef BSD -# include -# else -# include -# endif - -/* For png_FILE_p - this provides the standard definition of a - * FILE - */ -# ifdef PNG_STDIO_SUPPORTED -# include -# endif -#endif - -/* This controls optimization of the reading of 16 and 32 bit values - * from PNG files. It can be set on a per-app-file basis - it - * just changes whether a macro is used to the function is called. - * The library builder sets the default, if read functions are not - * built into the library the macro implementation is forced on. - */ -#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED -# define PNG_USE_READ_MACROS -#endif -#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS) -# if PNG_DEFAULT_READ_MACROS -# define PNG_USE_READ_MACROS -# endif -#endif - -/* COMPILER SPECIFIC OPTIONS. - * - * These options are provided so that a variety of difficult compilers - * can be used. Some are fixed at build time (e.g. PNG_API_RULE - * below) but still have compiler specific implementations, others - * may be changed on a per-file basis when compiling against libpng. - */ - -/* The PNGARG macro protects us against machines that don't have function - * prototypes (ie K&R style headers). If your compiler does not handle - * function prototypes, define this macro and use the included ansi2knr. - * I've always been able to use _NO_PROTO as the indicator, but you may - * need to drag the empty declaration out in front of here, or change the - * ifdef to suit your own needs. - */ -#ifndef PNGARG - -# ifdef OF /* zlib prototype munger */ -# define PNGARG(arglist) OF(arglist) -# else - -# ifdef _NO_PROTO -# define PNGARG(arglist) () -# else -# define PNGARG(arglist) arglist -# endif /* _NO_PROTO */ - -# endif /* OF */ - -#endif /* PNGARG */ - -/* Function calling conventions. - * ============================= - * Normally it is not necessary to specify to the compiler how to call - * a function - it just does it - however on x86 systems derived from - * Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems - * and some others) there are multiple ways to call a function and the - * default can be changed on the compiler command line. For this reason - * libpng specifies the calling convention of every exported function and - * every function called via a user supplied function pointer. This is - * done in this file by defining the following macros: - * - * PNGAPI Calling convention for exported functions. - * PNGCBAPI Calling convention for user provided (callback) functions. - * PNGCAPI Calling convention used by the ANSI-C library (required - * for longjmp callbacks and sometimes used internally to - * specify the calling convention for zlib). - * - * These macros should never be overridden. If it is necessary to - * change calling convention in a private build this can be done - * by setting PNG_API_RULE (which defaults to 0) to one of the values - * below to select the correct 'API' variants. - * - * PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout. - * This is correct in every known environment. - * PNG_API_RULE=1 Use the operating system convention for PNGAPI and - * the 'C' calling convention (from PNGCAPI) for - * callbacks (PNGCBAPI). This is no longer required - * in any known environment - if it has to be used - * please post an explanation of the problem to the - * libpng mailing list. - * - * These cases only differ if the operating system does not use the C - * calling convention, at present this just means the above cases - * (x86 DOS/Windows sytems) and, even then, this does not apply to - * Cygwin running on those systems. - * - * Note that the value must be defined in pnglibconf.h so that what - * the application uses to call the library matches the conventions - * set when building the library. - */ - -/* Symbol export - * ============= - * When building a shared library it is almost always necessary to tell - * the compiler which symbols to export. The png.h macro 'PNG_EXPORT' - * is used to mark the symbols. On some systems these symbols can be - * extracted at link time and need no special processing by the compiler, - * on other systems the symbols are flagged by the compiler and just - * the declaration requires a special tag applied (unfortunately) in a - * compiler dependent way. Some systems can do either. - * - * A small number of older systems also require a symbol from a DLL to - * be flagged to the program that calls it. This is a problem because - * we do not know in the header file included by application code that - * the symbol will come from a shared library, as opposed to a statically - * linked one. For this reason the application must tell us by setting - * the magic flag PNG_USE_DLL to turn on the special processing before - * it includes png.h. - * - * Four additional macros are used to make this happen: - * - * PNG_IMPEXP The magic (if any) to cause a symbol to be exported from - * the build or imported if PNG_USE_DLL is set - compiler - * and system specific. - * - * PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to - * 'type', compiler specific. - * - * PNG_DLL_EXPORT Set to the magic to use during a libpng build to - * make a symbol exported from the DLL. - * - * PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come - * from a DLL - used to define PNG_IMPEXP when - * PNG_USE_DLL is set. - */ - -/* System specific discovery. - * ========================== - * This code is used at build time to find PNG_IMPEXP, the API settings - * and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL - * import processing is possible. On Windows/x86 systems it also sets - * compiler-specific macros to the values required to change the calling - * conventions of the various functions. - */ -#if ( defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\ - defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) ) &&\ - ( defined(_X86_) || defined(_X64_) || defined(_M_IX86) ||\ - defined(_M_X64) || defined(_M_IA64) ) - /* Windows system (DOS doesn't support DLLs) running on x86/x64. Includes - * builds under Cygwin or MinGW. Also includes Watcom builds but these need - * special treatment because they are not compatible with GCC or Visual C - * because of different calling conventions. - */ -# if PNG_API_RULE == 2 - /* If this line results in an error, either because __watcall is not - * understood or because of a redefine just below you cannot use *this* - * build of the library with the compiler you are using. *This* build was - * build using Watcom and applications must also be built using Watcom! - */ -# define PNGCAPI __watcall -# endif - -# if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800)) -# define PNGCAPI __cdecl -# if PNG_API_RULE == 1 -# define PNGAPI __stdcall -# endif -# else - /* An older compiler, or one not detected (erroneously) above, - * if necessary override on the command line to get the correct - * variants for the compiler. - */ -# ifndef PNGCAPI -# define PNGCAPI _cdecl -# endif -# if PNG_API_RULE == 1 && !defined(PNGAPI) -# define PNGAPI _stdcall -# endif -# endif /* compiler/api */ - /* NOTE: PNGCBAPI always defaults to PNGCAPI. */ - -# if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD) - ERROR: PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed -# endif - -# if (defined(_MSC_VER) && _MSC_VER < 800) ||\ - (defined(__BORLANDC__) && __BORLANDC__ < 0x500) - /* older Borland and MSC - * compilers used '__export' and required this to be after - * the type. - */ -# ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) type PNG_IMPEXP -# endif -# define PNG_DLL_EXPORT __export -# else /* newer compiler */ -# define PNG_DLL_EXPORT __declspec(dllexport) -# ifndef PNG_DLL_IMPORT -# define PNG_DLL_IMPORT __declspec(dllimport) -# endif -# endif /* compiler */ - -#else /* !Windows/x86 */ -# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__) -# define PNGAPI _System -# else /* !Windows/x86 && !OS/2 */ - /* Use the defaults, or define PNG*API on the command line (but - * this will have to be done for every compile!) - */ -# endif /* other system, !OS/2 */ -#endif /* !Windows/x86 */ - -/* Now do all the defaulting . */ -#ifndef PNGCAPI -# define PNGCAPI -#endif -#ifndef PNGCBAPI -# define PNGCBAPI PNGCAPI -#endif -#ifndef PNGAPI -# define PNGAPI PNGCAPI -#endif - -/* The default for PNG_IMPEXP depends on whether the library is - * being built or used. - */ -#ifndef PNG_IMPEXP -# ifdef PNGLIB_BUILD - /* Building the library */ -# if (defined(DLL_EXPORT)/*from libtool*/ ||\ - defined(_WINDLL) || defined(_DLL) || defined(__DLL__) ||\ - defined(_USRDLL) ||\ - defined(PNG_BUILD_DLL)) && defined(PNG_DLL_EXPORT) - /* Building a DLL. */ -# define PNG_IMPEXP PNG_DLL_EXPORT -# endif /* DLL */ -# else - /* Using the library */ -# if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT) - /* This forces use of a DLL, disallowing static linking */ -# define PNG_IMPEXP PNG_DLL_IMPORT -# endif -# endif - -# ifndef PNG_IMPEXP -# define PNG_IMPEXP -# endif -#endif - -/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat - * 'attributes' as a storage class - the attributes go at the start of the - * function definition, and attributes are always appended regardless of the - * compiler. This considerably simplifies these macros but may cause problems - * if any compilers both need function attributes and fail to handle them as - * a storage class (this is unlikely.) - */ -#ifndef PNG_FUNCTION -# define PNG_FUNCTION(type, name, args, attributes) attributes type name args -#endif - -#ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) PNG_IMPEXP type -#endif - - /* The ordinal value is only relevant when preprocessing png.h for symbol - * table entries, so we discard it here. See the .dfn files in the - * scripts directory. - */ -#ifndef PNG_EXPORTA - -# define PNG_EXPORTA(ordinal, type, name, args, attributes)\ - PNG_FUNCTION(PNG_EXPORT_TYPE(type),(PNGAPI name),PNGARG(args), \ - extern attributes) -#endif - -/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument, - * so make something non-empty to satisfy the requirement: - */ -#define PNG_EMPTY /*empty list*/ - -#define PNG_EXPORT(ordinal, type, name, args)\ - PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY) - -/* Use PNG_REMOVED to comment out a removed interface. */ -#ifndef PNG_REMOVED -# define PNG_REMOVED(ordinal, type, name, args, attributes) -#endif - -#ifndef PNG_CALLBACK -# define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args) -#endif - -/* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. - * - * Added at libpng-1.2.41. - */ - -#ifndef PNG_NO_PEDANTIC_WARNINGS -# ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED -# define PNG_PEDANTIC_WARNINGS_SUPPORTED -# endif -#endif - -#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED - /* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. Added at libpng - * version 1.2.41. - */ -# if defined(__GNUC__) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# ifndef PNG_PTR_NORETURN - /* It's not enough to have the compiler be the correct compiler at - * this point - it's necessary for the library (which defines - * the type of the library longjmp) to also be the GNU library. - * This is because many systems use the GNU compiler with a - * non-GNU libc implementation. Min/GW headers are also compatible - * with GCC as well as uclibc, so it seems best to exclude known - * problem libcs here rather than just including known libcs. - * - * NOTE: this relies on the only use of PNG_PTR_NORETURN being with - * the system longjmp. If the same type is used elsewhere then this - * will need to be changed. - */ -# if !defined(__CYGWIN__) -# define PNG_PTR_NORETURN __attribute__((__noreturn__)) -# endif -# endif -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif - - /* This specifically protects structure members that should only be - * accessed from within the library, therefore should be empty during - * a library build. - */ -# ifndef PNGLIB_BUILD -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT __attribute__((__deprecated__)) -# endif -# ifndef PNG_PRIVATE -# if 0 /* Doesn't work so we use deprecated instead*/ -# define PNG_PRIVATE \ - __attribute__((warning("This function is not exported by libpng."))) -# else -# define PNG_PRIVATE \ - __attribute__((__deprecated__)) -# endif -# endif -# endif /* PNGLIB_BUILD */ -# endif /* __GNUC__ */ - -# if defined(_MSC_VER) && (_MSC_VER >= 1300) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* not supported */ -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __declspec(noreturn) -# endif -# ifndef PNG_PTR_NORETURN -# define PNG_PTR_NORETURN /* not supported */ -# endif -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __declspec(restrict) -# endif - - /* This specifically protects structure members that should only be - * accessed from within the library, therefore should be empty during - * a library build. - */ -# ifndef PNGLIB_BUILD -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __declspec(deprecated) -# endif -# ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT __declspec(deprecated) -# endif -# ifndef PNG_PRIVATE -# define PNG_PRIVATE __declspec(deprecated) -# endif -# endif /* PNGLIB_BUILD */ -# endif /* _MSC_VER */ -#endif /* PNG_PEDANTIC_WARNINGS */ - -#ifndef PNG_DEPRECATED -# define PNG_DEPRECATED /* Use of this function is deprecated */ -#endif -#ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* The result of this function must be checked */ -#endif -#ifndef PNG_NORETURN -# define PNG_NORETURN /* This function does not return */ -#endif -#ifndef PNG_PTR_NORETURN -# define PNG_PTR_NORETURN /* This function does not return */ -#endif -#ifndef PNG_ALLOCATED -# define PNG_ALLOCATED /* The result of the function is new memory */ -#endif -#ifndef PNG_DEPSTRUCT -# define PNG_DEPSTRUCT /* Access to this struct member is deprecated */ -#endif -#ifndef PNG_PRIVATE -# define PNG_PRIVATE /* This is a private libpng function */ -#endif -#ifndef PNG_FP_EXPORT /* A floating point API. */ -# ifdef PNG_FLOATING_POINT_SUPPORTED -# define PNG_FP_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args) -# else /* No floating point APIs */ -# define PNG_FP_EXPORT(ordinal, type, name, args) -# endif -#endif -#ifndef PNG_FIXED_EXPORT /* A fixed point API. */ -# ifdef PNG_FIXED_POINT_SUPPORTED -# define PNG_FIXED_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args) -# else /* No fixed point APIs */ -# define PNG_FIXED_EXPORT(ordinal, type, name, args) -# endif -#endif - -/* The following uses const char * instead of char * for error - * and warning message functions, so some compilers won't complain. - * If you do not want to use const, define PNG_NO_CONST here. - * - * This should not change how the APIs are called, so it can be done - * on a per-file basis in the application. - */ -#ifndef PNG_CONST -# ifndef PNG_NO_CONST -# define PNG_CONST const -# else -# define PNG_CONST -# endif -#endif - -/* Some typedefs to get us started. These should be safe on most of the - * common platforms. The typedefs should be at least as large as the - * numbers suggest (a png_uint_32 must be at least 32 bits long), but they - * don't have to be exactly that size. Some compilers dislike passing - * unsigned shorts as function parameters, so you may be better off using - * unsigned int for png_uint_16. - */ - -#if defined(INT_MAX) && (INT_MAX > 0x7ffffffeL) -typedef unsigned int png_uint_32; -typedef int png_int_32; -#else -typedef unsigned long png_uint_32; -typedef long png_int_32; -#endif -typedef unsigned short png_uint_16; -typedef short png_int_16; -typedef unsigned char png_byte; - -#ifdef PNG_NO_SIZE_T -typedef unsigned int png_size_t; -#else -typedef size_t png_size_t; -#endif -#define png_sizeof(x) (sizeof (x)) - -/* The following is needed for medium model support. It cannot be in the - * pngpriv.h header. Needs modification for other compilers besides - * MSC. Model independent support declares all arrays and pointers to be - * large using the far keyword. The zlib version used must also support - * model independent data. As of version zlib 1.0.4, the necessary changes - * have been made in zlib. The USE_FAR_KEYWORD define triggers other - * changes that are needed. (Tim Wegner) - */ - -/* Separate compiler dependencies (problem here is that zlib.h always - * defines FAR. (SJT) - */ -#ifdef __BORLANDC__ -# if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__) -# define LDATA 1 -# else -# define LDATA 0 -# endif - /* GRR: why is Cygwin in here? Cygwin is not Borland C... */ -# if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__) -# define PNG_MAX_MALLOC_64K /* only used in build */ -# if (LDATA != 1) -# ifndef FAR -# define FAR __far -# endif -# define USE_FAR_KEYWORD -# endif /* LDATA != 1 */ - /* Possibly useful for moving data out of default segment. - * Uncomment it if you want. Could also define FARDATA as - * const if your compiler supports it. (SJT) -# define FARDATA FAR - */ -# endif /* __WIN32__, __FLAT__, __CYGWIN__ */ -#endif /* __BORLANDC__ */ - - -/* Suggest testing for specific compiler first before testing for - * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM, - * making reliance oncertain keywords suspect. (SJT) - */ - -/* MSC Medium model */ -#ifdef FAR -# ifdef M_I86MM -# define USE_FAR_KEYWORD -# define FARDATA FAR -# include -# endif -#endif - -/* SJT: default case */ -#ifndef FAR -# define FAR -#endif - -/* At this point FAR is always defined */ -#ifndef FARDATA -# define FARDATA -#endif - -/* Typedef for floating-point numbers that are converted - * to fixed-point with a multiple of 100,000, e.g., gamma - */ -typedef png_int_32 png_fixed_point; - -/* Add typedefs for pointers */ -typedef void FAR * png_voidp; -typedef PNG_CONST void FAR * png_const_voidp; -typedef png_byte FAR * png_bytep; -typedef PNG_CONST png_byte FAR * png_const_bytep; -typedef png_uint_32 FAR * png_uint_32p; -typedef PNG_CONST png_uint_32 FAR * png_const_uint_32p; -typedef png_int_32 FAR * png_int_32p; -typedef PNG_CONST png_int_32 FAR * png_const_int_32p; -typedef png_uint_16 FAR * png_uint_16p; -typedef PNG_CONST png_uint_16 FAR * png_const_uint_16p; -typedef png_int_16 FAR * png_int_16p; -typedef PNG_CONST png_int_16 FAR * png_const_int_16p; -typedef char FAR * png_charp; -typedef PNG_CONST char FAR * png_const_charp; -typedef png_fixed_point FAR * png_fixed_point_p; -typedef PNG_CONST png_fixed_point FAR * png_const_fixed_point_p; -typedef png_size_t FAR * png_size_tp; -typedef PNG_CONST png_size_t FAR * png_const_size_tp; - -#ifdef PNG_STDIO_SUPPORTED -typedef FILE * png_FILE_p; -#endif - -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double FAR * png_doublep; -typedef PNG_CONST double FAR * png_const_doublep; -#endif - -/* Pointers to pointers; i.e. arrays */ -typedef png_byte FAR * FAR * png_bytepp; -typedef png_uint_32 FAR * FAR * png_uint_32pp; -typedef png_int_32 FAR * FAR * png_int_32pp; -typedef png_uint_16 FAR * FAR * png_uint_16pp; -typedef png_int_16 FAR * FAR * png_int_16pp; -typedef PNG_CONST char FAR * FAR * png_const_charpp; -typedef char FAR * FAR * png_charpp; -typedef png_fixed_point FAR * FAR * png_fixed_point_pp; -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double FAR * FAR * png_doublepp; -#endif - -/* Pointers to pointers to pointers; i.e., pointer to array */ -typedef char FAR * FAR * FAR * png_charppp; - -/* png_alloc_size_t is guaranteed to be no smaller than png_size_t, - * and no smaller than png_uint_32. Casts from png_size_t or png_uint_32 - * to png_alloc_size_t are not necessary; in fact, it is recommended - * not to use them at all so that the compiler can complain when something - * turns out to be problematic. - * Casts in the other direction (from png_alloc_size_t to png_size_t or - * png_uint_32) should be explicitly applied; however, we do not expect - * to encounter practical situations that require such conversions. - */ -#if defined(__TURBOC__) && !defined(__FLAT__) - typedef unsigned long png_alloc_size_t; -#else -# if defined(_MSC_VER) && defined(MAXSEG_64K) - typedef unsigned long png_alloc_size_t; -# else - /* This is an attempt to detect an old Windows system where (int) is - * actually 16 bits, in that case png_malloc must have an argument with a - * bigger size to accomodate the requirements of the library. - */ -# if (defined(_Windows) || defined(_WINDOWS) || defined(_WINDOWS_)) && \ - (!defined(INT_MAX) || INT_MAX <= 0x7ffffffeL) - typedef DWORD png_alloc_size_t; -# else - typedef png_size_t png_alloc_size_t; -# endif -# endif -#endif - -#endif /* PNGCONF_H */ diff --git a/cdeps/win64/pnglibconf.h b/cdeps/win64/pnglibconf.h deleted file mode 100755 index e36ee348..00000000 --- a/cdeps/win64/pnglibconf.h +++ /dev/null @@ -1,181 +0,0 @@ - -/* libpng STANDARD API DEFINITION */ - -/* pnglibconf.h - library build configuration */ - -/* libpng version 1.5.0 - last changed on February 11, 2011 */ - -/* Copyright (c) 1998-2011 Glenn Randers-Pehrson */ - -/* This code is released under the libpng license. */ -/* For conditions of distribution and use, see the disclaimer */ -/* and license in png.h */ - -/* pnglibconf.h */ -/* Derived from: scripts/pnglibconf.dfa */ -/* If you edit this file by hand you must obey the rules expressed in */ -/* pnglibconf.dfa with respect to the dependencies between the following */ -/* symbols. It is much better to generate a new file using */ -/* scripts/libpngconf.mak */ - -#ifndef PNGLCONF_H -#define PNGLCONF_H -/* settings */ -#define PNG_API_RULE 0 -#define PNG_CALLOC_SUPPORTED -#define PNG_COST_SHIFT 3 -#define PNG_DEFAULT_READ_MACROS 1 -#define PNG_GAMMA_THRESHOLD_FIXED 5000 -#define PNG_MAX_GAMMA_8 11 -#define PNG_QUANTIZE_BLUE_BITS 5 -#define PNG_QUANTIZE_GREEN_BITS 5 -#define PNG_QUANTIZE_RED_BITS 5 -#define PNG_sCAL_PRECISION 5 -#define PNG_USER_CHUNK_CACHE_MAX 0 -#define PNG_USER_CHUNK_MALLOC_MAX 0 -#define PNG_USER_HEIGHT_MAX 1000000L -#define PNG_USER_WIDTH_MAX 1000000L -#define PNG_WEIGHT_SHIFT 8 -#define PNG_ZBUF_SIZE 8192 -/* end of settings */ -/* options */ -#define PNG_16BIT_SUPPORTED -#define PNG_ALIGN_MEMORY_SUPPORTED -#define PNG_BENIGN_ERRORS_SUPPORTED -#define PNG_bKGD_SUPPORTED -#define PNG_CHECK_cHRM_SUPPORTED -#define PNG_cHRM_SUPPORTED -#define PNG_CONSOLE_IO_SUPPORTED -#define PNG_CONVERT_tIME_SUPPORTED -#define PNG_EASY_ACCESS_SUPPORTED -#define PNG_ERROR_TEXT_SUPPORTED -#define PNG_FIXED_POINT_SUPPORTED -#define PNG_FLOATING_ARITHMETIC_SUPPORTED -#define PNG_FLOATING_POINT_SUPPORTED -#define PNG_gAMA_SUPPORTED -#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED -#define PNG_hIST_SUPPORTED -#define PNG_iCCP_SUPPORTED -#define PNG_INCH_CONVERSIONS_SUPPORTED -#define PNG_INFO_IMAGE_SUPPORTED -#define PNG_IO_STATE_SUPPORTED -#define PNG_iTXt_SUPPORTED -#define PNG_MNG_FEATURES_SUPPORTED -#define PNG_oFFs_SUPPORTED -#define PNG_pCAL_SUPPORTED -#define PNG_pHYs_SUPPORTED -#define PNG_POINTER_INDEXING_SUPPORTED -#define PNG_PROGRESSIVE_READ_SUPPORTED -#define PNG_READ_16BIT_SUPPORTED -#define PNG_READ_16_TO_8_SUPPORTED -#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_READ_BACKGROUND_SUPPORTED -#define PNG_READ_BGR_SUPPORTED -#define PNG_READ_bKGD_SUPPORTED -#define PNG_READ_cHRM_SUPPORTED -#define PNG_READ_COMPOSITE_NODIV_SUPPORTED -#define PNG_READ_EXPAND_16_SUPPORTED -#define PNG_READ_EXPAND_SUPPORTED -#define PNG_READ_FILLER_SUPPORTED -#define PNG_READ_gAMA_SUPPORTED -#define PNG_READ_GAMMA_SUPPORTED -#define PNG_READ_GRAY_TO_RGB_SUPPORTED -#define PNG_READ_hIST_SUPPORTED -#define PNG_READ_iCCP_SUPPORTED -#define PNG_READ_INTERLACING_SUPPORTED -#define PNG_READ_INT_FUNCTIONS_SUPPORTED -#define PNG_READ_INVERT_ALPHA_SUPPORTED -#define PNG_READ_INVERT_SUPPORTED -#define PNG_READ_iTXt_SUPPORTED -#define PNG_READ_oFFs_SUPPORTED -#define PNG_READ_OPT_PLTE_SUPPORTED -#define PNG_READ_PACK_SUPPORTED -#define PNG_READ_PACKSWAP_SUPPORTED -#define PNG_READ_pCAL_SUPPORTED -#define PNG_READ_pHYs_SUPPORTED -#define PNG_READ_QUANTIZE_SUPPORTED -#define PNG_READ_RGB_TO_GRAY_SUPPORTED -#define PNG_READ_sBIT_SUPPORTED -#define PNG_READ_sCAL_SUPPORTED -#define PNG_READ_SHIFT_SUPPORTED -#define PNG_READ_sPLT_SUPPORTED -#define PNG_READ_sRGB_SUPPORTED -#define PNG_READ_STRIP_ALPHA_SUPPORTED -#define PNG_READ_SUPPORTED -#define PNG_READ_SWAP_ALPHA_SUPPORTED -#define PNG_READ_SWAP_SUPPORTED -#define PNG_READ_tEXt_SUPPORTED -#define PNG_READ_TEXT_SUPPORTED -#define PNG_READ_tIME_SUPPORTED -#define PNG_READ_TRANSFORMS_SUPPORTED -#define PNG_READ_tRNS_SUPPORTED -#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_READ_USER_CHUNKS_SUPPORTED -#define PNG_READ_USER_TRANSFORM_SUPPORTED -#define PNG_READ_zTXt_SUPPORTED -#define PNG_SAVE_INT_32_SUPPORTED -#define PNG_sBIT_SUPPORTED -#define PNG_sCAL_SUPPORTED -#define PNG_SEQUENTIAL_READ_SUPPORTED -#define PNG_SET_CHUNK_CACHE_LIMIT_SUPPORTED -#define PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED -#define PNG_SETJMP_SUPPORTED -#define PNG_SET_USER_LIMITS_SUPPORTED -#define PNG_sPLT_SUPPORTED -#define PNG_sRGB_SUPPORTED -#define PNG_STDIO_SUPPORTED -#define PNG_tEXt_SUPPORTED -#define PNG_TEXT_SUPPORTED -#define PNG_TIME_RFC1123_SUPPORTED -#define PNG_tIME_SUPPORTED -#define PNG_tRNS_SUPPORTED -#define PNG_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_USER_CHUNKS_SUPPORTED -#define PNG_USER_LIMITS_SUPPORTED -#define PNG_USER_MEM_SUPPORTED -#define PNG_USER_TRANSFORM_INFO_SUPPORTED -#define PNG_USER_TRANSFORM_PTR_SUPPORTED -#define PNG_WARNINGS_SUPPORTED -#define PNG_WRITE_16BIT_SUPPORTED -#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_WRITE_BGR_SUPPORTED -#define PNG_WRITE_bKGD_SUPPORTED -#define PNG_WRITE_cHRM_SUPPORTED -#define PNG_WRITE_FILLER_SUPPORTED -#define PNG_WRITE_FILTER_SUPPORTED -#define PNG_WRITE_FLUSH_SUPPORTED -#define PNG_WRITE_gAMA_SUPPORTED -#define PNG_WRITE_hIST_SUPPORTED -#define PNG_WRITE_iCCP_SUPPORTED -#define PNG_WRITE_INTERLACING_SUPPORTED -#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED -#define PNG_WRITE_INVERT_ALPHA_SUPPORTED -#define PNG_WRITE_INVERT_SUPPORTED -#define PNG_WRITE_iTXt_SUPPORTED -#define PNG_WRITE_oFFs_SUPPORTED -#define PNG_WRITE_PACK_SUPPORTED -#define PNG_WRITE_PACKSWAP_SUPPORTED -#define PNG_WRITE_pCAL_SUPPORTED -#define PNG_WRITE_pHYs_SUPPORTED -#define PNG_WRITE_sBIT_SUPPORTED -#define PNG_WRITE_sCAL_SUPPORTED -#define PNG_WRITE_SHIFT_SUPPORTED -#define PNG_WRITE_sPLT_SUPPORTED -#define PNG_WRITE_sRGB_SUPPORTED -#define PNG_WRITE_SUPPORTED -#define PNG_WRITE_SWAP_ALPHA_SUPPORTED -#define PNG_WRITE_SWAP_SUPPORTED -#define PNG_WRITE_tEXt_SUPPORTED -#define PNG_WRITE_TEXT_SUPPORTED -#define PNG_WRITE_tIME_SUPPORTED -#define PNG_WRITE_TRANSFORMS_SUPPORTED -#define PNG_WRITE_tRNS_SUPPORTED -#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_WRITE_USER_TRANSFORM_SUPPORTED -#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED -#define PNG_WRITE_zTXt_SUPPORTED -#define PNG_zTXt_SUPPORTED -/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ -/*#undef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED*/ -/* end of options */ -#endif /* PNGLCONF_H */ diff --git a/cdeps/win64/zconf.h b/cdeps/win64/zconf.h deleted file mode 100755 index 02ce56c4..00000000 --- a/cdeps/win64/zconf.h +++ /dev/null @@ -1,428 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# define uncompress z_uncompress -# define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# define gzFile z_gzFile -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef STDC -# include /* for off_t */ -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -#endif - -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 -# define z_off64_t off64_t -#else -# define z_off64_t z_off_t -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/cdeps/win64/zlib.h b/cdeps/win64/zlib.h deleted file mode 100755 index bfbba83e..00000000 --- a/cdeps/win64/zlib.h +++ /dev/null @@ -1,1613 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.5, April 19th, 2010 - - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.5" -#define ZLIB_VERNUM 0x1250 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 5 -#define ZLIB_VER_SUBREVISION 0 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use in the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). Some - output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed code - block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the stream - are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect the - compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the - exact value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit() does not process any header information -- that is deferred - until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing will - resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained, so applications that need that information should - instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by the - caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as - fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The - strategy parameter only affects the compression ratio but not the - correctness of the compressed output even if it is not set appropriately. - Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler - decoder for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. The - stream will keep the same compression level and any other attributes that - may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression level is changed, the input available so far is - compressed with the old level (and may be flushed); the new level will take - effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to be - compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if - strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - int windowBits)); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above or -1 << 16 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When any - of extra, name, or comment are not Z_NULL and the respective field is not - present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the normal - behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) Upon exit, destLen - is the actual size of the uncompressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef voidp gzFile; /* opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - - Opens a gzip (.gz) file for reading or writing. The mode parameter is as - in fopen ("rb" or "wb") but can also include a compression level ("wb9") or - a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only - compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' - for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen associates a gzFile with the file descriptor fd. File descriptors - are obtained from calls like open, dup, creat, pipe or fileno (if the file - has been previously opened with fopen). The mode parameter is as in gzopen. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -/* - Set the internal buffer size used by this library's functions. The - default buffer size is 8192 bytes. This function must be called after - gzopen() or gzdopen(), and before any other calls that read or write the - file. The buffer memory allocation is always deferred to the first read or - write. Two buffers are allocated, either both of the specified size when - writing, or one of the specified size and the other twice that size when - reading. A larger buffer size of, for example, 64K or 128K bytes will - noticeably increase the speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. -*/ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes written or 0 in case of - error. -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the arguments to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or 0 in case of error. The number of - uncompressed bytes written is limited to 8191, or one less than the buffer - size given to gzbuffer(). The caller should assure that this limit is not - exceeded. If it is exceeded, then gzprintf() will return an error (0) with - nothing written. In this case, there may also be a buffer overflow with - unpredictable consequences, which is possible only if zlib was compiled with - the insecure functions sprintf() or vsprintf() because the secure snprintf() - or vsnprintf() functions were not available. This can be determined using - zlibCompileFlags(). -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or a - newline character is read and transferred to buf, or an end-of-file - condition is encountered. If any characters are read or if len == 1, the - string is terminated with a null character. If no characters are read due - to an end-of-file or len < 1, then the buffer is left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If there was an error, the contents at - buf are indeterminate. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read as the first character - on the next read. At least one character of push-back is allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter flush - is as in the deflate() function. The return value is the zlib error number - (see function gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatented gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); - - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - - Returns the starting position for the next gzread or gzwrite on the given - compressed file. This position represents a number of bytes in the - uncompressed data stream, and is zero when starting, even if appending or - reading a gzip stream from the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - - Returns the current offset in the file being read or written. This offset - includes the count of bytes that precede the gzip stream, for example when - appending or when using gzdopen() for reading. When reading, the offset - does not include as yet unused buffered input. This information can be used - for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns true (1) if the end-of-file indicator has been set while reading, - false (0) otherwise. Note that the end-of-file indicator is set only if the - read tried to go past the end of the input, but came up short. Therefore, - just like feof(), gzeof() may return false even if there is no more data to - read, in the event that the last read request was for the exact number of - bytes remaining in the input file. This will happen if the input file size - is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file and - deallocates the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); -ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the given - compressed file. errnum is set to zlib error number. If an error occurred - in the file system and not in the compression library, errnum is set to - Z_ERRNO and the application may consult errno to get the exact error code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is Z_NULL, this function returns the - required initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -#endif - -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifdef _LARGEFILE64_SOURCE - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -#endif - -/* hack for buggy compilers */ -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; -#endif - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); -ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/clipboard/clipboard.go b/clipboard/clipboard.go index f1b21861..e0017f96 100644 --- a/clipboard/clipboard.go +++ b/clipboard/clipboard.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. /* - Package clipboard read/write on clipboard */ package clipboard diff --git a/clipboard/clipboard_darwin.go b/clipboard/clipboard_darwin.go index 6f33078d..eedd4c3a 100644 --- a/clipboard/clipboard_darwin.go +++ b/clipboard/clipboard_darwin.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build darwin // +build darwin package clipboard @@ -48,5 +49,6 @@ func writeAll(text string) error { if err := in.Close(); err != nil { return err } + return copyCmd.Wait() } diff --git a/clipboard/clipboard_test.go b/clipboard/clipboard_test.go index 0da4ffcd..43f05ad9 100644 --- a/clipboard/clipboard_test.go +++ b/clipboard/clipboard_test.go @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build darwin || windows +// +build darwin windows + package clipboard_test import ( @@ -10,54 +13,54 @@ import ( "github.com/go-vgo/robotgo/clipboard" ) -// func TestCopyAndPaste(t *testing.T) { -// expected := "日本語" +func TestCopyAndPaste(t *testing.T) { + expected := "日本語" -// err := clipboard.WriteAll(expected) -// if err != nil { -// t.Fatal(err) -// } + err := clipboard.WriteAll(expected) + if err != nil { + t.Fatal(err) + } -// actual, err := clipboard.ReadAll() -// if err != nil { -// t.Fatal(err) -// } + actual, err := clipboard.ReadAll() + if err != nil { + t.Fatal(err) + } -// if actual != expected { -// t.Errorf("want %s, got %s", expected, actual) -// } -// } + if actual != expected { + t.Errorf("want %s, got %s", expected, actual) + } +} -// func TestMultiCopyAndPaste(t *testing.T) { -// expected1 := "French: éèêëàùœç" -// expected2 := "Weird UTF-8: 💩☃" +func TestMultiCopyAndPaste(t *testing.T) { + expected1 := "French: éèêëàùœç" + expected2 := "Weird UTF-8: 💩☃" -// err := clipboard.WriteAll(expected1) -// if err != nil { -// t.Fatal(err) -// } + err := clipboard.WriteAll(expected1) + if err != nil { + t.Fatal(err) + } -// actual1, err := clipboard.ReadAll() -// if err != nil { -// t.Fatal(err) -// } -// if actual1 != expected1 { -// t.Errorf("want %s, got %s", expected1, actual1) -// } + actual1, err := clipboard.ReadAll() + if err != nil { + t.Fatal(err) + } + if actual1 != expected1 { + t.Errorf("want %s, got %s", expected1, actual1) + } -// err = clipboard.WriteAll(expected2) -// if err != nil { -// t.Fatal(err) -// } + err = clipboard.WriteAll(expected2) + if err != nil { + t.Fatal(err) + } -// actual2, err := clipboard.ReadAll() -// if err != nil { -// t.Fatal(err) -// } -// if actual2 != expected2 { -// t.Errorf("want %s, got %s", expected2, actual2) -// } -// } + actual2, err := clipboard.ReadAll() + if err != nil { + t.Fatal(err) + } + if actual2 != expected2 { + t.Errorf("want %s, got %s", expected2, actual2) + } +} func BenchmarkReadAll(b *testing.B) { for i := 0; i < b.N; i++ { diff --git a/clipboard/clipboard_unix.go b/clipboard/clipboard_unix.go index 76d7611d..fde35cbd 100644 --- a/clipboard/clipboard_unix.go +++ b/clipboard/clipboard_unix.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build freebsd || linux || netbsd || openbsd || solaris || dragonfly // +build freebsd linux netbsd openbsd solaris dragonfly package clipboard @@ -67,11 +68,13 @@ func readAll() (string, error) { if Unsupported { return "", errMissingCommands } + pasteCmd := getPasteCommand() out, err := pasteCmd.Output() if err != nil { return "", err } + return string(out), nil } @@ -94,5 +97,6 @@ func writeAll(text string) error { if err := in.Close(); err != nil { return err } + return copyCmd.Wait() } diff --git a/clipboard/clipboard_windows.go b/clipboard/clipboard_windows.go index 7111e817..2b9202ed 100644 --- a/clipboard/clipboard_windows.go +++ b/clipboard/clipboard_windows.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build windows // +build windows package clipboard @@ -38,8 +39,10 @@ var ( func waitOpenClipboard() error { started := time.Now() limit := started.Add(time.Second) - var r uintptr - var err error + var ( + r uintptr + err error + ) for time.Now().Before(limit) { r, _, err = openClipboard.Call(0) if r != 0 { @@ -47,6 +50,7 @@ func waitOpenClipboard() error { } time.Sleep(time.Millisecond) } + return err } diff --git a/clipboard/cmd/gocopy/gocopy.go b/clipboard/cmd/gocopy/gocopy.go index 115672af..aaa9c30b 100644 --- a/clipboard/cmd/gocopy/gocopy.go +++ b/clipboard/cmd/gocopy/gocopy.go @@ -1,14 +1,14 @@ package main import ( - "io/ioutil" + "io" "os" "github.com/go-vgo/robotgo/clipboard" ) func main() { - out, err := ioutil.ReadAll(os.Stdin) + out, err := io.ReadAll(os.Stdin) if err != nil { panic(err) } diff --git a/clipboard/example/example.go b/clipboard/example/example.go index f29304e0..3b6cb377 100644 --- a/clipboard/example/example.go +++ b/clipboard/example/example.go @@ -7,14 +7,19 @@ import ( ) func main() { - clipboard.WriteAll("日本語") + err := clipboard.WriteAll("日本語") + if err != nil { + log.Println("clipboard write all error: ", err) + } + text, err := clipboard.ReadAll() if err != nil { log.Println("clipboard read all error: ", err) - } else { - if text != "" { - log.Println("text is: ", text) - // Output: 日本語 - } + return + } + + if text != "" { + log.Println("text is: ", text) + // Output: 日本語 } } diff --git a/doc.go b/doc.go new file mode 100644 index 00000000..e2b57bb7 --- /dev/null +++ b/doc.go @@ -0,0 +1,119 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package robotgo + +/* +Keys are supported: + "A-Z a-z 0-9" + + "backspace" + "delete" + "enter" + "tab" + "esc" + "escape" + "up" Up arrow key + "down" Down arrow key + "right" Right arrow key + "left" Left arrow key + "home" + "end" + "pageup" + "pagedown" + + "f1" + "f2" + "f3" + "f4" + "f5" + "f6" + "f7" + "f8" + "f9" + "f10" + "f11" + "f12" + "f13" + "f14" + "f15" + "f16" + "f17" + "f18" + "f19" + "f20" + "f21" + "f22" + "f23" + "f24" + + "cmd" this is the "win" key for windows + "lcmd" left command + "rcmd" right command + // "command" + "alt" + "lalt" left alt + "ralt" right alt + "ctrl" + "lctrl" left ctrl + "rctrl" right ctrl + "control" + "shift" + "lshift" left shift + "rshift" right shift + // "right_shift" + "capslock" + "space" + "print" + "printscreen" // No Mac support + "insert" + "menu" Windows only + + "audio_mute" Mute the volume + "audio_vol_down" Lower the volume + "audio_vol_up" Increase the volume + "audio_play" + "audio_stop" + "audio_pause" + "audio_prev" Previous Track + "audio_next" Next Track + "audio_rewind" Linux only + "audio_forward" Linux only + "audio_repeat" Linux only + "audio_random" Linux only + + + "num0" + "num1" + "num2" + "num3" + "num4" + "num5" + "num6" + "num7" + "num8" + "num9" + "num_lock" + + "num." + "num+" + "num-" + "num*" + "num/" + "num_clear" + "num_enter" + "num_equal" + + "lights_mon_up" Turn up monitor brightness No Windows support + "lights_mon_down" Turn down monitor brightness No Windows support + "lights_kbd_toggle" Toggle keyboard backlight on/off No Windows support + "lights_kbd_up" Turn up keyboard backlight brightness No Windows support + "lights_kbd_down" Turn down keyboard backlight brightness No Windows support +*/ diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d7f4d4c3..84d474b3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,6 +1,116 @@ # CHANGELOG +## RobotGo v0.100.0, MT. Baker; Enhancement bitmap and image, add arm support... + +### Add + +- [NEW] add more image function support +- [NEW] add ImgToBitmap(), ToImg(), FindEveryBitmap(), FindEveryColor(), Svae(), Read(), SaveJpeg() and other function support + +- [NEW] add func ToImage: convert C.MMBitmapRef to standard image.Image +- [NEW] add ToImage examples code +- [NEW] add more image function and update go mod + +- [NEW] add find every color function +- [NEW] add free and find all point function +- [NEW] update find bitmap and color + +- [NEW] add byte to image function +- [NEW] add more image convert function + +- [NEW] add mac os M1 support +- [NEW] add windows arm support + +- [NEW] add more key toggle and press function + +- [NEW] add ToRGBA() function support +- [NEW] add ImgToBitmap and RGBAToBitmap support +- [NEW] Update and move image function to img.go + +- [NEW] add more img to bitmap examples code and Update file name + +### Update + +- [NEW] Update README.md and CHANGELOG.md +- [NEW] add macOS to .travis.yml +- [NEW] update go mod pkg + +- [NEW] Update hook examples link to newest +- [NEW] update dockerfile and appveyor to go1.14.4 + +- [NEW] Update README.md, add more examples +- [NEW] move hook and event to gohook +- [NEW] move cbitmap and bitmap-bytes to bitmap dir + +- [NEW] update some name +- [NEW] update dockerfile and appveyor.yml + +- [NEW] update clipboard code +- [NEW] update hook code and more API + +- [NEW] optimize code and update version +- [NEW] add paste string err return and optimize code +- [NEW] update go.yml and travis.yml to go1.15 +- [NEW] Update Ubuntu apt-get to apt + +- [NEW] update go version and key code +- [NEW] update test code and go mod +- [NEW] Update README.md and test code + +- [NEW] update parameter name and version +- [NEW] update dockerfile and appveyor.yml +- [NEW] update error return and print + +- [NEW] update ShowAlert optimize return code +- [NEW] add more test and update go mod + +- [NEW] compatible with 32-bit platforms +- [NEW] add more bitmap examples + +- [NEW] update point structure to public + +- [NEW] add more examples +- [NEW] update examples and version +- [NEW] Update clipboard example code + +- [NEW] Update README.md Section ####Other to windows (#348) … +- [NEW] Update png.h path +- [NEW] Update go mod +- [NEW] Update circle.yml and travis.yml + +- [NEW] Remove unless example code and update circle.yml +- [NEW] Removed drop api example code and Update README.md + +- [NEW] Update go mod and xx.yml +- [NEW] Update README.md and example + +- [NEW] add more bitmap examples code +- [NEW] Update go mod and Update README.md +- [NEW] gofmt to 1.17 build tag +- [NEW] Update bitmap examples code + +- [NEW] Update version and keycode +- [NEW] Update docs remove drop API + + +### Fixed + +- [FIX] Update go mod and fixed #290 +- [FIX] Update gohook to v0.30.2 fixed bug +- [FIX] Fixed Mouse buttons reversed type +- [FIX] Fixed returns "Invalid key code specified." if specified character is not v… … add keyCodeForCharFallBack + +- [FIX] This fixes the disappearing backslash issue #351 +- [FIX] Export ToUC function and update test code +- [FIX] Fixes #258: char* arrays in C not being copied correctly +- [FIX] Fixed Linux TypeStr() function double quote + +- [FIX] update free bitmap fixed #333 +- [FIX] update gops to v0.20.0 fixed bug and other mod pkg +- [FIX] update gohook fixed warning + + ## RobotGo v0.90.0, MT. Rainier diff --git a/README_zh.md b/docs/archive/README_zh.md similarity index 57% rename from README_zh.md rename to docs/archive/README_zh.md index 91d7379f..7229ec38 100644 --- a/README_zh.md +++ b/docs/archive/README_zh.md @@ -1,5 +1,7 @@ # Robotgo +# !!! Warning: this page not updated !!! + [![Build Status](https://github.com/go-vgo/robotgo/workflows/Go/badge.svg)](https://github.com/go-vgo/robotgo/commits/master) [![CircleCI Status](https://circleci.com/gh/go-vgo/robotgo.svg?style=shield)](https://circleci.com/gh/go-vgo/robotgo) [![Build Status](https://travis-ci.org/go-vgo/robotgo.svg)](https://travis-ci.org/go-vgo/robotgo) @@ -9,15 +11,16 @@ [![GitHub release](https://img.shields.io/github/release/go-vgo/robotgo.svg)](https://github.com/go-vgo/robotgo/releases/latest) [![Join the chat at https://gitter.im/go-vgo/robotgo](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-vgo/robotgo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - >Golang 跨平台自动化系统,控制键盘鼠标位图和读取屏幕,窗口句柄以及全局事件监听 +> Golang 跨平台自动化系统,控制键盘、鼠标、位图、图像、读取屏幕,进程、窗口句柄以及全局事件监听 RobotGo 支持 Mac, Windows, and Linux(X11).
-提 Issues 请到 [Github](https://github.com/go-vgo/robotgo), 便于统一管理和即时更新 +提 Issues 请到 [Github](https://github.com/go-vgo/robotgo), 便于统一管理和即时更新; `REDAME_zh.md 已废弃, 不再更新` ## Contents + - [Docs](#docs) - [Binding](#binding) - [Requirements](#requirements) @@ -32,20 +35,24 @@ RobotGo 支持 Mac, Windows, and Linux(X11). - [License](#license) ## Docs -- [GoDoc](https://godoc.org/github.com/go-vgo/robotgo) -- [中文文档](https://github.com/go-vgo/robotgo/blob/master/docs/doc_zh.md)    -- [English Docs](https://github.com/go-vgo/robotgo/blob/master/docs/doc.md) + +- [GoDoc](https://godoc.org/github.com/go-vgo/robotgo)
+ + ## Binding: [Robotn](https://github.com/vcaesar/robotn), binding JavaScript and other, support more language. ## Requirements: + 环境要求: 在安装 RobotGo 之前, 请确保 `Golang、GCC` 被正确安装 ### ALL: + ``` Golang @@ -53,45 +60,55 @@ GCC ``` #### For Mac OS X: + +Xcode Command Line Tools (And Privacy setting: [#277](https://github.com/go-vgo/robotgo/issues/277) ) + ``` -Xcode Command Line Tools +xcode-select --install ``` #### For Windows: + +[MinGW-w64](https://sourceforge.net/projects/mingw-w64/files) (推荐使用) + ``` -MinGW-w64 (推荐使用) or other GCC +Or the other GCC (But you should compile the "libpng" with yourself. +Or you can removed the bitmap.go.) ``` #### For everything else (Linux 等其他系统): ``` -GCC, libpng +GCC, +libpng(bitmap) X11 with the XTest extension (also known as the Xtst library) 事件: xcb, xkb, libxkbcommon + +Clipboard: + +xsel xclip ``` ##### Ubuntu: ```yml -sudo apt-get install gcc libc6-dev - -sudo apt-get install libx11-dev xorg-dev libxtst-dev libpng++-dev +sudo apt install gcc libc6-dev -sudo apt-get install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev -sudo apt-get install libxkbcommon-dev +sudo apt install libx11-dev xorg-dev libxtst-dev libpng++-dev -sudo apt-get install xsel xclip +sudo apt install xcb libxcb-xkb-dev x11-xkb-utils libx11-xcb-dev libxkbcommon-x11-dev libxkbcommon-dev +sudo apt install xsel xclip ``` -#### Fedora: +##### Fedora: ```yml -sudo dnf install libxkbcommon-devel libXtst-devel libxkbcommon-x11-devel xorg-x11-xkb-utils-devel +sudo dnf install libXtst-devel libxkbcommon-devel libxkbcommon-x11-devel xorg-x11-xkb-utils-devel sudo dnf install libpng-devel @@ -99,14 +116,23 @@ sudo dnf install xsel xclip ``` ## Installation: + +With Go module support (Go 1.11+), just import: + +```go +import "github.com/go-vgo/robotgo" +``` + +Otherwise, to install the robotgo package, run the command: + ``` go get github.com/go-vgo/robotgo ``` - It's that easy! png.h: No such file or directory? Please see [issues/47](https://github.com/go-vgo/robotgo/issues/47). ## Update: + ``` go get -u github.com/go-vgo/robotgo ``` @@ -114,7 +140,6 @@ go get -u github.com/go-vgo/robotgo 注意 go1.10.x C 文件编译缓存问题, [golang #24355](https://github.com/golang/go/issues/24355). `go mod vendor` problem, [golang #26366](https://github.com/golang/go/issues/26366). - ## [Examples:](https://github.com/go-vgo/robotgo/blob/master/examples) #### [鼠标](https://github.com/go-vgo/robotgo/blob/master/examples/mouse/main.go) @@ -127,9 +152,23 @@ import ( ) func main() { - robotgo.ScrollMouse(10, "up") - robotgo.MouseClick("left", true) - robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) + // robotgo.ScrollMouse(10, "up") + robotgo.Scroll(0, -10) + robotgo.Scroll(100, 0) + robotgo.MilliSleep(100) + // robotgo.ScrollRelative(10, -100) + robotgo.ScrollSmooth(-10, 6) + + robotgo.MouseSleep = 100 + robotgo.Move(10, 20) + robotgo.MoveRelative(0, -10) + robotgo.Drag(10, 10) + + robotgo.Click("left", true) + robotgo.MoveSmooth(100, 200, 1.0, 10.0) + + robotgo.Toggle("left") + robotgo.Toggle("left", "up") } ``` @@ -145,24 +184,29 @@ import ( ) func main() { - robotgo.TypeStr("Hello World") - robotgo.TypeStr("测试") - // robotgo.TypeString("测试") + robotgo.TypeStr("Hello World. Winter is coming!") + robotgo.TypeStr("だんしゃり", 1.0) + // robotgo.TypeStr("テストする") - robotgo.TypeStr("山达尔星新星军团, galaxy. こんにちは世界.") + robotgo.TypeStr("Hi galaxy. こんにちは世界.") robotgo.Sleep(1) - // ustr := uint32(robotgo.CharCodeAt("测试", 0)) + // ustr := uint32(robotgo.CharCodeAt("テストする", 0)) // robotgo.UnicodeType(ustr) + robotgo.KeySleep = 100 robotgo.KeyTap("enter") - // robotgo.TypeString("en") + // robotgo.TypeStr("en") robotgo.KeyTap("i", "alt", "command") arr := []string{"alt", "command"} robotgo.KeyTap("i", arr) - robotgo.WriteAll("测试") + robotgo.MilliSleep(100) + robotgo.KeyToggle("a") + robotgo.KeyToggle("a", "up") + + robotgo.WriteAll("テストする") text, err := robotgo.ReadAll() if err == nil { fmt.Println(text) @@ -179,6 +223,7 @@ import ( "fmt" "github.com/go-vgo/robotgo" + "github.com/vcaesar/imgo" ) func main() { @@ -187,6 +232,16 @@ func main() { color := robotgo.GetPixelColor(100, 200) fmt.Println("color----", color) + + sx, sy := robotgo.GetScreenSize() + fmt.Println("get screen size: ", sx, sy) + + bit := robotgo.CaptureScreen(10, 10, 30, 30) + defer robotgo.FreeBitmap(bit) + robotgo.SaveBitmap(bit, "test_1.png") + + img := robotgo.ToImage(bit) + imgo.Save("test.png", img) } ``` @@ -205,28 +260,108 @@ func main() { bitmap := robotgo.CaptureScreen(10, 20, 30, 40) // use `defer robotgo.FreeBitmap(bit)` to free the bitmap defer robotgo.FreeBitmap(bitmap) - fmt.Println("...", bitmap) - fx, fy := robotgo.FindBitmap(bitmap) + fmt.Println("bitmap...", bitmap) + img := robotgo.ToImage(bitmap) + robotgo.SavePng(img, "test_1.png") + + bit2 := robotgo.ToCBitmap(robotgo.ImgToBitmap(img)) + fx, fy := robotgo.FindBitmap(bit2) + fmt.Println("FindBitmap------ ", fx, fy) + robotgo.Move(fx, fy) + + arr := robotgo.FindAllBitmap(bit2) + fmt.Println("Find all bitmap: ", arr) + robotgo.SaveBitmap(bitmap, "test.png") + + fx, fy = robotgo.FindBitmap(bitmap) fmt.Println("FindBitmap------", fx, fy) robotgo.SaveBitmap(bitmap, "test.png") } ``` +#### [OpenCV](https://github.com/vcaesar/gcv) + +```Go +package main + +import ( + "fmt" + "math/rand" + + "github.com/go-vgo/robotgo" + "github.com/vcaesar/gcv" +) + +func main() { + opencv() +} + +func opencv() { + name := "test.png" + name1 := "test_001.png" + robotgo.SaveCapture(name1, 10, 10, 30, 30) + robotgo.SaveCapture(name) + + fmt.Print("gcv find image: ") + fmt.Println(gcv.FindImgFile(name1, name)) + fmt.Println(gcv.FindAllImgFile(name1, name)) + + bit := robotgo.OpenBitmap(name1) + defer robotgo.FindBitmap(bit) + fmt.Print("find bitmap: ") + fmt.Println(robotgo.FindBitmap(bit)) + + // bit0 := robotgo.CaptureScreen() + // img := robotgo.ToImage(bit0) + // bit1 := robotgo.CaptureScreen(10, 10, 30, 30) + // img1 := robotgo.ToImage(bit1) + // defer robotgo.FreeBitmapArr(bit0, bit1) + img := robotgo.CaptureImg() + img1 := robotgo.CaptureImg(10, 10, 30, 30) + + fmt.Print("gcv find image: ") + fmt.Println(gcv.FindImg(img1, img)) + fmt.Println() + + res := gcv.FindAllImg(img1, img) + fmt.Println(res[0].TopLeft.Y, res[0].Rects.TopLeft.X, res) + x, y := res[0].TopLeft.X, res[0].TopLeft.Y + robotgo.Move(x, y-rand.Intn(5)) + robotgo.MilliSleep(100) + robotgo.Click() + + res = gcv.FindAll(img1, img) // use find template and sift + fmt.Println("find all: ", res) + res1 := gcv.Find(img1, img) + fmt.Println("find: ", res1) + + img2, _, _ := robotgo.DecodeImg("test_001.png") + x, y = gcv.FindX(img2, img) + fmt.Println(x, y) +} +``` + #### [事件](https://github.com/go-vgo/robotgo/blob/master/examples/gohook/main.go) ```Go package main import ( - "fmt" + "fmt" "github.com/go-vgo/robotgo" hook "github.com/robotn/gohook" ) func main() { + add() + low() + event() +} + +func add() { fmt.Println("--- Please press ctrl + shift + q to stop hook ---") robotgo.EventHook(hook.KeyDown, []string{"q", "ctrl", "shift"}, func(e hook.Event) { fmt.Println("ctrl-shift-q") @@ -240,7 +375,18 @@ func main() { s := robotgo.EventStart() <-robotgo.EventProcess(s) +} +func low() { + evChan := hook.Start() + defer hook.End() + + for ev := range evChan { + fmt.Println("hook: ", ev) + } +} + +func event() { ok := robotgo.AddEvents("q", "ctrl", "shift") if ok { fmt.Println("add events...") @@ -290,8 +436,8 @@ func main() { robotgo.Kill(100) } - abool := robotgo.ShowAlert("test", "robotgo") - if abool == 0 { + abool := robotgo.Alert("test", "robotgo") + if abool { fmt.Println("ok@@@ ", "ok") } @@ -302,7 +448,8 @@ func main() { ## CrossCompiling -##### Windows64 to win32 +##### Windows64 to windows32 + ```Go SET CGO_ENABLED=1 SET GOARCH=386 @@ -310,32 +457,38 @@ go build main.go ``` #### Other to windows + +Install Requirements (Ubuntu): + +```bash +sudo apt install gcc-multilib +sudo apt install gcc-mingw-w64 +sudo apt install libz-mingw-w64-dev +``` + +Build the binary: + ```Go GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ go build -x ./ ``` + ``` // CC=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\gcc.exe // CXX=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\g++.exe ``` ## Authors -* [The author is vz](https://github.com/vcaesar) -* [Maintainers](https://github.com/orgs/go-vgo/people) -* [Contributors](https://github.com/go-vgo/robotgo/graphs/contributors) + +- [The author is vz](https://github.com/vcaesar) +- [Maintainers](https://github.com/orgs/go-vgo/people) +- [Contributors](https://github.com/go-vgo/robotgo/graphs/contributors) ## Plans + - 更新 Find an image on screen, read pixels from an image - 更新 Window Handle - 尝试支持 Android, 也许支持 IOS -## Donate - -支持 robotgo, [buy me a coffee](https://github.com/go-vgo/buy-me-a-coffee). - -#### Paypal - -Donate money by [paypal](https://www.paypal.me/veni0/25) to my account [vzvway@gmail.com](vzvway@gmail.com) - ## Contributors - See [contributors page](https://github.com/go-vgo/robotgo/graphs/contributors) for full list of contributors. @@ -345,4 +498,4 @@ Donate money by [paypal](https://www.paypal.me/veni0/25) to my account [vzvway@g Robotgo is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0), with portions covered by various BSD-like licenses. -See [LICENSE-APACHE](http://www.apache.org/licenses/LICENSE-2.0), [LICENSE-MIT](https://github.com/go-vgo/robotgo/blob/master/LICENSE). \ No newline at end of file +See [LICENSE-APACHE](http://www.apache.org/licenses/LICENSE-2.0), [LICENSE-MIT](https://github.com/go-vgo/robotgo/blob/master/LICENSE). diff --git a/docs/doc.md b/docs/archive/doc.md similarity index 95% rename from docs/doc.md rename to docs/archive/doc.md index b5fe095f..1a5d3b15 100644 --- a/docs/doc.md +++ b/docs/archive/doc.md @@ -5,14 +5,14 @@ ## [Keyboard](#Keyboard) ##### [Keys](https://github.com/go-vgo/robotgo/blob/master/docs/keys.md) -##### [SetKeyboardDelay](#SetKeyDelay) (Equivalent to SetKeyDelay, Wno-deprecated) + ##### [SetKeyDelay](#SetKeyDelay) ##### [KeyTap](#KeyTap) ##### [KeyToggle](#KeyToggle) -##### [TypeString](#TypeString) -##### [TypeStringDelayed](#TypeStrDelay) (Equivalent to TypeStrDelay, Wno-deprecated) -##### [TypeStrDelay](#TypeStrDelay) + ##### [TypeStr](#TypeStr) +##### [TypeStrDelay](#TypeStrDelay) ##### [WriteAll](#WriteAll) ##### [ReadAll](#ReadAll) @@ -57,7 +57,7 @@ ## [Event](#Event) -##### [LEvent](#LEvent) (Equivalent to AddEvent, Wno-deprecated) + ##### [AddEvent](#AddEvent) ##### [StopEvent](#StopEvent) @@ -71,7 +71,7 @@ ##### [GetActive](#GetActive) ##### [SetHandle](#SetHandle) ##### [GetHandle](#GetHandle) -##### [GetBHandle](#GetHandle) + ##### [GetTitle](#GetTitle) ##### [GetPID](#GetPID) ##### [Pids](#Pids) @@ -126,24 +126,24 @@ modifier (optional, string or array) - Accepts alt, command (mac), control, and #### Return: return KeyToggle status -###

.TypeString(string)

+ -###

.TypeStrDelay(string, cpm)

+###

.TypeStr(string)

#### Arguments: string - The string to send. - cpm - Characters per minute. -###

.TypeStr(string)

+###

.TypeStrDelay(string, cpm)

#### Arguments: string - The string to send. + cpm - Characters per minute. ###

.WriteAll(text string)

@@ -213,8 +213,8 @@ robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) #### Examples: ```Go -robogo.MouseClick() -robogo.MouseClick("left", true) +robotgo.MouseClick() +robotgo.MouseClick("left", true) ``` ###

.MoveClick(x, y, button, double)

@@ -231,8 +231,8 @@ robogo.MouseClick("left", true) #### Examples: ```Go -robogo.MoveClick(10, 20) -robogo.MoveClick(10, 20, "left", true) +robotgo.MoveClick(10, 20) +robotgo.MoveClick(10, 20, "left", true) ``` ###

.MouseToggle(down, button)

@@ -331,7 +331,7 @@ robotgo.ScrollMouse(50, "down") Gets part or all of the screen. GoCaptureScreen Returns a go struct - Capture_Screen (Drop support) + #### Arguments: diff --git a/docs/doc_zh.md b/docs/archive/doc_zh.md similarity index 96% rename from docs/doc_zh.md rename to docs/archive/doc_zh.md index 774df827..a3dbebc1 100644 --- a/docs/doc_zh.md +++ b/docs/archive/doc_zh.md @@ -5,14 +5,14 @@ ## [键盘](#Keyboard) ##### [Keys](https://github.com/go-vgo/robotgo/blob/master/docs/keys.md) -##### [SetKeyboardDelay](#SetKeyDelay) (相当于 SetKeyDelay, 废弃 API) + ##### [SetKeyDelay](#SetKeyDelay) ##### [KeyTap](#KeyTap) ##### [KeyToggle](#KeyToggle) -##### [TypeString](#TypeString) -##### [TypeStringDelayed](#TypeStrDelay) (相当于 TypeStrDelay, 废弃 API) -##### [TypeStrDelay](#TypeStrDelay) + ##### [TypeStr](#TypeStr) +##### [TypeStrDelay](#TypeStrDelay) ##### [WriteAll](#WriteAll) ##### [ReadAll](#ReadAll) @@ -59,7 +59,7 @@ ## [事件](#Event) -##### [LEvent](#AddEvent) (相当于 AddEvent, 废弃 API) + ##### [AddEvent](#AddEvent) ##### [StopEvent](#StopEvent) @@ -73,7 +73,7 @@ ##### [GetActive](#GetActive) ##### [SetHandle](#SetHandle) ##### [GetHandle](#GetHandle) -##### [GetBHandle](#GetHandle) + ##### [GetTitle](#GetTitle) ##### [GetPID](#GetPID) ##### [Pids](#Pids) @@ -131,24 +131,25 @@ modifier (optional, string or array) - Accepts alt, command (mac), control, and 返回 KeyToggle 状态 -###

.TypeString(string)

+ -###

.TypeStrDelay(string, cpm)

+###

.TypeStr(string)

#### 参数: string - The string to send. - cpm - Characters per minute. -###

.TypeStr(string)

+ +###

.TypeStrDelay(string, cpm)

#### 参数: string - The string to send. + cpm - Characters per minute. ###

.WriteAll(text string)

@@ -220,8 +221,8 @@ robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) #### 示例: ```Go -robogo.MouseClick() -robogo.MouseClick("left", true) +robotgo.MouseClick() +robotgo.MouseClick("left", true) ``` ###

.MoveClick(x, y, button, double)

@@ -238,8 +239,8 @@ robogo.MouseClick("left", true) #### 示例: ```Go -robogo.MoveClick(10, 20) -robogo.MoveClick(10, 20, "left", true) +robotgo.MoveClick(10, 20) +robotgo.MoveClick(10, 20, "left", true) ``` ###

.MouseToggle(down, button)

@@ -345,7 +346,7 @@ robotgo.ScrollMouse(50, "down") Gets part or all of the screen. GoCaptureScreen Returns a go struct - Capture_Screen (废弃) + #### 参数: diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 00000000..47187071 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,33 @@ +## CrossCompiling + +##### Windows64 to windows32 + +```Go +SET CGO_ENABLED=1 +SET GOARCH=386 +go build main.go +``` + +#### Other to windows + +Install Requirements (Ubuntu): + +```bash +sudo apt install gcc-multilib +sudo apt install gcc-mingw-w64 +# fix err: zlib.h: No such file or directory, Just used by bitmap. +sudo apt install libz-mingw-w64-dev +``` + +Build the binary: + +```Go +GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ go build -x ./ +``` + +``` +// CC=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\gcc.exe +// CXX=mingw-w64\x86_64-7.2.0-win32-seh-rt_v5-rev1\mingw64\bin\g++.exe +``` + +Some discussions and questions, please see [issues/228](https://github.com/go-vgo/robotgo/issues/228), [issues/143](https://github.com/go-vgo/robotgo/issues/143). diff --git a/docs/keys.md b/docs/keys.md index fcfe3f62..cedc4fdf 100644 --- a/docs/keys.md +++ b/docs/keys.md @@ -1,3 +1,25 @@ +## Type Conversion + +| | type conversion | func | +| --- | --------------------------------- | ----------------------- | +| \* | robotgo.Bitmap -> robotgo.CBitmap | robotgo.ToCBitmap() | +| | robotgo.Bitmap -> \*image.RGBA | robotgo.ToRGBAGo() | +| \* | robotgo.CBitmap -> C.MMBitmapRef | robotgo.ToMMBitmapRef() | +| | robotgo.CBitmap -> robotgo.Bitmap | robotgo.ToBitmap() | +| | robotgo.CBitmap -> image.Image | robotgo.ToImage() | +| | robotgo.CBitmap -> \*image.RGBA | robotgo.ToRGBA() | +| \* | C.MMBitmapRef -> robotgo.CBitmap | robotgo.CBitmap() | +| \* | image.Image -> robotgo.Bitmap | robotgo.ImgToBitmap() | +| | image.Image -> robotgo.CBitmap | robotgo.ImgToCBitmap() | +| | image.Image -> []byte | robotgo.ToByteImg() | +| | image.Image -> string | robotgo.ToStringImg() | +| \* | \*image.RGBA -> robotgo.Bitmap | robotgo.RGBAToBitmap() | +| \* | []byte -> image.Image | robotgo.ByteToImg() | +| | []byte-> robotgo.CBitmap | robotgo.ByteToCBitmap() | +| | []byte -> string | string() | +| \* | string -> image.Image | robotgo.StrToImg() | +| | string -> byte | []byte() | + # Keys ```Go @@ -46,7 +68,7 @@ "cmd" is the "win" key for windows "lcmd" left command "rcmd" right command - "command" + // "command" "alt" "lalt" left alt "ralt" right alt @@ -57,7 +79,7 @@ "shift" "lshift" left shift "rshift" right shift - "right_shift" + // "right_shift" "capslock" "space" "print" @@ -100,22 +122,22 @@ "num_enter" "num_equal" - // "numpad_0" No Linux support - "numpad_0" - "numpad_1" - "numpad_2" - "numpad_3" - "numpad_4" - "numpad_5" - "numpad_6" - "numpad_7" - "numpad_8" - "numpad_9" - "numpad_lock" + // // "numpad_0" No Linux support + // "numpad_0" + // "numpad_1" + // "numpad_2" + // "numpad_3" + // "numpad_4" + // "numpad_5" + // "numpad_6" + // "numpad_7" + // "numpad_8" + // "numpad_9" + // "numpad_lock" "lights_mon_up" Turn up monitor brightness No Windows support "lights_mon_down" Turn down monitor brightness No Windows support "lights_kbd_toggle" Toggle keyboard backlight on/off No Windows support "lights_kbd_up" Turn up keyboard backlight brightness No Windows support "lights_kbd_down" Turn down keyboard backlight brightness No Windows support -``` \ No newline at end of file +``` diff --git a/event/goEvent.h b/event/goEvent.h deleted file mode 100644 index b3467fb8..00000000 --- a/event/goEvent.h +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include "pub.h" - - -void dispatch_proc(iohook_event * const event) { - char buffer[256] = { 0 }; - size_t length = snprintf(buffer, sizeof(buffer), - "id=%i,when=%" PRIu64 ",mask=0x%X", - event->type, event->time, event->mask); - - switch (event->type) { - case EVENT_KEY_PRESSED: - // If the escape key is pressed, naturally terminate the program. - if (event->data.keyboard.keycode == VC_ESCAPE) { - // int status = hook_stop(); - // switch (status) { - // // System level errors. - // case IOHOOK_ERROR_OUT_OF_MEMORY: - // loggerProc(LOG_LEVEL_ERROR, "Failed to allocate memory. (%#X)", status); - // break; - - // case IOHOOK_ERROR_X_RECORD_GET_CONTEXT: - // // NOTE This is the only platform specific error that occurs on hook_stop(). - // loggerProc(LOG_LEVEL_ERROR, "Failed to get XRecord context. (%#X)", status); - // break; - - // // Default error. - // case IOHOOK_FAILURE: - // default: - // loggerProc(LOG_LEVEL_ERROR, "An unknown hook error occurred. (%#X)", status); - // break; - // } - } - case EVENT_KEY_RELEASED: - snprintf(buffer + length, sizeof(buffer) - length, - ",keycode=%u,rawcode=0x%X", - event->data.keyboard.keycode, event->data.keyboard.rawcode); - int akeyCode = (uint16_t) event->data.keyboard.keycode; - - if (event->data.keyboard.keycode == VC_ESCAPE - && atoi(cevent) == 11) { - int stopEvent = stop_event(); - // printf("stop_event%d\n", stopEvent); - cstatus = 0; - } - - // printf("atoi(str)---%d\n", atoi(cevent)); - if (akeyCode == atoi(cevent)) { - int stopEvent = stop_event(); - // printf("%d\n", stopEvent); - cstatus = 0; - } - break; - - case EVENT_KEY_TYPED: - snprintf(buffer + length, sizeof(buffer) - length, - ",keychar=%lc,rawcode=%u", - (uint16_t) event->data.keyboard.keychar, - event->data.keyboard.rawcode); - - #ifdef WE_REALLY_WANT_A_POINTER - char *buf = malloc (6); - #else - char buf[6]; - #endif - - sprintf(buf, "%lc", (uint16_t) event->data.keyboard.keychar); - - #ifdef WE_REALLY_WANT_A_POINTER - free (buf); - #endif - - if (strcmp(buf, cevent) == 0) { - int stopEvent = stop_event(); - // printf("%d\n", stopEvent); - cstatus = 0; - } - // return (char*) event->data.keyboard.keychar; - break; - - case EVENT_MOUSE_PRESSED: - case EVENT_MOUSE_RELEASED: - case EVENT_MOUSE_CLICKED: - case EVENT_MOUSE_MOVED: - case EVENT_MOUSE_DRAGGED: - snprintf(buffer + length, sizeof(buffer) - length, - ",x=%i,y=%i,button=%i,clicks=%i", - event->data.mouse.x, event->data.mouse.y, - event->data.mouse.button, event->data.mouse.clicks); - - int abutton = event->data.mouse.button; - int aclicks = event->data.mouse.clicks; - int amouse = -1; - - if (strcmp(cevent, "mleft") == 0) { - amouse = 1; - } - if (strcmp(cevent, "mright") == 0) { - amouse = 2; - } - if (strcmp(cevent, "wheelDown") == 0) { - amouse = 4; - } - if (strcmp(cevent, "wheelUp") == 0) { - amouse = 5; - } - if (strcmp(cevent, "wheelLeft") == 0) { - amouse = 6; - } - if (strcmp(cevent, "wheelRight") == 0) { - amouse = 7; - } - if (abutton == amouse && aclicks == 1) { - int stopEvent = stop_event(); - cstatus = 0; - } - - break; - - case EVENT_MOUSE_WHEEL: - snprintf(buffer + length, sizeof(buffer) - length, - ",type=%i,amount=%i,rotation=%i", - event->data.wheel.type, event->data.wheel.amount, - event->data.wheel.rotation); - break; - - default: - break; - } - - // fprintf(stdout, "----%s\n", buffer); -} - -int add_event(char *key_event) { - // (uint16_t *) - cevent = key_event; - // Set the logger callback for library output. - hookSetlogger(&loggerProc); - - // Set the event callback for IOhook events. - hook_set_dispatch_proc(&dispatch_proc); - // Start the hook and block. - // NOTE If EVENT_HOOK_ENABLED was delivered, the status will always succeed. - int status = hook_run(); - - switch (status) { - case IOHOOK_SUCCESS: - // Everything is ok. - break; - - // System level errors. - case IOHOOK_ERROR_OUT_OF_MEMORY: - loggerProc(LOG_LEVEL_ERROR, "Failed to allocate memory. (%#X)", status); - break; - - - // X11 specific errors. - case IOHOOK_ERROR_X_OPEN_DISPLAY: - loggerProc(LOG_LEVEL_ERROR, "Failed to open X11 display. (%#X)", status); - break; - - case IOHOOK_ERROR_X_RECORD_NOT_FOUND: - loggerProc(LOG_LEVEL_ERROR, "Unable to locate XRecord extension. (%#X)", status); - break; - - case IOHOOK_ERROR_X_RECORD_ALLOC_RANGE: - loggerProc(LOG_LEVEL_ERROR, "Unable to allocate XRecord range. (%#X)", status); - break; - - case IOHOOK_ERROR_X_RECORD_CREATE_CONTEXT: - loggerProc(LOG_LEVEL_ERROR, "Unable to allocate XRecord context. (%#X)", status); - break; - - case IOHOOK_ERROR_X_RECORD_ENABLE_CONTEXT: - loggerProc(LOG_LEVEL_ERROR, "Failed to enable XRecord context. (%#X)", status); - break; - - - // Windows specific errors. - case IOHOOK_ERROR_SET_WINDOWS_HOOK_EX: - loggerProc(LOG_LEVEL_ERROR, "Failed to register low level windows hook. (%#X)", status); - break; - - - // Darwin specific errors. - case IOHOOK_ERROR_AXAPI_DISABLED: - loggerProc(LOG_LEVEL_ERROR, "Failed to enable access for assistive devices. (%#X)", status); - break; - - case IOHOOK_ERROR_CREATE_EVENT_PORT: - loggerProc(LOG_LEVEL_ERROR, "Failed to create apple event port. (%#X)", status); - break; - - case IOHOOK_ERROR_CREATE_RUN_LOOP_SOURCE: - loggerProc(LOG_LEVEL_ERROR, "Failed to create apple run loop source. (%#X)", status); - break; - - case IOHOOK_ERROR_GET_RUNLOOP: - loggerProc(LOG_LEVEL_ERROR, "Failed to acquire apple run loop. (%#X)", status); - break; - - case IOHOOK_ERROR_CREATE_OBSERVER: - loggerProc(LOG_LEVEL_ERROR, "Failed to create apple run loop observer. (%#X)", status); - break; - - // Default error. - case IOHOOK_FAILURE: - default: - loggerProc(LOG_LEVEL_ERROR, "An unknown hook error occurred. (%#X)", status); - break; - } - - // return status; - // printf("%d\n", status); - return cstatus; -} - -int stop_event(){ - int status = hook_stop(); - switch (status) { - // System level errors. - case IOHOOK_ERROR_OUT_OF_MEMORY: - loggerProc(LOG_LEVEL_ERROR, "Failed to allocate memory. (%#X)", status); - break; - - case IOHOOK_ERROR_X_RECORD_GET_CONTEXT: - // NOTE This is the only platform specific error that occurs on hook_stop(). - loggerProc(LOG_LEVEL_ERROR, "Failed to get XRecord context. (%#X)", status); - break; - - // Default error. - case IOHOOK_FAILURE: - default: - // loggerProc(LOG_LEVEL_ERROR, "An unknown hook error occurred. (%#X)", status); - break; - } - - return status; -} \ No newline at end of file diff --git a/event/pub.h b/event/pub.h deleted file mode 100644 index e93b7a91..00000000 --- a/event/pub.h +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#include "../base/os.h" - -#if defined(IS_MACOSX) - #include "../cdeps/hook/darwin/input_c.h" - #include "../cdeps/hook/darwin/hook_c.h" - #include "../cdeps/hook/darwin/event_c.h" - #include "../cdeps/hook/darwin/properties_c.h" -#elif defined(USE_X11) - //#define USE_XKBCOMMON 0 - #include "../cdeps/hook/x11/input_c.h" - #include "../cdeps/hook/x11/hook_c.h" - #include "../cdeps/hook/x11/event_c.h" - #include "../cdeps/hook/x11/properties_c.h" -#elif defined(IS_WINDOWS) - #include "../cdeps/hook/windows/input_c.h" - #include "../cdeps/hook/windows/hook_c.h" - #include "../cdeps/hook/windows/event_c.h" - #include "../cdeps/hook/windows/properties_c.h" -#endif - -#include -#include -#include -#include -#include -#include "../cdeps/hook/iohook.h" - - -int vccode[100]; -int codesz; - -char *cevent; -int rrevent; -// uint16_t *cevent; -int cstatus = 1; - - -int stop_event(); -int add_event(char *key_event); -// int allEvent(char *key_event); -int allEvent(char *key_event, int vcode[], int size); - -// NOTE: The following callback executes on the same thread that hook_run() is called -// from. - -struct _MEvent { - uint8_t id; - size_t mask; - uint16_t keychar; - // char *keychar; - size_t x; - uint8_t y; - uint8_t bytesPerPixel; -}; - -typedef struct _MEvent MEvent; -// typedef MMBitmap *MMBitmapRef; - -MEvent mEvent; - - -bool loggerProc(unsigned int level, const char *format, ...) { - bool status = false; - - va_list args; - switch (level) { - #ifdef USE_DEBUG - case LOG_LEVEL_DEBUG: - case LOG_LEVEL_INFO: - va_start(args, format); - status = vfprintf(stdout, format, args) >= 0; - va_end(args); - break; - #endif - - case LOG_LEVEL_WARN: - case LOG_LEVEL_ERROR: - va_start(args, format); - status = vfprintf(stderr, format, args) >= 0; - va_end(args); - break; - } - - return status; -} \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index 4692a6cb..e7188e89 100644 --- a/examples/README.md +++ b/examples/README.md @@ -17,9 +17,10 @@ import ( ) func main() { - robotgo.ScrollMouse(10, "up") + // robotgo.ScrollMouse(10, "up") + robotgo.Scroll(0, 10) robotgo.MouseClick("left", true) - robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) + robotgo.MoveSmooth(100, 200, 1.0, 100.0) } ``` @@ -36,13 +37,13 @@ import ( func main() { robotgo.TypeStr("Hello World") - // robotgo.TypeString("だんしゃり") + // robotgo.TypeStr("だんしゃり") robotgo.TypeStr("だんしゃり") // ustr := uint32(robotgo.CharCodeAt("だんしゃり", 0)) // robotgo.UnicodeType(ustr) robotgo.KeyTap("enter") - robotgo.TypeString("en") + robotgo.TypeStr("en") robotgo.KeyTap("i", "alt", "command") arr := []string{"alt", "command"} robotgo.KeyTap("i", arr) @@ -67,7 +68,7 @@ import ( ) func main() { - x, y := robotgo.GetMousePos() + x, y := robotgo.Location() fmt.Println("pos:", x, y) color := robotgo.GetPixelColor(100, 200) fmt.Println("color----", color) diff --git a/examples/bitmap-bytes/main.go b/examples/bitmap-bytes/main.go deleted file mode 100644 index cc012b9c..00000000 --- a/examples/bitmap-bytes/main.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "bytes" - "log" - - "image/jpeg" - "io/ioutil" - - "github.com/go-vgo/robotgo" - "golang.org/x/image/bmp" -) - -func main() { - bitMap := robotgo.CaptureScreen() - defer robotgo.FreeBitmap(bitMap) - - bs := robotgo.ToBitmapBytes(bitMap) - img, err := bmp.Decode(bytes.NewReader(bs)) - if err != nil { - log.Println("bmp.Decode err is: ", err) - return - } - - b := new(bytes.Buffer) - err = jpeg.Encode(b, img, &jpeg.Options{Quality: 20}) - if err != nil { - log.Println("jpeg.Encode err is: ", err) - return - } - - log.Println("bytes: ", b.Bytes()) - ioutil.WriteFile("out.jpg", b.Bytes(), 0666) -} diff --git a/examples/bitmap/main.go b/examples/bitmap/main.go deleted file mode 100644 index ae858011..00000000 --- a/examples/bitmap/main.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -package main - -import ( - "fmt" - "log" - - "github.com/go-vgo/robotgo" - "github.com/vcaesar/imgo" - // "go-vgo/robotgo" -) - -func toBitmap(bmp robotgo.CBitmap) { - bitmap := robotgo.ToMMBitmapRef(bmp) - - gbit := robotgo.ToBitmap(bitmap) - fmt.Println("go bitmap", gbit, gbit.Width) - - cbit := robotgo.ToCBitmap(gbit) - // defer robotgo.FreeBitmap(cbit) - log.Println("cbit == bitmap: ", cbit == bitmap) - robotgo.SaveBitmap(cbit, "tocbitmap.png") -} - -func findColor(bmp robotgo.CBitmap) { - bitmap := robotgo.ToMMBitmapRef(bmp) - - // find the color in bitmap - color := robotgo.GetColor(bitmap, 1, 2) - fmt.Println("color...", color) - cx, cy := robotgo.FindColor(robotgo.CHex(color), bitmap, 1.0) - fmt.Println("pos...", cx, cy) - cx, cy = robotgo.FindColor(robotgo.CHex(color)) - fmt.Println("pos...", cx, cy) - - cx, cy = robotgo.FindColor(0xAADCDC, bitmap) - fmt.Println("pos...", cx, cy) - cx, cy = robotgo.FindColor(0xAADCDC, nil, 0.1) - fmt.Println("pos...", cx, cy) - - cx, cy = robotgo.FindColorCS(0xAADCDC, 388, 179, 300, 300) - fmt.Println("pos...", cx, cy) - - cnt := robotgo.CountColor(0xAADCDC, bitmap) - fmt.Println("count...", cnt) - cnt1 := robotgo.CountColorCS(0xAADCDC, 10, 20, 30, 40) - fmt.Println("count...", cnt1) -} - -func bitmapString(bmp robotgo.CBitmap) { - bitmap := robotgo.ToMMBitmapRef(bmp) - - // creates bitmap from string by bitmap - bitstr := robotgo.TostringBitmap(bitmap) - fmt.Println("bitstr...", bitstr) - - // sbitmap := robotgo.BitmapFromstring(bitstr, 2) - // fmt.Println("...", sbitmap) - - // sbitmap := robotgo.BitmapStr(bitstr) - sbitmap := robotgo.BitmapFromStr(bitstr) - fmt.Println("bitmap str...", sbitmap) - robotgo.SaveBitmap(sbitmap, "teststr.png") -} - -func bitmapTool(bmp robotgo.CBitmap) { - bitmap := robotgo.ToMMBitmapRef(bmp) - - // bitmap := robotgo.CaptureScreen(10, 20, 30, 40) - abool := robotgo.PointInBounds(bitmap, 1, 2) - fmt.Println("point in bounds...", abool) - - // returns new bitmap object created from a portion of another - bitpos := robotgo.GetPortion(bitmap, 10, 10, 11, 10) - fmt.Println(bitpos) - - // saves image to absolute filepath in the given format - robotgo.SaveBitmap(bitmap, "test.png") - robotgo.SaveBitmap(bitmap, "test31.tif", 1) -} - -func decode() { - img, name, err := robotgo.DecodeImg("test.png") - if err != nil { - log.Println("decode image ", err) - } - fmt.Println("decode test.png", img, name) - - byt := robotgo.OpenImg("test.png") - imgo.Save("test2.png", byt) - - w, h := robotgo.GetImgSize("test.png") - fmt.Println("image width and hight ", w, h) - w, h = imgo.GetSize("test.png") - fmt.Println("image width and hight ", w, h) - - // convert image - robotgo.Convert("test.png", "test.tif") -} - -func bitmapTest(bmp robotgo.CBitmap) { - bitmap := robotgo.ToMMBitmapRef(bmp) - - bit := robotgo.CaptureScreen(1, 2, 40, 40) - defer robotgo.FreeBitmap(bit) - fmt.Println("CaptureScreen...", bit) - - // searches for needle in bitmap - fx, fy := robotgo.FindBitmap(bit, bitmap) - fmt.Println("FindBitmap------", fx, fy) - - // fx, fy := robotgo.FindBit(bitmap) - // fmt.Println("FindBitmap------", fx, fy) - - fx, fy = robotgo.FindBitmap(bit) - fmt.Println("FindBitmap------", fx, fy) -} - -func findBitmap(bmp robotgo.CBitmap) { - fx, fy := robotgo.FindBitmap(robotgo.ToMMBitmapRef(bmp)) - fmt.Println("findBitmap: ", fx, fy) - - fx, fy = robotgo.FindCBitmap(bmp) - fmt.Println("findCBitmap: ", fx, fy) - fx, fy = robotgo.FindCBitmap(bmp, nil, 0.1) - fmt.Println("findCBitmap: ", fx, fy) - - // open image bitmap - openbit := robotgo.OpenBitmap("test.tif") - fmt.Println("openBitmap...", openbit) - - fx, fy = robotgo.FindBitmap(openbit) - fmt.Println("FindBitmap------", fx, fy) - - fx, fy = robotgo.FindPic("test.tif") - fmt.Println("FindPic------", fx, fy) -} - -func bitmap() { - //////////////////////////////////////////////////////////////////////////////// - // Bitmap - //////////////////////////////////////////////////////////////////////////////// - - // gets all of the screen - abitMap := robotgo.CaptureScreen() - fmt.Println("abitMap...", abitMap) - - // gets part of the screen - bitmap := robotgo.CaptureScreen(100, 200, 30, 30) - defer robotgo.FreeBitmap(bitmap) - fmt.Println("CaptureScreen...", bitmap) - - cbit := robotgo.CBitmap(bitmap) - toBitmap(cbit) - - findColor(cbit) - - count := robotgo.CountBitmap(abitMap, bitmap) - fmt.Println("count...", count) - - bitmapTest(cbit) - findBitmap(cbit) - - bitmapString(cbit) - bitmapTool(cbit) - - decode() - - // free the bitmap - robotgo.FreeBitmap(abitMap) - // robotgo.FreeBitmap(bitmap) -} - -func main() { - bitmap() -} diff --git a/examples/cbitmap/main.go b/examples/cbitmap/main.go deleted file mode 100644 index c9c9560b..00000000 --- a/examples/cbitmap/main.go +++ /dev/null @@ -1,53 +0,0 @@ -package main - -import ( - "github.com/go-vgo/robotgo" -) - -func main() { - bmp, free := loadBitmaps("start.png", "chest.png", "eat.png") - defer free() - - for { - clickBitmap(bmp["start.png"], false) - clickBitmap(bmp["chest.png"], true) - clickBitmap(bmp["eat.png"], false) - } -} - -func loadBitmaps(files ...string) (bitmaps map[string]robotgo.Bitmap, free func()) { - freeFuncs := make([]func(), 0) - bitmaps = make(map[string]robotgo.Bitmap) - for _, f := range files { - bitmap, freeFunc := readBitmap(f) - bitmaps[f] = bitmap - freeFuncs = append(freeFuncs, freeFunc) - } - - free = func() { - for key := range freeFuncs { - freeFuncs[key]() - } - } - return bitmaps, free -} - -func readBitmap(file string) (bitmap robotgo.Bitmap, free func()) { - cBitmap := robotgo.OpenBitmap(file) - bitmap = robotgo.ToBitmap(cBitmap) - free = func() { - robotgo.FreeBitmap(cBitmap) - } - return bitmap, free -} - -func clickBitmap(bmp robotgo.Bitmap, doubleClick bool) bool { - fx, fy := robotgo.FindBitmap(robotgo.ToCBitmap(bmp)) - if fx != -1 && fy != -1 { - robotgo.MoveMouse(fx, fy) - robotgo.MouseClick("left", doubleClick) - return true - } - - return false -} diff --git a/examples/color-picker/main.go b/examples/color-picker/main.go deleted file mode 100644 index 48f188ac..00000000 --- a/examples/color-picker/main.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/go-vgo/robotgo" -) - -func colorPicker() { - m := robotgo.AddEvent("mleft") - if m { - x, y := robotgo.GetMousePos() - fmt.Println("mouse pos: ", x, y) - - clo := robotgo.GetPixelColor(x, y) - fmt.Println("color: #", clo) - - // clipboard - robotgo.WriteAll("#" + clo) - } -} - -func main() { - fmt.Println("color picker...") - - for { - colorPicker() - } -} diff --git a/examples/event/main.go b/examples/event/main.go deleted file mode 100644 index 7c627f01..00000000 --- a/examples/event/main.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -package main - -import ( - "fmt" - - "github.com/go-vgo/robotgo" - // "go-vgo/robotgo" -) - -func addEvent() { - fmt.Println("--- Please press ctrl + shift + q ---") - ok := robotgo.AddEvents("q", "ctrl", "shift") - if ok { - fmt.Println("add events...") - } - - fmt.Println("--- Please press w---") - ok = robotgo.AddEvents("w") - if ok { - fmt.Println("add events") - } - - // start hook - s := robotgo.Start() - // end hook - defer robotgo.End() - - for ev := range s { - fmt.Println("hook: ", ev) - } -} - -func addMouse() { - fmt.Println("--- Please press left mouse button ---") - ok := robotgo.AddMouse("left") - if ok { - fmt.Println("add mouse...") - } - - fmt.Println("--- Please press left mouse button and move mosue to 100,100 ---") - ok = robotgo.AddMouse("left", 100, 100) - if ok { - fmt.Println("add mouse and move to 100,100 ...") - } - - fmt.Println("--- Please move mosue to 100,100 ---") - ok = robotgo.AddMousePos(100, 100) - if ok { - fmt.Println(" move mouse to 100,100 ...") - } -} - -func add() { - fmt.Println("--- Please press v---") - eve := robotgo.AddEvent("v") - - if eve { - fmt.Println("--- You press v---", "v") - } - - fmt.Println("--- Please press k---") - keve := robotgo.AddEvent("k") - if keve { - fmt.Println("--- You press k---", "k") - } - - fmt.Println("--- Please press f1---") - feve := robotgo.AddEvent("f1") - if feve { - fmt.Println("You press...", "f1") - } -} - -func event() { - //////////////////////////////////////////////////////////////////////////////// - // Global event listener - //////////////////////////////////////////////////////////////////////////////// - - add() - - fmt.Println("--- Please press left mouse button---") - mleft := robotgo.AddEvent("mleft") - if mleft { - fmt.Println("--- You press left mouse button---", "mleft") - } - - mright := robotgo.AddEvent("mright") - if mright { - fmt.Println("--- You press right mouse button---", "mright") - } - - // stop AddEvent - // robotgo.StopEvent() -} - -func main() { - fmt.Println("test begin...") - - addEvent() - - addMouse() - - event() -} diff --git a/examples/gohook/main.go b/examples/gohook/main.go deleted file mode 100644 index 31300b7f..00000000 --- a/examples/gohook/main.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 The cauefcr Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/cauefcr/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -package main - -import ( - "fmt" - - "github.com/go-vgo/robotgo" - hook "github.com/robotn/gohook" -) - -func addEvent() { - fmt.Println("--- Please press ctrl + shift + q to stop hook ---") - robotgo.EventHook(hook.KeyDown, []string{"q", "ctrl", "shift"}, func(e hook.Event) { - fmt.Println("ctrl-shift-q") - robotgo.EventEnd() - }) - - fmt.Println("--- Please press w---") - robotgo.EventHook(hook.KeyDown, []string{"w"}, func(e hook.Event) { - fmt.Println("w") - }) - - s := robotgo.EventStart() - <-robotgo.EventProcess(s) -} - -func addMouse() { - fmt.Println("--- Please press left mouse button to see it's position and the right mouse button to exit ---") - robotgo.EventHook(hook.MouseDown, []string{}, func(e hook.Event) { - if e.Button == hook.MouseMap["right"] { - fmt.Printf("mleft @ %v - %v\n", e.X, e.Y) - } else if e.Button == hook.MouseMap["left"] { - robotgo.EventEnd() - } - }) - - s := robotgo.EventStart() - <-robotgo.EventProcess(s) -} - -func lowLevel() { - //////////////////////////////////////////////////////////////////////////////// - // Global event listener - //////////////////////////////////////////////////////////////////////////////// - fmt.Println("Press q to stop event gathering") - evChan := robotgo.EventStart() - for e := range evChan { - fmt.Println(e) - if e.Keychar == 'q' { - robotgo.EventEnd() - // break - } - } -} - -func main() { - fmt.Println("test begin...") - addEvent() - - addMouse() - - lowLevel() -} diff --git a/examples/hook/main.go b/examples/hook/main.go deleted file mode 100644 index eddc31ca..00000000 --- a/examples/hook/main.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "fmt" - - hook "github.com/robotn/gohook" -) - -// hook listen and return values using detailed examples -func add() { - s := hook.Start() - defer hook.End() - - ct := false - for { - i := <-s - - if i.Kind == hook.KeyHold && i.Rawcode == 59 { - ct = true - } - - if ct && i.Rawcode == 12 { - break - } - } -} - -// base hook example -func base() { - evChan := hook.Start() - defer hook.End() - - for ev := range evChan { - fmt.Println("hook: ", ev) - } -} - -func main() { - base() - - add() -} diff --git a/examples/key/main.go b/examples/key/main.go index d4de1936..5967d58e 100644 --- a/examples/key/main.go +++ b/examples/key/main.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package main @@ -18,45 +18,49 @@ import ( ) func typeStr() { - // importing "Hello World" - robotgo.TypeStr("Hello World!", 1.0) - + // typing "Hello World" + robotgo.TypeStr("Hello World!", 0, 1) + robotgo.KeySleep = 100 robotgo.TypeStr("だんしゃり") - robotgo.MicroSleep(10.2) - robotgo.TypeStr("Hi galaxy. こんにちは世界.") - robotgo.Sleep(2) - // robotgo.TypeString("So, hi, bye!") + robotgo.TypeStr("Hi galaxy, hi stars, hi MT.Rainier, hi sea. こんにちは世界.") + robotgo.TypeStr("So, hi, bye! 你好, 再见!") + robotgo.Sleep(1) + + robotgo.TypeStr("Hi, Seattle space needle, Golden gate bridge, One world trade center.") robotgo.MilliSleep(100) ustr := uint32(robotgo.CharCodeAt("So, hi, bye!", 0)) robotgo.UnicodeType(ustr) - robotgo.PasteStr("paste string") + err := robotgo.PasteStr("paste string") + fmt.Println("PasteStr: ", err) } func keyTap() { // press "enter" robotgo.KeyTap("enter") + robotgo.KeyTap(robotgo.Enter) + robotgo.KeySleep = 200 robotgo.KeyTap("a") robotgo.MilliSleep(100) robotgo.KeyTap("a", "ctrl") // hide window err := robotgo.KeyTap("h", "cmd") - if err != "" { + if err != nil { fmt.Println("robotgo.KeyTap run error is: ", err) } - robotgo.KeyTap("h", "cmd", 12) + robotgo.KeyTap("h", "cmd") // press "i", "alt", "command" Key combination - robotgo.KeyTap("i", "alt", "command") - robotgo.KeyTap("i", "alt", "cmd", 11) + robotgo.KeyTap(robotgo.KeyI, robotgo.Alt, robotgo.Cmd) + robotgo.KeyTap("i", "alt", "cmd") arr := []string{"alt", "cmd"} robotgo.KeyTap("i", arr) - robotgo.KeyTap("i", arr, 12) + robotgo.KeyTap("i", arr) robotgo.KeyTap("i", "cmd", " alt", "shift") @@ -70,8 +74,17 @@ func keyTap() { robotgo.KeyTap("a", "control") } +func special() { + robotgo.TypeStr("{}") + robotgo.KeyTap("[", "]") + + robotgo.KeyToggle("(") + robotgo.KeyToggle("(", "up") +} + func keyToggle() { - robotgo.KeyToggle("a", "down") + // robotgo.KeySleep = 150 + robotgo.KeyToggle(robotgo.KeyA) robotgo.KeyToggle("a", "down", "alt") robotgo.Sleep(1) @@ -79,14 +92,14 @@ func keyToggle() { robotgo.MilliSleep(100) robotgo.KeyToggle("q", "up", "alt", "cmd", "shift") - err := robotgo.KeyToggle("enter", "down") - if err != "" { + err := robotgo.KeyToggle(robotgo.Enter) + if err != nil { fmt.Println("robotgo.KeyToggle run error is: ", err) } } func cilp() { - // robotgo.TypeString("en") + // robotgo.TypeStr("en") // write string to clipboard e := robotgo.WriteAll("テストする") @@ -99,7 +112,7 @@ func cilp() { if err != nil { fmt.Println("robotgo.ReadAll err is: ", err) } - fmt.Println(text) + fmt.Println("text: ", text) } func key() { @@ -108,6 +121,7 @@ func key() { //////////////////////////////////////////////////////////////////////////////// typeStr() + special() keyTap() keyToggle() diff --git a/examples/main.go b/examples/main.go index eade852a..343d9f5d 100644 --- a/examples/main.go +++ b/examples/main.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package main diff --git a/examples/mouse/main.go b/examples/mouse/main.go index e4ecfb12..7eb1e606 100644 --- a/examples/mouse/main.go +++ b/examples/mouse/main.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package main @@ -18,26 +18,26 @@ import ( ) func move() { + robotgo.MouseSleep = 100 robotgo.Move(100, 200) robotgo.MoveRelative(10, -200) // move the mouse to 100, 200 - robotgo.MoveMouse(100, 200) + robotgo.Move(100, 200) - robotgo.Drag(10, 10) - robotgo.Drag(20, 20, "right") - // + // drag mouse with smooth robotgo.DragSmooth(10, 10) robotgo.DragSmooth(100, 200, 1.0, 100.0) // smooth move the mouse to 100, 200 robotgo.MoveSmooth(100, 200) - robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) + robotgo.MoveSmooth(100, 200, 1.0, 100.0) robotgo.MoveSmoothRelative(10, -100, 1.0, 30.0) for i := 0; i < 1080; i += 1000 { - fmt.Println(i) - robotgo.MoveMouse(800, i) + fmt.Println("i: ", i) + // MoveMouse(800, i) + robotgo.Move(800, i) } } @@ -50,29 +50,34 @@ func click() { robotgo.Click("right", false) // double click the left mouse button - robotgo.MouseClick("left", true) + robotgo.Click("left", true) } func get() { // gets the mouse coordinates - x, y := robotgo.GetMousePos() + x, y := robotgo.Location() fmt.Println("pos:", x, y) if x == 456 && y == 586 { fmt.Println("mouse...", "586") } - robotgo.MoveMouse(x, y) + robotgo.Move(x, y) } func toggleAndScroll() { // scrolls the mouse either up - robotgo.ScrollMouse(10, "up") - robotgo.Scroll(100, 200) + robotgo.ScrollDir(10, "up") + robotgo.ScrollDir(10, "right") + + robotgo.Scroll(100, 10) + robotgo.Scroll(0, -10) - // toggles right mouse button - robotgo.MouseToggle("down", "right") + robotgo.Toggle("left") + robotgo.Toggle("left", "up") - robotgo.MouseToggle("up") + // toggles the right mouse button + robotgo.Toggle("right") + robotgo.Toggle("right", "up") } func mouse() { diff --git a/examples/scale/main.go b/examples/scale/main.go index cf822ffc..704c75b8 100644 --- a/examples/scale/main.go +++ b/examples/scale/main.go @@ -7,27 +7,44 @@ import ( ) func main() { - // // syscall.NewLazyDLL("user32.dll").NewProc("SetProcessDPIAware").Call() width, height := robotgo.GetScaleSize() fmt.Println("get scale screen size: ", width, height) bitmap := robotgo.CaptureScreen(0, 0, width, height) - robotgo.SaveBitmap(bitmap, "test.png") + defer robotgo.FreeBitmap(bitmap) + // bitmap.Save(bitmap, "test.png") + robotgo.Save(robotgo.ToImage(bitmap), "test.png") - sx := robotgo.ScaleX() - s := robotgo.Scale() + robotgo.Scale = true + robotgo.Move(10, 10) + robotgo.MoveSmooth(100, 100) + + fmt.Println(robotgo.Location()) + + num := robotgo.DisplaysNum() + for i := 0; i < num; i++ { + rect := robotgo.GetScreenRect(i) + fmt.Println("rect: ", rect) + } +} + +func old() { + sx := robotgo.ScaleX() // Deprecated + s := robotgo.Scale1() // Deprecated, use the ScaleF() function robotx, roboty := 35*s/100, 25*s/100 fmt.Println("scale: ", sx, s, " pos: ", robotx, roboty) - mx, my := robotgo.GetMousePos() + mx, my := robotgo.Location() sx, sy := mx*s/100, my*s/100 rx, ry, rw, rh := sx, sy, robotx, roboty // bit1 := robotgo.CaptureScreen(10, 20, robotw, roboth) bit1 := robotgo.CaptureScreen(rx, ry, rw, rh) - robotgo.SaveBitmap(bit1, "test2.png") + defer robotgo.FreeBitmap(bit1) + // bitmap.Save(bit1, "test2.png") + robotgo.Save(robotgo.ToImage(bit1), "test2.png") clo := robotgo.GetPixelColor(robotx, roboty) fmt.Println("GetPixelColor...", clo) diff --git a/examples/screen/main.go b/examples/screen/main.go index 123c4282..2d4be1dc 100644 --- a/examples/screen/main.go +++ b/examples/screen/main.go @@ -3,31 +3,56 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package main import ( "fmt" + "strconv" "github.com/go-vgo/robotgo" // "go-vgo/robotgo" ) func bitmap() { - abitMap := robotgo.CaptureScreen() - fmt.Println("abitMap...", abitMap) - gbit := robotgo.ToBitmap(abitMap) + bit := robotgo.CaptureScreen() + defer robotgo.FreeBitmap(bit) + fmt.Println("abitMap...", bit) + + gbit := robotgo.ToBitmap(bit) fmt.Println("bitmap...", gbit.Width) - gbitMap := robotgo.GoCaptureScreen() - fmt.Println("GoCaptureScreen...", gbitMap.Width) + gbitMap := robotgo.CaptureGo() + fmt.Println("Go CaptureScreen...", gbitMap.Width) // fmt.Println("...", gbitmap.Width, gbitmap.BytesPerPixel) - robotgo.SaveCapture("saveCapture.png", 10, 20, 100, 100) + + img, err := robotgo.CaptureImg() + fmt.Println("error: ", err) + robotgo.Save(img, "save.png") + + num := robotgo.DisplaysNum() + for i := 0; i < num; i++ { + robotgo.DisplayID = i + img1, _ := robotgo.CaptureImg() + path1 := "save_" + strconv.Itoa(i) + robotgo.Save(img1, path1+".png") + robotgo.SaveJpeg(img1, path1+".jpeg", 50) + + img2, _ := robotgo.CaptureImg(10, 10, 20, 20) + path2 := "test_" + strconv.Itoa(i) + robotgo.Save(img2, path2+".png") + robotgo.SaveJpeg(img2, path2+".jpeg", 50) + + x, y, w, h := robotgo.GetDisplayBounds(i) + img3, err := robotgo.CaptureImg(x, y, w, h) + fmt.Println("Capture error: ", err) + robotgo.Save(img3, path2+"_1.png") + } } func color() { @@ -63,7 +88,13 @@ func screen() { // gets the screen width and height sx, sy := robotgo.GetScreenSize() - fmt.Println("...", sx, sy) + fmt.Println("get screen size: ", sx, sy) + for i := 0; i < robotgo.DisplaysNum(); i++ { + s1 := robotgo.ScaleF(i) + fmt.Println("ScaleF: ", s1) + } + sx, sy = robotgo.GetScaleSize() + fmt.Println("get screen scale size: ", sx, sy) color() } diff --git a/examples/window/main.go b/examples/window/main.go index b9536292..fc3594d0 100644 --- a/examples/window/main.go +++ b/examples/window/main.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package main @@ -19,17 +19,16 @@ import ( func alert() { // show Alert Window - abool := robotgo.ShowAlert("hello", "robotgo") - if abool == 0 { + abool := robotgo.Alert("hello", "robotgo") + if abool { fmt.Println("ok@@@", "ok") } - robotgo.ShowAlert("hello", "robotgo", "Ok", "Cancel") - + robotgo.Alert("hello", "robotgo", "Ok", "Cancel") } func get() { // get the current process id - pid := robotgo.GetPID() + pid := robotgo.GetPid() fmt.Println("pid----", pid) // get current Window Active @@ -39,10 +38,6 @@ func get() { hwnd := robotgo.GetHandle() fmt.Println("hwnd---", hwnd) - // get current Window Handle - bhwnd := robotgo.GetBHandle() - fmt.Println("bhwnd---", bhwnd) - // get current Window title title := robotgo.GetTitle() fmt.Println("title-----", title) @@ -54,31 +49,45 @@ func get() { func findIds() { // find the process id by the process name fpid, err := robotgo.FindIds("Google") - if err == nil { - fmt.Println("pids...", fpid) - if len(fpid) > 0 { - robotgo.ActivePID(fpid[0]) - - tl := robotgo.GetTitle(fpid[0]) - fmt.Println("pid[0] title is: ", tl) + if err != nil { + fmt.Println(err) + return + } - x, y, w, h := robotgo.GetBounds(fpid[0]) - fmt.Println("GetBounds is: ", x, y, w, h) + if len(fpid) > 0 { + robotgo.KeyTap("a", fpid[0]) + robotgo.TypeStr("Hi galaxy!", fpid[0]) - // Windows - // hwnd := robotgo.FindWindow("google") - // hwnd := robotgo.GetHWND() - robotgo.MinWindow(fpid[0]) - robotgo.MaxWindow(fpid[0]) - robotgo.CloseWindow(fpid[0]) + robotgo.KeyToggle("a", fpid[0], "cmd") + robotgo.KeyToggle("a", fpid[0], "cmd", "up") + } - robotgo.Kill(fpid[0]) + fmt.Println("pids...", fpid) + if len(fpid) > 0 { + err = robotgo.ActivePid(fpid[0]) + if err != nil { + fmt.Println(err) } + + tl := robotgo.GetTitle(fpid[0]) + fmt.Println("pid[0] title is: ", tl) + + x, y, w, h := robotgo.GetBounds(fpid[0]) + fmt.Println("GetBounds is: ", x, y, w, h) + + // Windows + // hwnd := robotgo.FindWindow("google") + // hwnd := robotgo.GetHWND() + robotgo.MinWindow(fpid[0]) + robotgo.MaxWindow(fpid[0]) + robotgo.CloseWindow(fpid[0]) + + robotgo.Kill(fpid[0]) } } func active() { - robotgo.ActivePID(100) + robotgo.ActivePid(100) // robotgo.Sleep(2) robotgo.ActiveName("code") robotgo.Sleep(1) diff --git a/go.mod b/go.mod index 6b5b788f..40fb4a17 100644 --- a/go.mod +++ b/go.mod @@ -1,21 +1,40 @@ module github.com/go-vgo/robotgo +go 1.23.0 + +toolchain go1.23.6 + +require ( + github.com/otiai10/gosseract/v2 v2.4.1 + // github.com/robotn/gohook v0.31.3 + github.com/robotn/xgb v0.10.0 + github.com/robotn/xgbutil v0.10.0 + github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35 + github.com/vcaesar/gops v0.41.0 + github.com/vcaesar/imgo v0.41.0 + github.com/vcaesar/keycode v0.10.1 + github.com/vcaesar/tt v0.20.1 +) + require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/lxn/win v0.0.0-20191128105842-2da648fda5b4 - github.com/otiai10/curr v1.0.0 // indirect - github.com/otiai10/gosseract v2.2.1+incompatible - github.com/robotn/gohook v0.30.2 - github.com/robotn/xgb v0.0.0-20190912153532-2cb92d044934 - github.com/robotn/xgbutil v0.0.0-20190912154524-c861d6f87770 - github.com/vcaesar/gops v0.10.0 - github.com/vcaesar/imgo v0.10.0 - github.com/vcaesar/tt v0.10.0 - golang.org/x/image v0.0.0-20200430140353-33d19683fad8 - golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 // indirect - golang.org/x/sys v0.0.0-20200523222454-059865788121 // indirect + github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e // indirect + github.com/ebitengine/purego v0.8.3 // indirect + github.com/gen2brain/shm v0.1.1 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/jezek/xgb v1.1.1 // indirect + github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect + github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/shirou/gopsutil/v4 v4.25.4 // indirect + github.com/tklauser/go-sysconf v0.3.15 // indirect + github.com/tklauser/numcpus v0.10.0 // indirect + github.com/vcaesar/screenshot v0.11.1 + github.com/yusufpapurcu/wmi v1.2.4 // indirect + golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // indirect + golang.org/x/image v0.27.0 // indirect + golang.org/x/sys v0.33.0 // indirect ) // replace golang.org/x/sys => github.com/golang/sys v0.0.0-20190109145017-48ac38b7c8cb -go 1.13 +// go 1.13 diff --git a/go.sum b/go.sum index f0e03695..77e32a58 100644 --- a/go.sum +++ b/go.sum @@ -1,60 +1,71 @@ github.com/BurntSushi/freetype-go v0.0.0-20160129220410-b763ddbfe298/go.mod h1:D+QujdIlUNfa0igpNMk6UIvlb6C252URs4yupRUV4lQ= github.com/BurntSushi/graphics-go v0.0.0-20160129215708-b43f31a4a966/go.mod h1:Mid70uvE93zn9wgF92A/r5ixgnvX8Lh68fxp9KQBaI0= -github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= -github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI= -github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= -github.com/lxn/win v0.0.0-20191128105842-2da648fda5b4 h1:5BmtGkQbch91lglMHQ9JIDGiYCL3kBRBA0ItZTvOcEI= -github.com/lxn/win v0.0.0-20191128105842-2da648fda5b4/go.mod h1:ouWl4wViUNh8tPSIwxTVMuS014WakR1hqvBc2I0bMoA= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95 h1:+OLn68pqasWca0z5ryit9KGfp3sUsW4Lqg32iRMJyzs= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI= -github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= -github.com/otiai10/gosseract v2.2.1+incompatible h1:Ry5ltVdpdp4LAa2bMjsSJH34XHVOV7XMi41HtzL8X2I= -github.com/otiai10/gosseract v2.2.1+incompatible/go.mod h1:XrzWItCzCpFRZ35n3YtVTgq5bLAhFIkascoRo8G32QE= -github.com/otiai10/mint v1.3.0 h1:Ady6MKVezQwHBkGzLFbrsywyp09Ah7rkmfjV3Bcr5uc= -github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e h1:L+XrFvD0vBIBm+Wf9sFN6aU395t7JROoai0qXZraA4U= +github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e/go.mod h1:SUxUaAK/0UG5lYyZR1L1nC4AaYYvSSYTWQSH3FPcxKU= +github.com/ebitengine/purego v0.8.3 h1:K+0AjQp63JEZTEMZiwsI9g0+hAMNohwUOtY0RPGexmc= +github.com/ebitengine/purego v0.8.3/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/gen2brain/shm v0.1.1 h1:1cTVA5qcsUFixnDHl14TmRoxgfWEEZlTezpUj1vm5uQ= +github.com/gen2brain/shm v0.1.1/go.mod h1:UgIcVtvmOu+aCJpqJX7GOtiN7X2ct+TKLg4RTxwPIUA= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/jezek/xgb v1.1.1 h1:bE/r8ZZtSv7l9gk6nU0mYx51aXrvnyb44892TwSaqS4= +github.com/jezek/xgb v1.1.1/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk= +github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc= +github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= +github.com/otiai10/gosseract/v2 v2.4.1 h1:G8AyBpXEeSlcq8TI85LH/pM5SXk8Djy2GEXisgyblRw= +github.com/otiai10/gosseract/v2 v2.4.1/go.mod h1:1gNWP4Hgr2o7yqWfs6r5bZxAatjOIdqWxJLWsTsembk= +github.com/otiai10/mint v1.6.3 h1:87qsV/aw1F5as1eH1zS/yqHY85ANKVMgkDrf9rcxbQs= +github.com/otiai10/mint v1.6.3/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/robotn/gohook v0.30.2 h1:PbG/N24ycg3lEfl6+UpGumC/jnuHL9gJCy2jMGbQKhA= -github.com/robotn/gohook v0.30.2/go.mod h1:cWEhn477y4+4/D1SXIDPhivGSNsZT4dcco3uLTVBa6g= -github.com/robotn/xgb v0.0.0-20190912153532-2cb92d044934 h1:2lhSR8N3T6I30q096DT7/5AKEIcf1vvnnWAmS0wfnNY= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/robotn/xgb v0.0.0-20190912153532-2cb92d044934/go.mod h1:SxQhJskUJ4rleVU44YvnrdvxQr0tKy5SRSigBrCgyyQ= -github.com/robotn/xgbutil v0.0.0-20190912154524-c861d6f87770 h1:2uX8QRLkkxn2EpAQ6I3KhA79BkdRZfvugJUzJadiJwk= -github.com/robotn/xgbutil v0.0.0-20190912154524-c861d6f87770/go.mod h1:svkDXUDQjUiWzLrA0OZgHc4lbOts3C+uRfP6/yjwYnU= -github.com/shirou/gopsutil v2.19.11+incompatible h1:lJHR0foqAjI4exXqWsU3DbH7bX1xvdhGdnXTIARA9W4= -github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= -github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4 h1:udFKJ0aHUL60LboW/A+DfgoHVedieIzIXE8uylPue0U= -github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4/go.mod h1:qsXQc7+bwAM3Q1u/4XEfrquwF8Lw7D7y5cD8CuHnfIc= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/vcaesar/gops v0.10.0 h1:pVIwPfHNKdkHBFyMQu5x5patIPGE+R8kd3+4BIEU7sU= -github.com/vcaesar/gops v0.10.0/go.mod h1:HDKiKqHeRYwEhBUTjgBHWT/PkwvLusticopFNbGO/eY= -github.com/vcaesar/imgo v0.10.0 h1:6TOWsQFHdxIq7UVijeKBnhOymO+lDuRJwuP7VhSeR9U= -github.com/vcaesar/imgo v0.10.0/go.mod h1:52+3yYrTNjWKh+CkQozNRCLWCE/X666yAWPGbYC3DZI= -github.com/vcaesar/tt v0.10.0 h1:jPtFiRRnCOXVakd5ujCed2dwWwTs91wh8W1iHeUIfc0= -github.com/vcaesar/tt v0.10.0/go.mod h1:GHPxQYhn+7OgKakRusH7KJ0M5MhywoeLb8Fcffs/Gtg= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a h1:gHevYm0pO4QUbwy8Dmdr01R5r1BuKtfYqRqF0h/Cbh0= -golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/image v0.0.0-20200430140353-33d19683fad8 h1:6WW6V3x1P/jokJBpRQYUJnMHRP6isStQwCozxnU7XQw= -golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 h1:AeiKBIuRw3UomYXSbLy0Mc2dDLfdtbT/IVn4keq83P0= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1 h1:gZpLHxUX5BdYLA08Lj4YCJNN/jk7KtquiArPoeX0WvA= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +github.com/robotn/xgb v0.10.0 h1:O3kFbIwtwZ3pgLbp1h5slCQ4OpY8BdwugJLrUe6GPIM= +github.com/robotn/xgb v0.10.0/go.mod h1:SxQhJskUJ4rleVU44YvnrdvxQr0tKy5SRSigBrCgyyQ= +github.com/robotn/xgbutil v0.10.0 h1:gvf7mGQqCWQ68aHRtCxgdewRk+/KAJui6l3MJQQRCKw= +github.com/robotn/xgbutil v0.10.0/go.mod h1:svkDXUDQjUiWzLrA0OZgHc4lbOts3C+uRfP6/yjwYnU= +github.com/shirou/gopsutil/v4 v4.25.4 h1:cdtFO363VEOOFrUCjZRh4XVJkb548lyF0q0uTeMqYPw= +github.com/shirou/gopsutil/v4 v4.25.4/go.mod h1:xbuxyoZj+UsgnZrENu3lQivsngRR5BdjbJwf2fv4szA= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35 h1:wAZbkTZkqDzWsqxPh2qkBd3KvFU7tcxV0BP0Rnhkxog= +github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35/go.mod h1:aMd4yDHLjbOuYP6fMxj1d9ACDQlSWwYztcpybGHCQc8= +github.com/tc-hib/winres v0.2.1 h1:YDE0FiP0VmtRaDn7+aaChp1KiF4owBiJa5l964l5ujA= +github.com/tc-hib/winres v0.2.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk= +github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4= +github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4= +github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso= +github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ= +github.com/vcaesar/gops v0.41.0 h1:FG748Jyw3FOuZnbzSgB+CQSx2e5LbLCPWV2JU1brFdc= +github.com/vcaesar/gops v0.41.0/go.mod h1:/3048L7Rj7QjQKTSB+kKc7hDm63YhTWy5QJ10TCP37A= +github.com/vcaesar/imgo v0.41.0 h1:kNLYGrThXhB9Dd6IwFmfPnxq9P6yat2g7dpPjr7OWO8= +github.com/vcaesar/imgo v0.41.0/go.mod h1:/LGOge8etlzaVu/7l+UfhJxR6QqaoX5yeuzGIMfWb4I= +github.com/vcaesar/keycode v0.10.1 h1:0DesGmMAPWpYTCYddOFiCMKCDKgNnwiQa2QXindVUHw= +github.com/vcaesar/keycode v0.10.1/go.mod h1:JNlY7xbKsh+LAGfY2j4M3znVrGEm5W1R8s/Uv6BJcfQ= +github.com/vcaesar/screenshot v0.11.1 h1:GgPuN89XC4Yh38dLx4quPlSo3YiWWhwIria/j3LtrqU= +github.com/vcaesar/screenshot v0.11.1/go.mod h1:gJNwHBiP1v1v7i8TQ4yV1XJtcyn2I/OJL7OziVQkwjs= +github.com/vcaesar/tt v0.20.1 h1:D/jUeeVCNbq3ad8M7hhtB3J9x5RZ6I1n1eZ0BJp7M+4= +github.com/vcaesar/tt v0.20.1/go.mod h1:cH2+AwGAJm19Wa6xvEa+0r+sXDJBT0QgNQey6mwqLeU= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ/GnQx2BE33L8BOHQkI= +golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ= +golang.org/x/image v0.27.0 h1:C8gA4oWU/tKkdCfYT6T2u4faJu3MeNS5O8UPWlPF61w= +golang.org/x/image v0.27.0/go.mod h1:xbdrClrAUway1MUTEZDq9mz/UpRwYAkFFNUslZtcB+g= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/hook.go b/hook.go deleted file mode 100644 index 731f9c05..00000000 --- a/hook.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -package robotgo - -import ( - "strconv" - - hook "github.com/robotn/gohook" -) - -/* - ___________ ____ _______ .__ __. .___________. -| ____\ \ / / | ____|| \ | | | | -| |__ \ \/ / | |__ | \| | `---| |----` -| __| \ / | __| | . ` | | | -| |____ \ / | |____ | |\ | | | -|_______| \__/ |_______||__| \__| |__| -*/ - -// EventStart start global event hook -// return event channel -func EventStart() chan hook.Event { - return hook.Start() -} - -// EventEnd removes global event hook -func EventEnd() { - hook.End() -} - -// EventProcess return go hook process -func EventProcess(Events chan hook.Event) chan bool { - return hook.Process(Events) -} - -// EventHook register gohook event -func EventHook(When uint8, keysPressed []string, Callback func(hook.Event)) { - hook.Register(When, keysPressed, Callback) - return -} - -// AddEvent add event listener, -// -// parameters for the string type, -// the keyboard corresponding key parameters, -// -// mouse arguments: mleft, center, mright, wheelDown, wheelUp, -// wheelLeft, wheelRight. -// -// Use "robotgo.AddEvents()" or "gohook" add asynchronous event listener -func AddEvent(key string) bool { - var ( - // cs *C.char - mArr = []string{"mleft", "center", "mright", "wheelDown", - "wheelUp", "wheelLeft", "wheelRight"} - mouseBool bool - ) - - for i := 0; i < len(mArr); i++ { - if key == mArr[i] { - mouseBool = true - } - } - - if len(key) > 1 && !mouseBool { - key = strconv.Itoa(int(Keycode[key])) - } - - geve := hook.AddEvent(key) - // defer C.free(unsafe.Pointer(cs)) - - if geve == 0 { - return true - } - - return false -} - -// StopEvent stop event listener -func StopEvent() { - hook.StopEvent() -} - -// Start start global event hook -// return event channel -func Start() chan hook.Event { - return hook.Start() -} - -// End removes global event hook -func End() { - hook.End() -} - -// AddEvents add global event hook -// -// robotgo.AddEvents("q") -// robotgo.AddEvents("q", "ctrl") -// robotgo.AddEvents("q", "ctrl", "shift") -func AddEvents(key string, arr ...string) bool { - s := hook.Start() - // defer hook.End() - - ct := false - k := 0 - for { - e := <-s - - l := len(arr) - if l > 0 { - for i := 0; i < l; i++ { - ukey := Keycode[arr[i]] - - if e.Kind == hook.KeyHold && e.Keycode == ukey { - k++ - } - - if k == l { - ct = true - } - - if e.Kind == hook.KeyUp && e.Keycode == ukey { - if k > 0 { - k-- - } - // time.Sleep(10 * time.Microsecond) - ct = false - } - } - } else { - ct = true - } - - if ct && e.Kind == hook.KeyUp && e.Keycode == Keycode[key] { - hook.End() - // k = 0 - break - } - } - - return true -} - -// AddMouse add mouse event hook -// -// mouse arguments: left, center, right, wheelDown, wheelUp, -// wheelLeft, wheelRight. -// -// robotgo.AddMouse("left") -// robotgo.AddMouse("left", 100, 100) -func AddMouse(btn string, x ...int16) bool { - s := hook.Start() - ukey := MouseMap[btn] - - ct := false - for { - e := <-s - - if len(x) > 1 { - if e.Kind == hook.MouseMove && e.X == x[0] && e.Y == x[1] { - ct = true - } - } else { - ct = true - } - - if ct && e.Kind == hook.MouseDown && e.Button == ukey { - hook.End() - break - } - } - - return true -} - -// AddMousePos add listen mouse event pos hook -func AddMousePos(x, y int16) bool { - s := hook.Start() - - for { - e := <-s - if e.Kind == hook.MouseMove && e.X == x && e.Y == y { - hook.End() - break - } - } - - return true -} diff --git a/img.go b/img.go new file mode 100644 index 00000000..0e8d32cd --- /dev/null +++ b/img.go @@ -0,0 +1,181 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package robotgo + +import ( + "image" + "os/exec" + "unsafe" + + "github.com/vcaesar/imgo" +) + +// DecodeImg decode the image to image.Image and return +func DecodeImg(path string) (image.Image, string, error) { + return imgo.DecodeFile(path) +} + +// OpenImg open the image return []byte +func OpenImg(path string) ([]byte, error) { + return imgo.ImgToBytes(path) +} + +// Read read the file return image.Image +func Read(path string) (image.Image, error) { + return imgo.Read(path) +} + +// Save create a image file with the image.Image +func Save(img image.Image, path string, quality ...int) error { + return imgo.Save(path, img, quality...) +} + +// SaveImg save the image by []byte +func SaveImg(b []byte, path string) error { + return imgo.SaveByte(path, b) +} + +// SavePng save the image by image.Image +func SavePng(img image.Image, path string) error { + return imgo.SaveToPNG(path, img) +} + +// SaveJpeg save the image by image.Image +func SaveJpeg(img image.Image, path string, quality ...int) error { + return imgo.SaveToJpeg(path, img, quality...) +} + +// ToByteImg convert image.Image to []byte +func ToByteImg(img image.Image, fm ...string) []byte { + return imgo.ToByte(img, fm...) +} + +// ToStringImg convert image.Image to string +func ToStringImg(img image.Image, fm ...string) string { + return string(ToByteImg(img, fm...)) +} + +// StrToImg convert base64 string to image.Image +func StrToImg(data string) (image.Image, error) { + return imgo.StrToImg(data) +} + +// ByteToImg convert []byte to image.Image +func ByteToImg(b []byte) (image.Image, error) { + return imgo.ByteToImg(b) +} + +// ImgSize get the file image size +func ImgSize(path string) (int, int, error) { + return imgo.GetSize(path) +} + +// Width return the image.Image width +func Width(img image.Image) int { + return img.Bounds().Max.X +} + +// Height return the image.Image height +func Height(img image.Image) int { + return img.Bounds().Max.Y +} + +// RGBAToBitmap convert the standard image.RGBA to Bitmap +func RGBAToBitmap(r1 *image.RGBA) (bit Bitmap) { + bit.Width = r1.Bounds().Size().X + bit.Height = r1.Bounds().Size().Y + bit.Bytewidth = r1.Stride + + src := ToUint8p(r1.Pix) + bit.ImgBuf = src + + bit.BitsPixel = 32 + bit.BytesPerPixel = 32 / 8 + + return +} + +// ImgToBitmap convert the standard image.Image to Bitmap +func ImgToBitmap(m image.Image) (bit Bitmap) { + bit.Width = m.Bounds().Size().X + bit.Height = m.Bounds().Size().Y + + pix, stride, _ := imgo.EncodeImg(m) + bit.Bytewidth = stride + + src := ToUint8p(pix) + bit.ImgBuf = src + // + bit.BitsPixel = 32 + bit.BytesPerPixel = 32 / 8 + return +} + +// ToUint8p convert the []uint8 to uint8 pointer +func ToUint8p(dst []uint8) *uint8 { + src := make([]uint8, len(dst)+10) + for i := 0; i <= len(dst)-4; i += 4 { + src[i+3] = dst[i+3] + src[i] = dst[i+2] + src[i+1] = dst[i+1] + src[i+2] = dst[i] + } + + ptr := unsafe.Pointer(&src[0]) + return (*uint8)(ptr) +} + +// ToRGBAGo convert Bitmap to standard image.RGBA +func ToRGBAGo(bmp1 Bitmap) *image.RGBA { + img1 := image.NewRGBA(image.Rect(0, 0, bmp1.Width, bmp1.Height)) + img1.Pix = make([]uint8, bmp1.Bytewidth*bmp1.Height) + + copyToVUint8A(img1.Pix, bmp1.ImgBuf) + img1.Stride = bmp1.Bytewidth + return img1 +} + +func val(p *uint8, n int) uint8 { + addr := uintptr(unsafe.Pointer(p)) + addr += uintptr(n) + p1 := (*uint8)(unsafe.Pointer(addr)) + return *p1 +} + +func copyToVUint8A(dst []uint8, src *uint8) { + for i := 0; i <= len(dst)-4; i += 4 { + dst[i] = val(src, i+2) + dst[i+1] = val(src, i+1) + dst[i+2] = val(src, i) + dst[i+3] = val(src, i+3) + } +} + +// GetText get the image text by tesseract ocr +// +// robotgo.GetText(imgPath, lang string) +func GetText(imgPath string, args ...string) (string, error) { + var lang = "eng" + + if len(args) > 0 { + lang = args[0] + if lang == "zh" { + lang = "chi_sim" + } + } + + body, err := exec.Command("tesseract", imgPath, + "stdout", "-l", lang).Output() + if err != nil { + return "", err + } + return string(body), nil +} diff --git a/key.go b/key.go new file mode 100644 index 00000000..14b1cd29 --- /dev/null +++ b/key.go @@ -0,0 +1,742 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package robotgo + +/* +// #include "key/keycode.h" +#include "key/keypress_c.h" +*/ +import "C" + +import ( + "errors" + "math/rand" + "reflect" + "runtime" + "strconv" + "strings" + "unicode" + "unsafe" + + "github.com/go-vgo/robotgo/clipboard" +) + +// Defining a bunch of constants. +const ( + // KeyA define key "a" + KeyA = "a" + KeyB = "b" + KeyC = "c" + KeyD = "d" + KeyE = "e" + KeyF = "f" + KeyG = "g" + KeyH = "h" + KeyI = "i" + KeyJ = "j" + KeyK = "k" + KeyL = "l" + KeyM = "m" + KeyN = "n" + KeyO = "o" + KeyP = "p" + KeyQ = "q" + KeyR = "r" + KeyS = "s" + KeyT = "t" + KeyU = "u" + KeyV = "v" + KeyW = "w" + KeyX = "x" + KeyY = "y" + KeyZ = "z" + // + CapA = "A" + CapB = "B" + CapC = "C" + CapD = "D" + CapE = "E" + CapF = "F" + CapG = "G" + CapH = "H" + CapI = "I" + CapJ = "J" + CapK = "K" + CapL = "L" + CapM = "M" + CapN = "N" + CapO = "O" + CapP = "P" + CapQ = "Q" + CapR = "R" + CapS = "S" + CapT = "T" + CapU = "U" + CapV = "V" + CapW = "W" + CapX = "X" + CapY = "Y" + CapZ = "Z" + // + Key0 = "0" + Key1 = "1" + Key2 = "2" + Key3 = "3" + Key4 = "4" + Key5 = "5" + Key6 = "6" + Key7 = "7" + Key8 = "8" + Key9 = "9" + + // Backspace backspace key string + Backspace = "backspace" + Delete = "delete" + Enter = "enter" + Tab = "tab" + Esc = "esc" + Escape = "escape" + Up = "up" // Up arrow key + Down = "down" // Down arrow key + Right = "right" // Right arrow key + Left = "left" // Left arrow key + Home = "home" + End = "end" + Pageup = "pageup" + Pagedown = "pagedown" + + F1 = "f1" + F2 = "f2" + F3 = "f3" + F4 = "f4" + F5 = "f5" + F6 = "f6" + F7 = "f7" + F8 = "f8" + F9 = "f9" + F10 = "f10" + F11 = "f11" + F12 = "f12" + F13 = "f13" + F14 = "f14" + F15 = "f15" + F16 = "f16" + F17 = "f17" + F18 = "f18" + F19 = "f19" + F20 = "f20" + F21 = "f21" + F22 = "f22" + F23 = "f23" + F24 = "f24" + + Cmd = "cmd" // is the "win" key for windows + Lcmd = "lcmd" // left command + Rcmd = "rcmd" // right command + // "command" + Alt = "alt" + Lalt = "lalt" // left alt + Ralt = "ralt" // right alt + Ctrl = "ctrl" + Lctrl = "lctrl" // left ctrl + Rctrl = "rctrl" // right ctrl + Control = "control" + Shift = "shift" + Lshift = "lshift" // left shift + Rshift = "rshift" // right shift + // "right_shift" + Capslock = "capslock" + Space = "space" + Print = "print" + Printscreen = "printscreen" // No Mac support + Insert = "insert" + Menu = "menu" // Windows only + + AudioMute = "audio_mute" // Mute the volume + AudioVolDown = "audio_vol_down" // Lower the volume + AudioVolUp = "audio_vol_up" // Increase the volume + AudioPlay = "audio_play" + AudioStop = "audio_stop" + AudioPause = "audio_pause" + AudioPrev = "audio_prev" // Previous Track + AudioNext = "audio_next" // Next Track + AudioRewind = "audio_rewind" // Linux only + AudioForward = "audio_forward" // Linux only + AudioRepeat = "audio_repeat" // Linux only + AudioRandom = "audio_random" // Linux only + + Num0 = "num0" // numpad 0 + Num1 = "num1" + Num2 = "num2" + Num3 = "num3" + Num4 = "num4" + Num5 = "num5" + Num6 = "num6" + Num7 = "num7" + Num8 = "num8" + Num9 = "num9" + NumLock = "num_lock" + + NumDecimal = "num." + NumPlus = "num+" + NumMinus = "num-" + NumMul = "num*" + NumDiv = "num/" + NumClear = "num_clear" + NumEnter = "num_enter" + NumEqual = "num_equal" + + LightsMonUp = "lights_mon_up" // Turn up monitor brightness No Windows support + LightsMonDown = "lights_mon_down" // Turn down monitor brightness No Windows support + LightsKbdToggle = "lights_kbd_toggle" // Toggle keyboard backlight on/off No Windows support + LightsKbdUp = "lights_kbd_up" // Turn up keyboard backlight brightness No Windows support + LightsKbdDown = "lights_kbd_down" +) + +// keyNames define a map of key names to MMKeyCode +var keyNames = map[string]C.MMKeyCode{ + "backspace": C.K_BACKSPACE, + "delete": C.K_DELETE, + "enter": C.K_RETURN, + "tab": C.K_TAB, + "esc": C.K_ESCAPE, + "escape": C.K_ESCAPE, + "up": C.K_UP, + "down": C.K_DOWN, + "right": C.K_RIGHT, + "left": C.K_LEFT, + "home": C.K_HOME, + "end": C.K_END, + "pageup": C.K_PAGEUP, + "pagedown": C.K_PAGEDOWN, + // + "f1": C.K_F1, + "f2": C.K_F2, + "f3": C.K_F3, + "f4": C.K_F4, + "f5": C.K_F5, + "f6": C.K_F6, + "f7": C.K_F7, + "f8": C.K_F8, + "f9": C.K_F9, + "f10": C.K_F10, + "f11": C.K_F11, + "f12": C.K_F12, + "f13": C.K_F13, + "f14": C.K_F14, + "f15": C.K_F15, + "f16": C.K_F16, + "f17": C.K_F17, + "f18": C.K_F18, + "f19": C.K_F19, + "f20": C.K_F20, + "f21": C.K_F21, + "f22": C.K_F22, + "f23": C.K_F23, + "f24": C.K_F24, + // + "cmd": C.K_META, + "lcmd": C.K_LMETA, + "rcmd": C.K_RMETA, + "command": C.K_META, + "alt": C.K_ALT, + "lalt": C.K_LALT, + "ralt": C.K_RALT, + "ctrl": C.K_CONTROL, + "lctrl": C.K_LCONTROL, + "rctrl": C.K_RCONTROL, + "control": C.K_CONTROL, + "shift": C.K_SHIFT, + "lshift": C.K_LSHIFT, + "rshift": C.K_RSHIFT, + "right_shift": C.K_RSHIFT, + "capslock": C.K_CAPSLOCK, + "space": C.K_SPACE, + "print": C.K_PRINTSCREEN, + "printscreen": C.K_PRINTSCREEN, + "insert": C.K_INSERT, + "menu": C.K_MENU, + + "audio_mute": C.K_AUDIO_VOLUME_MUTE, + "audio_vol_down": C.K_AUDIO_VOLUME_DOWN, + "audio_vol_up": C.K_AUDIO_VOLUME_UP, + "audio_play": C.K_AUDIO_PLAY, + "audio_stop": C.K_AUDIO_STOP, + "audio_pause": C.K_AUDIO_PAUSE, + "audio_prev": C.K_AUDIO_PREV, + "audio_next": C.K_AUDIO_NEXT, + "audio_rewind": C.K_AUDIO_REWIND, + "audio_forward": C.K_AUDIO_FORWARD, + "audio_repeat": C.K_AUDIO_REPEAT, + "audio_random": C.K_AUDIO_RANDOM, + + "num0": C.K_NUMPAD_0, + "num1": C.K_NUMPAD_1, + "num2": C.K_NUMPAD_2, + "num3": C.K_NUMPAD_3, + "num4": C.K_NUMPAD_4, + "num5": C.K_NUMPAD_5, + "num6": C.K_NUMPAD_6, + "num7": C.K_NUMPAD_7, + "num8": C.K_NUMPAD_8, + "num9": C.K_NUMPAD_9, + "num_lock": C.K_NUMPAD_LOCK, + + // todo: removed + "numpad_0": C.K_NUMPAD_0, + "numpad_1": C.K_NUMPAD_1, + "numpad_2": C.K_NUMPAD_2, + "numpad_3": C.K_NUMPAD_3, + "numpad_4": C.K_NUMPAD_4, + "numpad_5": C.K_NUMPAD_5, + "numpad_6": C.K_NUMPAD_6, + "numpad_7": C.K_NUMPAD_7, + "numpad_8": C.K_NUMPAD_8, + "numpad_9": C.K_NUMPAD_9, + "numpad_lock": C.K_NUMPAD_LOCK, + + "num.": C.K_NUMPAD_DECIMAL, + "num+": C.K_NUMPAD_PLUS, + "num-": C.K_NUMPAD_MINUS, + "num*": C.K_NUMPAD_MUL, + "num/": C.K_NUMPAD_DIV, + "num_clear": C.K_NUMPAD_CLEAR, + "num_enter": C.K_NUMPAD_ENTER, + "num_equal": C.K_NUMPAD_EQUAL, + + "lights_mon_up": C.K_LIGHTS_MON_UP, + "lights_mon_down": C.K_LIGHTS_MON_DOWN, + "lights_kbd_toggle": C.K_LIGHTS_KBD_TOGGLE, + "lights_kbd_up": C.K_LIGHTS_KBD_UP, + "lights_kbd_down": C.K_LIGHTS_KBD_DOWN, + + // { NULL: C.K_NOT_A_KEY } +} + +// CmdCtrl If the operating system is macOS, return the key string "cmd", +// otherwise return the key string "ctrl +func CmdCtrl() string { + if runtime.GOOS == "darwin" { + return "cmd" + } + return "ctrl" +} + +// It sends a key press and release to the active application +func tapKeyCode(code C.MMKeyCode, flags C.MMKeyFlags, pid C.uintptr) { + C.toggleKeyCode(code, true, flags, pid) + MilliSleep(3) + C.toggleKeyCode(code, false, flags, pid) +} + +var keyErr = errors.New("Invalid key flag specified.") + +func checkKeyCodes(k string) (key C.MMKeyCode, err error) { + if k == "" { + return + } + + if len(k) == 1 { + val1 := C.CString(k) + defer C.free(unsafe.Pointer(val1)) + + key = C.keyCodeForChar(*val1) + if key == C.K_NOT_A_KEY { + err = keyErr + return + } + return + } + + if v, ok := keyNames[k]; ok { + key = v + if key == C.K_NOT_A_KEY { + err = keyErr + return + } + } + return +} + +func checkKeyFlags(f string) (flags C.MMKeyFlags) { + m := map[string]C.MMKeyFlags{ + "alt": C.MOD_ALT, + "ralt": C.MOD_ALT, + "lalt": C.MOD_ALT, + "cmd": C.MOD_META, + "rcmd": C.MOD_META, + "lcmd": C.MOD_META, + "ctrl": C.MOD_CONTROL, + "rctrl": C.MOD_CONTROL, + "lctrl": C.MOD_CONTROL, + "shift": C.MOD_SHIFT, + "rshift": C.MOD_SHIFT, + "lshift": C.MOD_SHIFT, + "none": C.MOD_NONE, + } + + if v, ok := m[f]; ok { + return v + } + return +} + +func getFlagsFromValue(value []string) (flags C.MMKeyFlags) { + if len(value) <= 0 { + return + } + + for i := 0; i < len(value); i++ { + var f C.MMKeyFlags = C.MOD_NONE + + f = checkKeyFlags(value[i]) + flags = (C.MMKeyFlags)(flags | f) + } + + return +} + +func keyTaps(k string, keyArr []string, pid int) error { + flags := getFlagsFromValue(keyArr) + key, err := checkKeyCodes(k) + if err != nil { + return err + } + + tapKeyCode(key, flags, C.uintptr(pid)) + MilliSleep(KeySleep) + return nil +} + +func getKeyDown(keyArr []string) (bool, []string) { + if len(keyArr) <= 0 { + keyArr = append(keyArr, "down") + } + + down := true + if keyArr[0] == "up" { + down = false + } + + if keyArr[0] == "up" || keyArr[0] == "down" { + keyArr = keyArr[1:] + } + return down, keyArr +} + +func keyTogglesB(k string, down bool, keyArr []string, pid int) error { + flags := getFlagsFromValue(keyArr) + key, err := checkKeyCodes(k) + if err != nil { + return err + } + + C.toggleKeyCode(key, C.bool(down), flags, C.uintptr(pid)) + MilliSleep(KeySleep) + return nil +} + +func keyToggles(k string, keyArr []string, pid int) error { + down, keyArr1 := getKeyDown(keyArr) + return keyTogglesB(k, down, keyArr1, pid) +} + +/* + __ ___ ___________ ____ .______ ______ ___ .______ _______ +| |/ / | ____\ \ / / | _ \ / __ \ / \ | _ \ | \ +| ' / | |__ \ \/ / | |_) | | | | | / ^ \ | |_) | | .--. | +| < | __| \_ _/ | _ < | | | | / /_\ \ | / | | | | +| . \ | |____ | | | |_) | | `--' | / _____ \ | |\ \----.| '--' | +|__|\__\ |_______| |__| |______/ \______/ /__/ \__\ | _| `._____||_______/ + +*/ + +// ToInterfaces convert []string to []interface{} +func ToInterfaces(fields []string) []interface{} { + res := make([]interface{}, 0, len(fields)) + for _, s := range fields { + res = append(res, s) + } + return res +} + +// ToStrings convert []interface{} to []string +func ToStrings(fields []interface{}) []string { + res := make([]string, 0, len(fields)) + for _, s := range fields { + res = append(res, s.(string)) + } + return res +} + +// toErr it converts a C string to a Go error +func toErr(str *C.char) error { + gstr := C.GoString(str) + if gstr == "" { + return nil + } + return errors.New(gstr) +} + +func appendShift(key string, len1 int, args ...interface{}) (string, []interface{}) { + if len(key) > 0 && unicode.IsUpper([]rune(key)[0]) { + args = append(args, "shift") + } + + key = strings.ToLower(key) + if _, ok := Special[key]; ok { + key = Special[key] + if len(args) <= len1 { + args = append(args, "shift") + } + } + + return key, args +} + +// KeyTap taps the keyboard code; +// +// See keys supported: +// +// https://github.com/go-vgo/robotgo/blob/master/docs/keys.md#keys +// +// Examples: +// +// robotgo.KeySleep = 100 // 100 millisecond +// robotgo.KeyTap("a") +// robotgo.KeyTap("i", "alt", "command") +// +// arr := []string{"alt", "command"} +// robotgo.KeyTap("i", arr) +// +// robotgo.KeyTap("k", pid int) +func KeyTap(key string, args ...interface{}) error { + var keyArr []string + key, args = appendShift(key, 0, args...) + + pid := 0 + if len(args) > 0 { + if reflect.TypeOf(args[0]) == reflect.TypeOf(keyArr) { + keyArr = args[0].([]string) + } else { + if reflect.TypeOf(args[0]) == reflect.TypeOf(pid) { + pid = args[0].(int) + keyArr = ToStrings(args[1:]) + } else { + keyArr = ToStrings(args) + } + } + } + + return keyTaps(key, keyArr, pid) +} + +func getToggleArgs(args ...interface{}) (pid int, keyArr []string) { + if len(args) > 0 && reflect.TypeOf(args[0]) == reflect.TypeOf(pid) { + pid = args[0].(int) + keyArr = ToStrings(args[1:]) + } else { + keyArr = ToStrings(args) + } + return +} + +// KeyToggle toggles the keyboard, if there not have args default is "down" +// +// See keys: +// +// https://github.com/go-vgo/robotgo/blob/master/docs/keys.md#keys +// +// Examples: +// +// robotgo.KeyToggle("a") +// robotgo.KeyToggle("a", "up") +// +// robotgo.KeyToggle("a", "up", "alt", "cmd") +// robotgo.KeyToggle("k", pid int) +func KeyToggle(key string, args ...interface{}) error { + key, args = appendShift(key, 1, args...) + pid, keyArr := getToggleArgs(args...) + return keyToggles(key, keyArr, pid) +} + +// KeyPress press key string +func KeyPress(key string, args ...interface{}) error { + err := KeyDown(key, args...) + if err != nil { + return err + } + + MilliSleep(1 + rand.Intn(3)) + return KeyUp(key, args...) +} + +// KeyDown press down a key +func KeyDown(key string, args ...interface{}) error { + return KeyToggle(key, args...) +} + +// KeyUp press up a key +func KeyUp(key string, args ...interface{}) error { + arr := []interface{}{"up"} + arr = append(arr, args...) + return KeyToggle(key, arr...) +} + +// ReadAll read string from clipboard +func ReadAll() (string, error) { + return clipboard.ReadAll() +} + +// WriteAll write string to clipboard +func WriteAll(text string) error { + return clipboard.WriteAll(text) +} + +// CharCodeAt char code at utf-8 +func CharCodeAt(s string, n int) rune { + i := 0 + for _, r := range s { + if i == n { + return r + } + i++ + } + + return 0 +} + +// UnicodeType tap the uint32 unicode +func UnicodeType(str uint32, args ...int) { + cstr := C.uint(str) + pid := 0 + if len(args) > 0 { + pid = args[0] + } + + isPid := 0 + if len(args) > 1 { + isPid = args[1] + } + + C.unicodeType(cstr, C.uintptr(pid), C.int8_t(isPid)) +} + +// ToUC trans string to unicode []string +func ToUC(text string) []string { + var uc []string + + for _, r := range text { + textQ := strconv.QuoteToASCII(string(r)) + textUnQ := textQ[1 : len(textQ)-1] + + st := strings.Replace(textUnQ, "\\u", "U", -1) + if st == "\\\\" { + st = "\\" + } + if st == `\"` { + st = `"` + } + uc = append(uc, st) + } + + return uc +} + +func inputUTF(str string) { + cstr := C.CString(str) + C.input_utf(cstr) + + C.free(unsafe.Pointer(cstr)) +} + +// TypeStr send a string (supported UTF-8) +// +// robotgo.TypeStr(string: "The string to send", int: pid, "milli_sleep time", "x11 option") +// +// Examples: +// +// robotgo.TypeStr("abc@123, Hi galaxy, こんにちは") +// robotgo.TypeStr("To be or not to be, this is questions.", pid int) +func TypeStr(str string, args ...int) { + var tm, tm1 = 0, 7 + + if len(args) > 1 { + tm = args[1] + } + if len(args) > 2 { + tm1 = args[2] + } + pid := 0 + if len(args) > 0 { + pid = args[0] + } + + if runtime.GOOS == "linux" { + strUc := ToUC(str) + for i := 0; i < len(strUc); i++ { + ru := []rune(strUc[i]) + if len(ru) <= 1 { + ustr := uint32(CharCodeAt(strUc[i], 0)) + UnicodeType(ustr, pid) + } else { + inputUTF(strUc[i]) + MilliSleep(tm1) + } + + MilliSleep(tm) + } + return + } + + for i := 0; i < len([]rune(str)); i++ { + ustr := uint32(CharCodeAt(str, i)) + UnicodeType(ustr, pid) + // if len(args) > 0 { + MilliSleep(tm) + // } + } + MilliSleep(KeySleep) +} + +// PasteStr paste a string (support UTF-8), +// write the string to clipboard and tap `cmd + v` +func PasteStr(str string) error { + err := clipboard.WriteAll(str) + if err != nil { + return err + } + + if runtime.GOOS == "darwin" { + return KeyTap("v", "command") + } + + return KeyTap("v", "control") +} + +// TypeStrDelay type string with delayed +// And you can use robotgo.KeySleep = 100 to delayed not this function +func TypeStrDelay(str string, delay int) { + TypeStr(str) + MilliSleep(delay) +} + +// SetDelay sets the key and mouse delay +// robotgo.SetDelay(100) option the robotgo.KeySleep and robotgo.MouseSleep = d +func SetDelay(d ...int) { + v := 10 + if len(d) > 0 { + v = d[0] + } + + KeySleep = v + MouseSleep = v +} diff --git a/key/goKey.h b/key/goKey.h deleted file mode 100644 index 77c1927d..00000000 --- a/key/goKey.h +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#include "../base/types.h" -// #include "keycode.h" -// #include "keypress.h" -#include "keypress_c.h" -#include "keycode_c.h" - - -int keyboardDelay = 0; - -struct KeyNames{ - const char* name; - MMKeyCode key; -}key_names[] = { - { "backspace", K_BACKSPACE }, - { "delete", K_DELETE }, - { "enter", K_RETURN }, - { "tab", K_TAB }, - { "esc", K_ESCAPE }, - { "escape", K_ESCAPE }, - { "up", K_UP }, - { "down", K_DOWN }, - { "right", K_RIGHT }, - { "left", K_LEFT }, - { "home", K_HOME }, - { "end", K_END }, - { "pageup", K_PAGEUP }, - { "pagedown", K_PAGEDOWN }, - // - { "f1", K_F1 }, - { "f2", K_F2 }, - { "f3", K_F3 }, - { "f4", K_F4 }, - { "f5", K_F5 }, - { "f6", K_F6 }, - { "f7", K_F7 }, - { "f8", K_F8 }, - { "f9", K_F9 }, - { "f10", K_F10 }, - { "f11", K_F11 }, - { "f12", K_F12 }, - { "f13", K_F13 }, - { "f14", K_F14 }, - { "f15", K_F15 }, - { "f16", K_F16 }, - { "f17", K_F17 }, - { "f18", K_F18 }, - { "f19", K_F19 }, - { "f20", K_F20 }, - { "f21", K_F21 }, - { "f22", K_F22 }, - { "f23", K_F23 }, - { "f24", K_F24 }, - // - { "cmd", K_META }, - { "lcmd", K_LMETA }, - { "rcmd", K_RMETA }, - { "command", K_META }, - { "alt", K_ALT }, - { "lalt", K_LALT }, - { "ralt", K_RALT }, - { "ctrl", K_CONTROL }, - { "lctrl", K_LCONTROL }, - { "rctrl", K_RCONTROL }, - { "control", K_CONTROL }, - { "shift", K_SHIFT }, - { "lshift", K_LSHIFT }, - { "rshift", K_RSHIFT }, - { "right_shift", K_RSHIFT }, - { "capslock", K_CAPSLOCK }, - { "space", K_SPACE }, - { "print", K_PRINTSCREEN }, - { "printscreen", K_PRINTSCREEN }, - { "insert", K_INSERT }, - { "menu", K_MENU }, - - { "audio_mute", K_AUDIO_VOLUME_MUTE }, - { "audio_vol_down", K_AUDIO_VOLUME_DOWN }, - { "audio_vol_up", K_AUDIO_VOLUME_UP }, - { "audio_play", K_AUDIO_PLAY }, - { "audio_stop", K_AUDIO_STOP }, - { "audio_pause", K_AUDIO_PAUSE }, - { "audio_prev", K_AUDIO_PREV }, - { "audio_next", K_AUDIO_NEXT }, - { "audio_rewind", K_AUDIO_REWIND }, - { "audio_forward", K_AUDIO_FORWARD }, - { "audio_repeat", K_AUDIO_REPEAT }, - { "audio_random", K_AUDIO_RANDOM }, - - { "num0", K_NUMPAD_0 }, - { "num1", K_NUMPAD_1 }, - { "num2", K_NUMPAD_2 }, - { "num3", K_NUMPAD_3 }, - { "num4", K_NUMPAD_4 }, - { "num5", K_NUMPAD_5 }, - { "num6", K_NUMPAD_6 }, - { "num7", K_NUMPAD_7 }, - { "num8", K_NUMPAD_8 }, - { "num9", K_NUMPAD_9 }, - { "num_lock", K_NUMPAD_LOCK }, - - {"num.", K_NUMPAD_DECIMAL }, - {"num+", K_NUMPAD_PLUS }, - {"num-", K_NUMPAD_MINUS }, - {"num*", K_NUMPAD_MUL }, - {"num/", K_NUMPAD_DIV }, - {"num_clear", K_NUMPAD_CLEAR }, - {"num_enter", K_NUMPAD_ENTER }, - {"num_equal", K_NUMPAD_EQUAL }, - - { "numpad_0", K_NUMPAD_0 }, - { "numpad_1", K_NUMPAD_1 }, - { "numpad_2", K_NUMPAD_2 }, - { "numpad_3", K_NUMPAD_3 }, - { "numpad_4", K_NUMPAD_4 }, - { "numpad_5", K_NUMPAD_5 }, - { "numpad_6", K_NUMPAD_6 }, - { "numpad_7", K_NUMPAD_7 }, - { "numpad_8", K_NUMPAD_8 }, - { "numpad_9", K_NUMPAD_9 }, - { "numpad_lock", K_NUMPAD_LOCK }, - - { "lights_mon_up", K_LIGHTS_MON_UP }, - { "lights_mon_down", K_LIGHTS_MON_DOWN }, - { "lights_kbd_toggle",K_LIGHTS_KBD_TOGGLE }, - { "lights_kbd_up", K_LIGHTS_KBD_UP }, - { "lights_kbd_down", K_LIGHTS_KBD_DOWN }, - - { NULL, K_NOT_A_KEY } /* end marker */ -}; - -int CheckKeyCodes(char* k, MMKeyCode *key){ - if (!key) { return -1; } - - if (strlen(k) == 1) { - *key = keyCodeForChar(*k); - return 0; - } - - *key = K_NOT_A_KEY; - - struct KeyNames* kn = key_names; - while (kn->name) { - if (strcmp(k, kn->name) == 0){ - *key = kn->key; - break; - } - kn++; - } - - if (*key == K_NOT_A_KEY) { - return -2; - } - - return 0; -} - -int CheckKeyFlags(char* f, MMKeyFlags* flags){ - if (!flags) { return -1; } - - if ( strcmp(f, "alt") == 0 || strcmp(f, "ralt") == 0 || - strcmp(f, "lalt") == 0 ) { - *flags = MOD_ALT; - } - else if( strcmp(f, "command") == 0 || strcmp(f, "cmd") == 0 || - strcmp(f, "rcmd") == 0 || strcmp(f, "lcmd") == 0 ) { - *flags = MOD_META; - } - else if( strcmp(f, "control") == 0 || strcmp(f, "ctrl") == 0 || - strcmp(f, "rctrl") == 0 || strcmp(f, "lctrl") == 0 ) { - *flags = MOD_CONTROL; - } - else if( strcmp(f, "shift") == 0 || strcmp(f, "right_shift") == 0 || - strcmp(f, "rshift") == 0 || strcmp(f, "lshift") == 0 ) { - *flags = MOD_SHIFT; - } - else if( strcmp(f, "none") == 0 ) { - *flags = (MMKeyFlags) MOD_NONE; - } else { - return -2; - } - - return 0; -} - -int GetFlagsFromValue(char* value[], MMKeyFlags* flags, int num){ - if (!flags) {return -1;} - - int i; - for ( i= 0; i +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package key diff --git a/key/key_windows.go b/key/key_windows.go new file mode 100644 index 00000000..808cd693 --- /dev/null +++ b/key/key_windows.go @@ -0,0 +1,4 @@ +//go:build windows +// +build windows + +package key diff --git a/key/keycode.h b/key/keycode.h index 5d40629f..d5577faa 100644 --- a/key/keycode.h +++ b/key/keycode.h @@ -4,11 +4,6 @@ #include "../base/os.h" -#ifdef __cplusplus -extern "C" -{ -#endif - #if defined(IS_MACOSX) #include /* Really only need */ @@ -96,6 +91,13 @@ enum _MMKeyCode { K_NUMPAD_CLEAR = kVK_ANSI_KeypadClear, K_NUMPAD_ENTER = kVK_ANSI_KeypadEnter, K_NUMPAD_EQUAL = kVK_ANSI_KeypadEquals, + K_NUMPAD_LB = kVK_ANSI_LeftBracket, + K_NUMPAD_RB = kVK_ANSI_RightBracket, + K_Backslash = kVK_ANSI_Backslash, + K_Semicolon = kVK_ANSI_Semicolon, + K_Quote = kVK_ANSI_Quote, + K_Slash = kVK_ANSI_Slash, + K_Grave = kVK_ANSI_Grave, K_AUDIO_VOLUME_MUTE = 1007, K_AUDIO_VOLUME_DOWN = 1001, @@ -177,7 +179,7 @@ enum _MMKeyCode { K_SHIFT = XK_Shift_L, K_LSHIFT = XK_Shift_L, K_RSHIFT = XK_Shift_R, - K_CAPSLOCK = XK_Shift_Lock, + K_CAPSLOCK = XK_Caps_Lock, K_SPACE = XK_space, K_INSERT = XK_Insert, K_PRINTSCREEN = XK_Print, @@ -204,6 +206,13 @@ enum _MMKeyCode { K_NUMPAD_CLEAR = K_NOT_A_KEY, K_NUMPAD_ENTER = 96, // XK_KP_Enter K_NUMPAD_EQUAL = XK_equal, + K_NUMPAD_LB = XK_bracketleft, + K_NUMPAD_RB = XK_bracketright, + K_Backslash = XK_backslash, + K_Semicolon = XK_semicolon, + K_Quote = XK_apostrophe, + K_Slash = XK_slash, + K_Grave = XK_grave, K_AUDIO_VOLUME_MUTE = XF86XK_AudioMute, K_AUDIO_VOLUME_DOWN = XF86XK_AudioLowerVolume, @@ -227,6 +236,53 @@ enum _MMKeyCode { typedef KeySym MMKeyCode; +/* + * Structs to store key mappings not handled by XStringToKeysym() on some + * Linux systems. + */ +struct XSpecialCharacterMapping { + char name; + MMKeyCode code; +}; + +struct XSpecialCharacterMapping XSpecialCharacterTable[] = { + {'~', XK_asciitilde}, + {'_', XK_underscore}, + {'[', XK_bracketleft}, + {']', XK_bracketright}, + {'!', XK_exclam}, + {'#', XK_numbersign}, + {'$', XK_dollar}, + {'%', XK_percent}, + {'&', XK_ampersand}, + {'*', XK_asterisk}, + {'+', XK_plus}, + {',', XK_comma}, + {'-', XK_minus}, + {'.', XK_period}, + {'?', XK_question}, + {'<', XK_less}, + {'>', XK_greater}, + {'=', XK_equal}, + {'@', XK_at}, + {':', XK_colon}, + {';', XK_semicolon}, + {'{', XK_braceleft}, + {'}', XK_braceright}, + {'|', XK_bar}, + {'^', XK_asciicircum}, + {'(', XK_parenleft}, + {')', XK_parenright}, + {' ', XK_space}, + {'/', XK_slash}, + {'\\', XK_backslash}, + {'`', XK_grave}, + {'"', XK_quoteright}, + {'\'', XK_quotedbl}, + {'\t', XK_Tab}, + {'\n', XK_Return} +}; + #elif defined(IS_WINDOWS) enum _MMKeyCode { @@ -308,6 +364,13 @@ enum _MMKeyCode { K_NUMPAD_CLEAR = K_NOT_A_KEY, K_NUMPAD_ENTER = VK_RETURN, K_NUMPAD_EQUAL = VK_OEM_PLUS, + K_NUMPAD_LB = VK_OEM_4, + K_NUMPAD_RB = VK_OEM_6, + K_Backslash = VK_OEM_5, + K_Semicolon = VK_OEM_1, + K_Quote = VK_OEM_7, + K_Slash = VK_OEM_2, + K_Grave = VK_OEM_3, K_AUDIO_VOLUME_MUTE = VK_VOLUME_MUTE, K_AUDIO_VOLUME_DOWN = VK_VOLUME_DOWN, @@ -338,7 +401,3 @@ typedef int MMKeyCode; MMKeyCode keyCodeForChar(const char c); #endif /* KEYCODE_H */ - -#ifdef __cplusplus -} -#endif diff --git a/key/keycode_c.h b/key/keycode_c.h index cb19f516..efc4f6bd 100644 --- a/key/keycode_c.h +++ b/key/keycode_c.h @@ -1,72 +1,19 @@ #include "keycode.h" #if defined(IS_MACOSX) + #include + #include /* For kVK_ constants, and TIS functions. */ -#include -#include /* For kVK_ constants, and TIS functions. */ - -/* Returns string representation of key, if it is printable. - * Ownership follows the Create Rule; that is, it is the caller's - * responsibility to release the returned object. */ -CFStringRef createStringForKey(CGKeyCode keyCode); - -#elif defined(USE_X11) - -/* - * Structs to store key mappings not handled by XStringToKeysym() on some - * Linux systems. - */ - -struct XSpecialCharacterMapping { - char name; - MMKeyCode code; -}; - -struct XSpecialCharacterMapping XSpecialCharacterTable[] = { - {'~', XK_asciitilde}, - {'_', XK_underscore}, - {'[', XK_bracketleft}, - {']', XK_bracketright}, - {'!', XK_exclam}, - {'#', XK_numbersign}, - {'$', XK_dollar}, - {'%', XK_percent}, - {'&', XK_ampersand}, - {'*', XK_asterisk}, - {'+', XK_plus}, - {',', XK_comma}, - {'-', XK_minus}, - {'.', XK_period}, - {'?', XK_question}, - {'<', XK_less}, - {'>', XK_greater}, - {'=', XK_equal}, - {'@', XK_at}, - {':', XK_colon}, - {';', XK_semicolon}, - {'`', XK_grave}, - {'{', XK_braceleft}, - {'}', XK_braceright}, - {'|', XK_bar}, - {'^', XK_asciicircum}, - {'(', XK_parenleft}, - {')', XK_parenright}, - {' ', XK_space}, - {'/', XK_slash}, - {'"', XK_quoteright}, - {'\'', XK_quotedbl}, - // {'\'', XK_quoteright}, - {'\\', XK_backslash}, - {'\t', XK_Tab}, - {'\n', XK_Return} -}; - + /* Returns string representation of key, if it is printable. + Ownership follows the Create Rule; + it is the caller's responsibility to release the returned object. */ + CFStringRef createStringForKey(CGKeyCode keyCode); #endif -MMKeyCode keyCodeForChar(const char c){ +MMKeyCode keyCodeForChar(const char c) { #if defined(IS_MACOSX) - /* OS X does not appear to have a built-in function for this, so instead we - * have to write our own. */ + /* OS X does not appear to have a built-in function for this, + so instead it to write our own. */ static CFMutableDictionaryRef charToCodeDict = NULL; CGKeyCode code; UniChar character = c; @@ -75,11 +22,9 @@ MMKeyCode keyCodeForChar(const char c){ /* Generate table of keycodes and characters. */ if (charToCodeDict == NULL) { size_t i; - charToCodeDict = CFDictionaryCreateMutable(kCFAllocatorDefault, - 128, - &kCFCopyStringDictionaryKeyCallBacks, - NULL); - if (charToCodeDict == NULL) return UINT16_MAX; + charToCodeDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 128, + &kCFCopyStringDictionaryKeyCallBacks, NULL); + if (charToCodeDict == NULL) { return K_NOT_A_KEY; } /* Loop through every keycode (0 - 127) to find its current mapping. */ for (i = 0; i < 128; ++i) { @@ -92,74 +37,76 @@ MMKeyCode keyCodeForChar(const char c){ } charStr = CFStringCreateWithCharacters(kCFAllocatorDefault, &character, 1); - /* Our values may be NULL (0), so we need to use this function. */ - if (!CFDictionaryGetValueIfPresent(charToCodeDict, charStr, - (const void **)&code)) { + if (!CFDictionaryGetValueIfPresent(charToCodeDict, charStr, (const void **)&code)) { code = UINT16_MAX; /* Error */ } - CFRelease(charStr); + + // TISGetInputSourceProperty may return nil so we need fallback + if (code == UINT16_MAX) { + return K_NOT_A_KEY; + } + return (MMKeyCode)code; #elif defined(IS_WINDOWS) - return VkKeyScan(c); - #elif defined(USE_X11) MMKeyCode code; + code = VkKeyScan(c); + if (code == 0xFFFF) { + return K_NOT_A_KEY; + } + return code; + #elif defined(USE_X11) char buf[2]; buf[0] = c; buf[1] = '\0'; - code = XStringToKeysym(buf); + MMKeyCode code = XStringToKeysym(buf); if (code == NoSymbol) { - /* Some special keys are apparently not handled properly by - * XStringToKeysym() on some systems, so search for them instead in our - * mapping table. */ + /* Some special keys are apparently not handled properly */ struct XSpecialCharacterMapping* xs = XSpecialCharacterTable; while (xs->name) { - if (c == xs->name ) { + if (c == xs->name) { code = xs->code; + // break; } xs++; } } + if (code == NoSymbol) { + return K_NOT_A_KEY; + } + + // x11 key bug + if (c == 60) { + code = 44; + } return code; #endif } - #if defined(IS_MACOSX) - -CFStringRef createStringForKey(CGKeyCode keyCode){ - TISInputSourceRef currentKeyboard = TISCopyCurrentASCIICapableKeyboardInputSource(); - CFDataRef layoutData = - (CFDataRef)TISGetInputSourceProperty(currentKeyboard, - kTISPropertyUnicodeKeyLayoutData); - - if (layoutData == nil) { return 0; } - - const UCKeyboardLayout *keyboardLayout = - (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData); - - UInt32 keysDown = 0; - UniChar chars[4]; - UniCharCount realLength; - - UCKeyTranslate(keyboardLayout, - keyCode, - kUCKeyActionDisplay, - 0, - LMGetKbdType(), - kUCKeyTranslateNoDeadKeysBit, - &keysDown, - sizeof(chars) / sizeof(chars[0]), - &realLength, - chars); - CFRelease(currentKeyboard); - - return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1); -} - + CFStringRef createStringForKey(CGKeyCode keyCode){ + // TISInputSourceRef currentKeyboard = TISCopyCurrentASCIICapableKeyboardInputSource(); + TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardLayoutInputSource(); + CFDataRef layoutData = (CFDataRef) TISGetInputSourceProperty( + currentKeyboard, kTISPropertyUnicodeKeyLayoutData); + + if (layoutData == nil) { return 0; } + + const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *) CFDataGetBytePtr(layoutData); + UInt32 keysDown = 0; + UniChar chars[4]; + UniCharCount realLength; + + UCKeyTranslate(keyboardLayout, keyCode, kUCKeyActionDisplay, 0, LMGetKbdType(), + kUCKeyTranslateNoDeadKeysBit, &keysDown, + sizeof(chars) / sizeof(chars[0]), &realLength, chars); + CFRelease(currentKeyboard); + + return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1); + } #endif diff --git a/key/keypress.h b/key/keypress.h index 20e84d69..3079d294 100644 --- a/key/keypress.h +++ b/key/keypress.h @@ -2,22 +2,14 @@ #ifndef KEYPRESS_H #define KEYPRESS_H +#include #include "../base/os.h" -#include "keycode.h" - -#if defined(_MSC_VER) - #include "../base/ms_stdbool.h" -#else - #include -#endif +#include "../base/types.h" -#ifdef __cplusplus -extern "C" -{ -#endif +#include "keycode.h" +#include #if defined(IS_MACOSX) - typedef enum { MOD_NONE = 0, MOD_META = kCGEventFlagMaskCommand, @@ -25,9 +17,7 @@ extern "C" MOD_CONTROL = kCGEventFlagMaskControl, MOD_SHIFT = kCGEventFlagMaskShift } MMKeyFlags; - #elif defined(USE_X11) - enum _MMKeyFlags { MOD_NONE = 0, MOD_META = Mod4Mask, @@ -35,11 +25,8 @@ extern "C" MOD_CONTROL = ControlMask, MOD_SHIFT = ShiftMask }; - typedef unsigned int MMKeyFlags; - #elif defined(IS_WINDOWS) - enum _MMKeyFlags { MOD_NONE = 0, /* These are already defined by the Win32 API */ @@ -48,44 +35,12 @@ extern "C" MOD_SHIFT = 0, */ MOD_META = MOD_WIN }; - typedef unsigned int MMKeyFlags; - #endif #if defined(IS_WINDOWS) -/* Send win32 key event for given key. */ -void win32KeyEvent(int key, MMKeyFlags flags); -#endif - -/* Toggles the given key down or up. */ -void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags); - -/* Toggles the key down and then up. */ -void tapKeyCode(MMKeyCode code, MMKeyFlags flags); - -/* Toggles the key corresponding to the given UTF character up or down. */ -void toggleKey(char c, const bool down, MMKeyFlags flags); -void tapKey(char c, MMKeyFlags flags); - -/* Sends a UTF-8 string without modifiers. */ -void typeString(const char *str); -/* Sends a Unicode character without modifiers. */ -void unicodeType(const unsigned value); - -/* Macro to convert WPM to CPM integers. - * (the average English word length is 5.1 characters.) */ -#define WPM_TO_CPM(WPM) (unsigned)(5.1 * WPM) - -/* Sends UTF-8 string without modifiers and - * with partially random delays between each letter. - * Note that deadbeef_srand() must be called before this function - * if you actually want randomness. - * */ -void typeStringDelayed(const char *str, const unsigned cpm); - -#ifdef __cplusplus -} + /* Send win32 key event for given key. */ + void win32KeyEvent(int key, MMKeyFlags flags, uintptr pid, int8_t isPid); #endif #endif /* KEYPRESS_H */ diff --git a/key/keypress_c.h b/key/keypress_c.h index da63ae4b..060f5f45 100644 --- a/key/keypress_c.h +++ b/key/keypress_c.h @@ -1,9 +1,19 @@ -#include "keypress.h" -// #include "../base/deadbeef_rand_c.h" +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +#include "../base/deadbeef_rand_c.h" #include "../base/microsleep.h" +#include "keypress.h" +#include "keycode_c.h" #include /* For isupper() */ - #if defined(IS_MACOSX) #include #import @@ -15,115 +25,147 @@ /* Convenience wrappers around ugly APIs. */ #if defined(IS_WINDOWS) - #define WIN32_KEY_EVENT_WAIT(key, flags) \ - (win32KeyEvent(key, flags), Sleep(DEADBEEF_RANDRANGE(0, 1))) + HWND GetHwndByPid(DWORD dwProcessId); + + HWND getHwnd(uintptr pid, int8_t isPid) { + HWND hwnd = (HWND) pid; + if (isPid == 0) { + hwnd = GetHwndByPid(pid); + } + return hwnd; + } + + void WIN32_KEY_EVENT_WAIT(MMKeyCode key, DWORD flags, uintptr pid) { + win32KeyEvent(key, flags, pid, 0); + Sleep(DEADBEEF_RANDRANGE(0, 1)); + } #elif defined(USE_X11) - #define X_KEY_EVENT(display, key, is_press) \ - (XTestFakeKeyEvent(display, \ - XKeysymToKeycode(display, key), \ - is_press, CurrentTime), \ - XSync(display, false)) - #define X_KEY_EVENT_WAIT(display, key, is_press) \ - (X_KEY_EVENT(display, key, is_press), \ - microsleep(DEADBEEF_UNIFORM(0.0, 0.5))) + Display *XGetMainDisplay(void); + + void X_KEY_EVENT(Display *display, MMKeyCode key, bool is_press) { + XTestFakeKeyEvent(display, XKeysymToKeycode(display, key), is_press, CurrentTime); + XSync(display, false); + } + + void X_KEY_EVENT_WAIT(Display *display, MMKeyCode key, bool is_press) { + X_KEY_EVENT(display, key, is_press); + microsleep(DEADBEEF_UNIFORM(0.0, 0.5)); + } #endif #if defined(IS_MACOSX) -static io_connect_t _getAuxiliaryKeyDriver(void){ - static mach_port_t sEventDrvrRef = 0; - mach_port_t masterPort, service, iter; - kern_return_t kr; + int SendTo(uintptr pid, CGEventRef event) { + if (pid != 0) { + CGEventPostToPid(pid, event); + } else { + CGEventPost(kCGHIDEventTap, event); + } + + CFRelease(event); + return 0; + } - if (!sEventDrvrRef) { - kr = IOMasterPort( bootstrap_port, &masterPort ); - assert(KERN_SUCCESS == kr); - kr = IOServiceGetMatchingServices(masterPort, - IOServiceMatching( kIOHIDSystemClass), &iter ); - assert(KERN_SUCCESS == kr); + static io_connect_t _getAuxiliaryKeyDriver(void) { + static mach_port_t sEventDrvrRef = 0; + mach_port_t masterPort, service, iter; + kern_return_t kr; - service = IOIteratorNext( iter ); - assert(service); - - kr = IOServiceOpen(service, - mach_task_self(), kIOHIDParamConnectType, &sEventDrvrRef ); - assert(KERN_SUCCESS == kr); + if (!sEventDrvrRef) { + kr = IOMasterPort(bootstrap_port, &masterPort); + assert(KERN_SUCCESS == kr); + kr = IOServiceGetMatchingServices(masterPort, IOServiceMatching(kIOHIDSystemClass), &iter); + assert(KERN_SUCCESS == kr); - IOObjectRelease(service); - IOObjectRelease(iter); - } - return sEventDrvrRef; -} -#endif + service = IOIteratorNext(iter); + assert(service); -#if defined(IS_WINDOWS) -void win32KeyEvent(int key, MMKeyFlags flags){ - int scan = MapVirtualKey(key & 0xff, MAPVK_VK_TO_VSC); - - /* Set the scan code for extended keys */ - switch (key){ - case VK_RCONTROL: - case VK_SNAPSHOT: /* Print Screen */ - case VK_RMENU: /* Right Alt / Alt Gr */ - case VK_PAUSE: /* Pause / Break */ - case VK_HOME: - case VK_UP: - case VK_PRIOR: /* Page up */ - case VK_LEFT: - case VK_RIGHT: - case VK_END: - case VK_DOWN: - case VK_NEXT: /* 'Page Down' */ - case VK_INSERT: - case VK_DELETE: - case VK_LWIN: - case VK_RWIN: - case VK_APPS: /* Application */ - case VK_VOLUME_MUTE: - case VK_VOLUME_DOWN: - case VK_VOLUME_UP: - case VK_MEDIA_NEXT_TRACK: - case VK_MEDIA_PREV_TRACK: - case VK_MEDIA_STOP: - case VK_MEDIA_PLAY_PAUSE: - case VK_BROWSER_BACK: - case VK_BROWSER_FORWARD: - case VK_BROWSER_REFRESH: - case VK_BROWSER_STOP: - case VK_BROWSER_SEARCH: - case VK_BROWSER_FAVORITES: - case VK_BROWSER_HOME: - case VK_LAUNCH_MAIL: - { - flags |= KEYEVENTF_EXTENDEDKEY; - break; + kr = IOServiceOpen(service, mach_task_self(), kIOHIDParamConnectType, &sEventDrvrRef); + assert(KERN_SUCCESS == kr); + + IOObjectRelease(service); + IOObjectRelease(iter); } + return sEventDrvrRef; } +#elif defined(IS_WINDOWS) - /* Set the scan code for keyup */ - // if ( flags & KEYEVENTF_KEYUP ) { - // scan |= 0x80; - // } - - // keybd_event(key, scan, flags, 0); - - INPUT keyInput; - - keyInput.type = INPUT_KEYBOARD; - keyInput.ki.wVk = key; - keyInput.ki.wScan = scan; - keyInput.ki.dwFlags = flags; - keyInput.ki.time = 0; - keyInput.ki.dwExtraInfo = 0; - SendInput(1, &keyInput, sizeof(keyInput)); -} + void win32KeyEvent(int key, MMKeyFlags flags, uintptr pid, int8_t isPid) { + int scan = MapVirtualKey(key & 0xff, MAPVK_VK_TO_VSC); + + /* Set the scan code for extended keys */ + switch (key){ + case VK_RCONTROL: + case VK_SNAPSHOT: /* Print Screen */ + case VK_RMENU: /* Right Alt / Alt Gr */ + case VK_PAUSE: /* Pause / Break */ + case VK_HOME: + case VK_UP: + case VK_PRIOR: /* Page up */ + case VK_LEFT: + case VK_RIGHT: + case VK_END: + case VK_DOWN: + case VK_NEXT: /* 'Page Down' */ + case VK_INSERT: + case VK_DELETE: + case VK_LWIN: + case VK_RWIN: + case VK_APPS: /* Application */ + case VK_VOLUME_MUTE: + case VK_VOLUME_DOWN: + case VK_VOLUME_UP: + case VK_MEDIA_NEXT_TRACK: + case VK_MEDIA_PREV_TRACK: + case VK_MEDIA_STOP: + case VK_MEDIA_PLAY_PAUSE: + case VK_BROWSER_BACK: + case VK_BROWSER_FORWARD: + case VK_BROWSER_REFRESH: + case VK_BROWSER_STOP: + case VK_BROWSER_SEARCH: + case VK_BROWSER_FAVORITES: + case VK_BROWSER_HOME: + case VK_LAUNCH_MAIL: + { + flags |= KEYEVENTF_EXTENDEDKEY; + break; + } + } + + // todo: test this + if (pid != 0) { + HWND hwnd = getHwnd(pid, isPid); + + int down = (flags == 0 ? WM_KEYDOWN : WM_KEYUP); + // SendMessage(hwnd, down, key, 0); + PostMessageW(hwnd, down, key, 0); + return; + } + + /* Set the scan code for keyup */ + // if ( flags & KEYEVENTF_KEYUP ) { + // scan |= 0x80; + // } + // keybd_event(key, scan, flags, 0); + + INPUT keyInput; + + keyInput.type = INPUT_KEYBOARD; + keyInput.ki.wVk = key; + keyInput.ki.wScan = scan; + keyInput.ki.dwFlags = flags; + keyInput.ki.time = 0; + keyInput.ki.dwExtraInfo = 0; + SendInput(1, &keyInput, sizeof(keyInput)); + } #endif -void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags){ +void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags, uintptr pid) { #if defined(IS_MACOSX) /* The media keys all have 1000 added to them to help us detect them. */ if (code >= 1000) { code = code - 1000; /* Get the real keycode. */ - NXEventData event; + NXEventData event; kern_return_t kr; IOGPoint loc = { 0, 0 }; @@ -133,48 +175,51 @@ void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags){ event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS; event.compound.misc.L[0] = evtInfo; - kr = IOHIDPostEvent( _getAuxiliaryKeyDriver(), - NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE ); - assert( KERN_SUCCESS == kr ); + kr = IOHIDPostEvent(_getAuxiliaryKeyDriver(), + NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE); + assert(KERN_SUCCESS == kr); } else { - CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL, - (CGKeyCode)code, down); + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef keyEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)code, down); assert(keyEvent != NULL); CGEventSetType(keyEvent, down ? kCGEventKeyDown : kCGEventKeyUp); - // CGEventSetFlags(keyEvent, flags); - CGEventSetFlags(keyEvent, (int) flags); - CGEventPost(kCGSessionEventTap, keyEvent); - CFRelease(keyEvent); + if (flags != 0) { + CGEventSetFlags(keyEvent, (CGEventFlags) flags); + } + + SendTo(pid, keyEvent); + CFRelease(source); } #elif defined(IS_WINDOWS) const DWORD dwFlags = down ? 0 : KEYEVENTF_KEYUP; /* Parse modifier keys. */ - if (flags & MOD_META) WIN32_KEY_EVENT_WAIT(K_META, dwFlags); - if (flags & MOD_ALT) WIN32_KEY_EVENT_WAIT(K_ALT, dwFlags); - if (flags & MOD_CONTROL) WIN32_KEY_EVENT_WAIT(K_CONTROL, dwFlags); - if (flags & MOD_SHIFT) WIN32_KEY_EVENT_WAIT(K_SHIFT, dwFlags); + if (flags & MOD_META) { WIN32_KEY_EVENT_WAIT(K_META, dwFlags, pid); } + if (flags & MOD_ALT) { WIN32_KEY_EVENT_WAIT(K_ALT, dwFlags, pid); } + if (flags & MOD_CONTROL) { WIN32_KEY_EVENT_WAIT(K_CONTROL, dwFlags, pid); } + if (flags & MOD_SHIFT) { WIN32_KEY_EVENT_WAIT(K_SHIFT, dwFlags, pid); } - win32KeyEvent(code, dwFlags); + win32KeyEvent(code, dwFlags, pid, 0); #elif defined(USE_X11) Display *display = XGetMainDisplay(); const Bool is_press = down ? True : False; /* Just to be safe. */ /* Parse modifier keys. */ - if (flags & MOD_META) X_KEY_EVENT_WAIT(display, K_META, is_press); - if (flags & MOD_ALT) X_KEY_EVENT_WAIT(display, K_ALT, is_press); - if (flags & MOD_CONTROL) X_KEY_EVENT_WAIT(display, K_CONTROL, is_press); - if (flags & MOD_SHIFT) X_KEY_EVENT_WAIT(display, K_SHIFT, is_press); + if (flags & MOD_META) { X_KEY_EVENT_WAIT(display, K_META, is_press); } + if (flags & MOD_ALT) { X_KEY_EVENT_WAIT(display, K_ALT, is_press); } + if (flags & MOD_CONTROL) { X_KEY_EVENT_WAIT(display, K_CONTROL, is_press); } + if (flags & MOD_SHIFT) { X_KEY_EVENT_WAIT(display, K_SHIFT, is_press); } X_KEY_EVENT(display, code, is_press); #endif } -void tapKeyCode(MMKeyCode code, MMKeyFlags flags){ - toggleKeyCode(code, true, flags); - toggleKeyCode(code, false, flags); -} +// void tapKeyCode(MMKeyCode code, MMKeyFlags flags){ +// toggleKeyCode(code, true, flags); +// microsleep(5.0); +// toggleKeyCode(code, false, flags); +// } #if defined(USE_X11) bool toUpper(char c) { @@ -193,14 +238,9 @@ void tapKeyCode(MMKeyCode code, MMKeyFlags flags){ } #endif -void toggleKey(char c, const bool down, MMKeyFlags flags){ +void toggleKey(char c, const bool down, MMKeyFlags flags, uintptr pid) { MMKeyCode keyCode = keyCodeForChar(c); - //Prevent unused variable warning for Mac and Linux. - #if defined(IS_WINDOWS) - int modifiers; - #endif - #if defined(USE_X11) if (toUpper(c) && !(flags & MOD_SHIFT)) { flags |= MOD_SHIFT; /* Not sure if this is safe for all layouts. */ @@ -212,85 +252,62 @@ void toggleKey(char c, const bool down, MMKeyFlags flags){ #endif #if defined(IS_WINDOWS) - modifiers = keyCode >> 8; // Pull out modifers. - if ((modifiers & 1) != 0) flags |= MOD_SHIFT; // Uptdate flags from keycode modifiers. - if ((modifiers & 2) != 0) flags |= MOD_CONTROL; - if ((modifiers & 4) != 0) flags |= MOD_ALT; + int modifiers = keyCode >> 8; // Pull out modifers. + + if ((modifiers & 1) != 0) { flags |= MOD_SHIFT; } // Uptdate flags from keycode modifiers. + if ((modifiers & 2) != 0) { flags |= MOD_CONTROL; } + if ((modifiers & 4) != 0) { flags |= MOD_ALT; } keyCode = keyCode & 0xff; // Mask out modifiers. #endif - toggleKeyCode(keyCode, down, flags); + toggleKeyCode(keyCode, down, flags, pid); } -void tapKey(char c, MMKeyFlags flags){ - toggleKey(c, true, flags); - toggleKey(c, false, flags); -} +// void tapKey(char c, MMKeyFlags flags){ +// toggleKey(c, true, flags); +// microsleep(5.0); +// toggleKey(c, false, flags); +// } #if defined(IS_MACOSX) -void toggleUnicode(UniChar ch, const bool down){ - /* This function relies on the convenient - * CGEventKeyboardSetUnicodeString(), which allows us to not have to - * convert characters to a keycode, but does not support adding modifier - * flags. It is therefore only used in typeStringDelayed() - * -- if you need modifier keys, use the above functions instead. */ - CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL, 0, down); - if (keyEvent == NULL) { - fputs("Could not create keyboard event.\n", stderr); - return; - } - - CGEventKeyboardSetUnicodeString(keyEvent, 1, &ch); - - CGEventPost(kCGSessionEventTap, keyEvent); - CFRelease(keyEvent); -} -#endif - -#if defined(USE_X11) - #define toggleUniKey(c, down) toggleKey(c, down, MOD_NONE) - - int input_utf(const char *utf) { - Display *dpy; - dpy = XOpenDisplay(NULL); - - KeySym sym = XStringToKeysym(utf); - // KeySym sym = XKeycodeToKeysym(dpy, utf); - - int min, max, numcodes; - XDisplayKeycodes(dpy, &min, &max); - KeySym *keysym; - keysym = XGetKeyboardMapping(dpy, min, max-min+1, &numcodes); - keysym[(max-min-1)*numcodes] = sym; - XChangeKeyboardMapping(dpy, min, numcodes, keysym, (max-min)); - XFree(keysym); - XFlush(dpy); - - KeyCode code = XKeysymToKeycode(dpy, sym); - - XTestFakeKeyEvent(dpy, code, True, 1); - XTestFakeKeyEvent(dpy, code, False, 1); + void toggleUnicode(UniChar ch, const bool down, uintptr pid) { + /* This function relies on the convenient CGEventKeyboardSetUnicodeString(), + convert characters to a keycode, but does not support adding modifier flags. + It is only used in typeString(). + -- if you need modifier keys, use the above functions instead. */ + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef keyEvent = CGEventCreateKeyboardEvent(source, 0, down); + if (keyEvent == NULL) { + fputs("Could not create keyboard event.\n", stderr); + return; + } - XFlush(dpy); - XCloseDisplay(dpy); + CGEventKeyboardSetUnicodeString(keyEvent, 1, &ch); - return 0; - } -#endif -#if !defined(USE_X11) - int input_utf(const char *utf){ - return 0; + SendTo(pid, keyEvent); + CFRelease(source); } +#else + #define toggleUniKey(c, down) toggleKey(c, down, MOD_NONE, 0) #endif // unicode type -void unicodeType(const unsigned value){ +void unicodeType(const unsigned value, uintptr pid, int8_t isPid) { #if defined(IS_MACOSX) UniChar ch = (UniChar)value; // Convert to unsigned char - toggleUnicode(ch, true); - toggleUnicode(ch, false); + toggleUnicode(ch, true, pid); + microsleep(5.0); + toggleUnicode(ch, false, pid); #elif defined(IS_WINDOWS) + if (pid != 0) { + HWND hwnd = getHwnd(pid, isPid); + + // SendMessage(hwnd, down, value, 0); + PostMessageW(hwnd, WM_CHAR, value, 0); + return; + } + INPUT input[2]; memset(input, 0, sizeof(input)); @@ -307,53 +324,36 @@ void unicodeType(const unsigned value){ SendInput(2, input, sizeof(INPUT)); #elif defined(USE_X11) toggleUniKey(value, true); + microsleep(5.0); toggleUniKey(value, false); #endif } -void typeStringDelayed(const char *str, const unsigned cpm){ - - /* Characters per second */ - const double cps = (double)cpm / 60.0; - - /* Average milli-seconds per character */ - const double mspc = (cps == 0.0) ? 0.0 : 1000.0 / cps; - - unsigned long n; - unsigned short c; - unsigned short c1; - unsigned short c2; - unsigned short c3; - - while (*str != '\0') { - c = *str++; - - // warning, the following utf8 decoder - // doesn't perform validation - if (c <= 0x7F) { - // 0xxxxxxx one byte - n = c; - } else if ((c & 0xE0) == 0xC0) { - // 110xxxxx two bytes - c1 = (*str++) & 0x3F; - n = ((c & 0x1F) << 6) | c1; - } else if ((c & 0xF0) == 0xE0) { - // 1110xxxx three bytes - c1 = (*str++) & 0x3F; - c2 = (*str++) & 0x3F; - n = ((c & 0x0F) << 12) | (c1 << 6) | c2; - } else if ((c & 0xF8) == 0xF0) { - // 11110xxx four bytes - c1 = (*str++) & 0x3F; - c2 = (*str++) & 0x3F; - c3 = (*str++) & 0x3F; - n = ((c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3; - } +#if defined(USE_X11) + int input_utf(const char *utf) { + Display *dpy = XOpenDisplay(NULL); + KeySym sym = XStringToKeysym(utf); + // KeySym sym = XKeycodeToKeysym(dpy, utf); + + int min, max, numcodes; + XDisplayKeycodes(dpy, &min, &max); + KeySym *keysym; + keysym = XGetKeyboardMapping(dpy, min, max-min+1, &numcodes); + keysym[(max-min-1)*numcodes] = sym; + XChangeKeyboardMapping(dpy, min, numcodes, keysym, (max-min)); + XFree(keysym); + XFlush(dpy); - unicodeType(n); + KeyCode code = XKeysymToKeycode(dpy, sym); + XTestFakeKeyEvent(dpy, code, True, 1); + XTestFakeKeyEvent(dpy, code, False, 1); - if (mspc > 0) { - microsleep(mspc + (DEADBEEF_UNIFORM(0.0, 0.5))); - } + XFlush(dpy); + XCloseDisplay(dpy); + return 0; + } +#else + int input_utf(const char *utf){ + return 0; } -} \ No newline at end of file +#endif \ No newline at end of file diff --git a/keycode.go b/keycode.go index 82db599f..a26aa67e 100644 --- a/keycode.go +++ b/keycode.go @@ -3,110 +3,35 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package robotgo +import ( + "github.com/vcaesar/keycode" +) + type uMap map[string]uint16 // MouseMap robotgo hook mouse's code map -var MouseMap = uMap{ - "left": 1, - "right": 2, - "center": 3, - "wheelDown": 4, - "wheelUp": 5, - "wheelLeft": 6, - "wheelRight": 7, -} +var MouseMap = keycode.MouseMap + +const ( + // Mleft mouse left button + Mleft = "left" + Mright = "right" + Center = "center" + WheelDown = "wheelDown" + WheelUp = "wheelUp" + WheelLeft = "wheelLeft" + WheelRight = "wheelRight" +) // Keycode robotgo hook key's code map -var Keycode = uMap{ - "`": 41, - "1": 2, - "2": 3, - "3": 4, - "4": 5, - "5": 6, - "6": 7, - "7": 8, - "8": 9, - "9": 10, - "0": 11, - "-": 12, - "+": 13, - // - "q": 16, - "w": 17, - "e": 18, - "r": 19, - "t": 20, - "y": 21, - "u": 22, - "i": 23, - "o": 24, - "p": 25, - "[": 26, - "]": 27, - "\\": 43, - // - "a": 30, - "s": 31, - "d": 32, - "f": 33, - "g": 34, - "h": 35, - "j": 36, - "k": 37, - "l": 38, - ";": 39, - "'": 40, - // - "z": 44, - "x": 45, - "c": 46, - "v": 47, - "b": 48, - "n": 49, - "m": 50, - ",": 51, - ".": 52, - "/": 53, - // - "f1": 59, - "f2": 60, - "f3": 61, - "f4": 62, - "f5": 63, - "f6": 64, - "f7": 65, - "f8": 66, - "f9": 67, - "f10": 68, - "f11": 69, - "f12": 70, - // more - "esc": 1, - "delete": 14, - "tab": 15, - "ctrl": 29, - "control": 29, - "alt": 56, - "space": 57, - "shift": 42, - "rshift": 54, - "enter": 28, - // - "cmd": 3675, - "command": 3675, - "rcmd": 3676, - "ralt": 3640, - // - "up": 57416, - "down": 57424, - "left": 57419, - "right": 57421, -} +var Keycode = keycode.Keycode + +// Special is the special key map +var Special = keycode.Special diff --git a/mouse/goMouse.h b/mouse/goMouse.h deleted file mode 100644 index 9b7fc61f..00000000 --- a/mouse/goMouse.h +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#include "../base/types.h" -#include "mouse_c.h" - -// Global delays. -int mouseDelay = 0; -// int keyboardDelay = 10; - - -// int CheckMouseButton(const char * const b, -// MMMouseButton * const button){ -// if (!button) return -1; - -// if (strcmp(b, "left") == 0) { -// *button = LEFT_BUTTON; -// } -// else if (strcmp(b, "right") == 0) { -// *button = RIGHT_BUTTON; -// } -// else if (strcmp(b, "middle") == 0) { -// *button = CENTER_BUTTON; -// } else { -// return -2; -// } - -// return 0; -// } - -int move_mouse(int32_t x, int32_t y){ - MMPointInt32 point; - // int x = 103; - // int y = 104; - point = MMPointInt32Make(x, y); - moveMouse(point); - - return 0; -} - - -int drag_mouse(int32_t x, int32_t y, MMMouseButton button){ - // const size_t x = 10; - // const size_t y = 20; - // MMMouseButton button = LEFT_BUTTON; - - MMPointInt32 point; - point = MMPointInt32Make(x, y); - dragMouse(point, button); - microsleep(mouseDelay); - - // printf("%s\n", "gyp-----"); - return 0; -} - -bool move_mouse_smooth(int32_t x, int32_t y, double lowSpeed, - double highSpeed, int msDelay){ - MMPointInt32 point; - point = MMPointInt32Make(x, y); - - bool cbool = smoothlyMoveMouse(point, lowSpeed, highSpeed); - microsleep(msDelay); - - return cbool; -} - -MMPointInt32 get_mouse_pos(){ - MMPointInt32 pos = getMousePos(); - - // Return object with .x and .y. - // printf("%zu\n%zu\n", pos.x, pos.y ); - return pos; -} - -int mouse_click(MMMouseButton button, bool doubleC){ - // MMMouseButton button = LEFT_BUTTON; - // bool doubleC = false; - if (!doubleC) { - clickMouse(button); - } else { - doubleClick(button); - } - - microsleep(mouseDelay); - - return 0; -} - -int mouse_toggle(char* d, MMMouseButton button){ - // MMMouseButton button = LEFT_BUTTON; - bool down = false; - if (strcmp(d, "down") == 0) { - down = true; - } else if (strcmp(d, "up") == 0) { - down = false; - } else { - return 1; - } - - toggleMouse(down, button); - microsleep(mouseDelay); - - return 0; -} - -int set_mouse_delay(size_t val){ - // int val = 10; - mouseDelay = val; - - return 0; -} - -int scroll(int x, int y, int msDelay){ - scrollMouseXY(x, y); - microsleep(msDelay); - - return 0; -} - -int scroll_mouse(size_t scrollMagnitude, char *s){ - // int scrollMagnitude = 20; - MMMouseWheelDirection scrollDirection; - - if (strcmp(s, "up") == 0) { - scrollDirection = DIRECTION_UP; - } else if (strcmp(s, "down") == 0) { - scrollDirection = DIRECTION_DOWN; - } else { - // return "Invalid scroll direction specified."; - return 1; - } - - scrollMouse(scrollMagnitude, scrollDirection); - microsleep(mouseDelay); - - return 0; -} diff --git a/mouse/mouse.go b/mouse/mouse.go new file mode 100644 index 00000000..74e8955d --- /dev/null +++ b/mouse/mouse.go @@ -0,0 +1,11 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package mouse diff --git a/mouse/mouse.h b/mouse/mouse.h index 7dff62a8..52aba723 100644 --- a/mouse/mouse.h +++ b/mouse/mouse.h @@ -4,103 +4,44 @@ #include "../base/os.h" #include "../base/types.h" - -#if defined(_MSC_VER) - #include "../base/ms_stdbool.h" -#else - #include -#endif - -#ifdef __cplusplus -// #ifdefined(__cplusplus)||defined(c_plusplus) -extern "C" -{ -#endif +#include #if defined(IS_MACOSX) - - // #include #include - // #include - typedef enum { + typedef enum { LEFT_BUTTON = kCGMouseButtonLeft, RIGHT_BUTTON = kCGMouseButtonRight, - CENTER_BUTTON = kCGMouseButtonCenter + CENTER_BUTTON = kCGMouseButtonCenter, + WheelDown = 4, + WheelUp = 5, + WheelLeft = 6, + WheelRight = 7, } MMMouseButton; - #elif defined(USE_X11) - enum _MMMouseButton { LEFT_BUTTON = 1, CENTER_BUTTON = 2, - RIGHT_BUTTON = 3 + RIGHT_BUTTON = 3, + WheelDown = 4, + WheelUp = 5, + WheelLeft = 6, + WheelRight = 7, }; typedef unsigned int MMMouseButton; - #elif defined(IS_WINDOWS) - enum _MMMouseButton { LEFT_BUTTON = 1, CENTER_BUTTON = 2, - RIGHT_BUTTON = 3 + RIGHT_BUTTON = 3, + WheelDown = 4, + WheelUp = 5, + WheelLeft = 6, + WheelRight = 7, }; typedef unsigned int MMMouseButton; - #else #error "No mouse button constants set for platform" #endif -#define MMMouseButtonIsValid(button) \ - (button == LEFT_BUTTON || button == RIGHT_BUTTON || \ - button == CENTER_BUTTON) - -enum __MMMouseWheelDirection -{ - DIRECTION_DOWN = -1, - DIRECTION_UP = 1 -}; -typedef int MMMouseWheelDirection; - -/* Immediately moves the mouse to the given point on-screen. - * It is up to the caller to ensure that this point is within the - * screen boundaries. */ -void moveMouse(MMPointInt32 point); - -/* Like moveMouse, moves the mouse to the given point on-screen, but marks - * the event as the mouse being dragged on platforms where it is supported. - * It is up to the caller to ensure that this point is within the screen - * boundaries. */ -void dragMouse(MMPointInt32 point, const MMMouseButton button); - -/* Smoothly moves the mouse from the current position to the given point. - * deadbeef_srand() should be called before using this function. - * - * Returns false if unsuccessful (i.e. a point was hit that is outside of the - * screen boundaries), or true if successful. */ -bool smoothlyMoveMouse(MMPointInt32 endPoint, double lowSpeed, double highSpeed); -// bool smoothlyMoveMouse(MMPoint point); - -/* Returns the coordinates of the mouse on the current screen. */ -MMPointInt32 getMousePos(void); - -/* Holds down or releases the mouse with the given button in the current - * position. */ -void toggleMouse(bool down, MMMouseButton button); - -/* Clicks the mouse with the given button in the current position. */ -void clickMouse(MMMouseButton button); - -/* Double clicks the mouse with the given button. */ -void doubleClick(MMMouseButton button); - -/* Scrolls the mouse in the stated direction. - * TODO: Add a smoothly scroll mouse next. */ -void scrollMouse(int scrollMagnitude, MMMouseWheelDirection scrollDirection); - -//#ifdefined(__cplusplus)||defined(c_plusplus) -#ifdef __cplusplus -} -#endif - #endif /* MOUSE_H */ \ No newline at end of file diff --git a/mouse/mouse_c.h b/mouse/mouse_c.h index 245f6186..f9697a95 100644 --- a/mouse/mouse_c.h +++ b/mouse/mouse_c.h @@ -1,12 +1,8 @@ #include "mouse.h" -// #include "../screen/screen.h" -// #include "../screen/screen_c.h" -#include "../base/deadbeef_rand_c.h" -// #include "../deadbeef_rand.h" +#include "../base/deadbeef_rand.h" #include "../base/microsleep.h" #include /* For floor() */ - #if defined(IS_MACOSX) // #include #include @@ -15,136 +11,115 @@ #include #include #include - // #include "../base/xdisplay_c.h" -#endif - -#if !defined(M_SQRT2) - #define M_SQRT2 1.4142135623730950488016887 /* Fix for MSVC. */ #endif /* Some convenience macros for converting our enums to the system API types. */ #if defined(IS_MACOSX) + CGEventType MMMouseDownToCGEventType(MMMouseButton button) { + if (button == LEFT_BUTTON) { + return kCGEventLeftMouseDown; + } + if (button == RIGHT_BUTTON) { + return kCGEventRightMouseDown; + } + return kCGEventOtherMouseDown; + } -#define MMMouseToCGEventType(down, button) \ - (down ? MMMouseDownToCGEventType(button) : MMMouseUpToCGEventType(button)) - -#define MMMouseDownToCGEventType(button) \ - ((button) == (LEFT_BUTTON) ? kCGEventLeftMouseDown \ - : ((button) == RIGHT_BUTTON ? kCGEventRightMouseDown \ - : kCGEventOtherMouseDown)) + CGEventType MMMouseUpToCGEventType(MMMouseButton button) { + if (button == LEFT_BUTTON) { return kCGEventLeftMouseUp; } + if (button == RIGHT_BUTTON) { return kCGEventRightMouseUp; } + return kCGEventOtherMouseUp; + } -#define MMMouseUpToCGEventType(button) \ - ((button) == LEFT_BUTTON ? kCGEventLeftMouseUp \ - : ((button) == RIGHT_BUTTON ? kCGEventRightMouseUp \ - : kCGEventOtherMouseUp)) + CGEventType MMMouseDragToCGEventType(MMMouseButton button) { + if (button == LEFT_BUTTON) { return kCGEventLeftMouseDragged; } + if (button == RIGHT_BUTTON) { return kCGEventRightMouseDragged; } + return kCGEventOtherMouseDragged; + } -#define MMMouseDragToCGEventType(button) \ - ((button) == LEFT_BUTTON ? kCGEventLeftMouseDragged \ - : ((button) == RIGHT_BUTTON ? kCGEventRightMouseDragged \ - : kCGEventOtherMouseDragged)) + CGEventType MMMouseToCGEventType(bool down, MMMouseButton button) { + if (down) { return MMMouseDownToCGEventType(button); } + return MMMouseUpToCGEventType(button); + } #elif defined(IS_WINDOWS) + + DWORD MMMouseUpToMEventF(MMMouseButton button) { + if (button == LEFT_BUTTON) { return MOUSEEVENTF_LEFTUP; } + if (button == RIGHT_BUTTON) { return MOUSEEVENTF_RIGHTUP; } + return MOUSEEVENTF_MIDDLEUP; + } -#define MMMouseToMEventF(down, button) \ - (down ? MMMouseDownToMEventF(button) : MMMouseUpToMEventF(button)) - -#define MMMouseUpToMEventF(button) \ - ((button) == LEFT_BUTTON ? MOUSEEVENTF_LEFTUP \ - : ((button) == RIGHT_BUTTON ? MOUSEEVENTF_RIGHTUP \ - : MOUSEEVENTF_MIDDLEUP)) - -#define MMMouseDownToMEventF(button) \ - ((button) == LEFT_BUTTON ? MOUSEEVENTF_LEFTDOWN \ - : ((button) == RIGHT_BUTTON ? MOUSEEVENTF_RIGHTDOWN \ - : MOUSEEVENTF_MIDDLEDOWN)) + DWORD MMMouseDownToMEventF(MMMouseButton button) { + if (button == LEFT_BUTTON) { return MOUSEEVENTF_LEFTDOWN; } + if (button == RIGHT_BUTTON) { return MOUSEEVENTF_RIGHTDOWN; } + return MOUSEEVENTF_MIDDLEDOWN; + } + DWORD MMMouseToMEventF(bool down, MMMouseButton button) { + if (down) { return MMMouseDownToMEventF(button); } + return MMMouseUpToMEventF(button); + } #endif #if defined(IS_MACOSX) -/** - * Calculate the delta for a mouse move and add them to the event. - * @param event The mouse move event (by ref). - * @param point The new mouse x and y. - */ -void calculateDeltas(CGEventRef *event, MMPointInt32 point){ - /** - * The next few lines are a workaround for games not detecting mouse moves. - * See this issue for more information: - * https://github.com/go-vgo/robotgo/issues/159 - */ - CGEventRef get = CGEventCreate(NULL); - CGPoint mouse = CGEventGetLocation(get); - - // Calculate the deltas. - int64_t deltaX = point.x - mouse.x; - int64_t deltaY = point.y - mouse.y; - - CGEventSetIntegerValueField(*event, kCGMouseEventDeltaX, deltaX); - CGEventSetIntegerValueField(*event, kCGMouseEventDeltaY, deltaY); - - CFRelease(get); -} -#endif + /* Calculate the delta for a mouse move and add them to the event. */ + void calculateDeltas(CGEventRef *event, MMPointInt32 point) { + /* The next few lines are a workaround for games not detecting mouse moves. */ + CGEventRef get = CGEventCreate(NULL); + CGPoint mouse = CGEventGetLocation(get); + + // Calculate the deltas. + int64_t deltaX = point.x - mouse.x; + int64_t deltaY = point.y - mouse.y; + + CGEventSetIntegerValueField(*event, kCGMouseEventDeltaX, deltaX); + CGEventSetIntegerValueField(*event, kCGMouseEventDeltaY, deltaY); + CFRelease(get); + } +#endif -/** - * Move the mouse to a specific point. - * @param point The coordinates to move the mouse to (x, y). - */ +/* Move the mouse to a specific point. */ void moveMouse(MMPointInt32 point){ #if defined(IS_MACOSX) - CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, - CGPointFromMMPointInt32(point), - kCGMouseButtonLeft); + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef move = CGEventCreateMouseEvent(source, kCGEventMouseMoved, + CGPointFromMMPointInt32(point), kCGMouseButtonLeft); calculateDeltas(&move, point); - CGEventPost(kCGSessionEventTap, move); + CGEventPost(kCGHIDEventTap, move); CFRelease(move); + CFRelease(source); #elif defined(USE_X11) Display *display = XGetMainDisplay(); - XWarpPointer(display, None, DefaultRootWindow(display), - 0, 0, 0, 0, point.x, point.y); + XWarpPointer(display, None, DefaultRootWindow(display), 0, 0, 0, 0, point.x, point.y); XSync(display, false); #elif defined(IS_WINDOWS) - // Mouse motion is now done using SendInput with MOUSEINPUT. - // We use Absolute mouse positioning - #define MOUSE_COORD_TO_ABS(coord, width_or_height) ( \ - ((65536 * coord) / width_or_height) + (coord < 0 ? -1 : 1)) - - point.x = MOUSE_COORD_TO_ABS(point.x, GetSystemMetrics(SM_CXSCREEN)); - point.y = MOUSE_COORD_TO_ABS(point.y, GetSystemMetrics(SM_CYSCREEN)); - - INPUT mouseInput; - mouseInput.type = INPUT_MOUSE; - mouseInput.mi.dx = point.x; - mouseInput.mi.dy = point.y; - mouseInput.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; - mouseInput.mi.time = 0; // System will provide the timestamp - mouseInput.mi.dwExtraInfo = 0; - mouseInput.mi.mouseData = 0; - SendInput(1, &mouseInput, sizeof(mouseInput)); - + SetCursorPos(point.x, point.y); #endif } void dragMouse(MMPointInt32 point, const MMMouseButton button){ #if defined(IS_MACOSX) const CGEventType dragType = MMMouseDragToCGEventType(button); - CGEventRef drag = CGEventCreateMouseEvent(NULL, dragType, - CGPointFromMMPoint(point), (CGMouseButton)button); + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef drag = CGEventCreateMouseEvent(source, dragType, + CGPointFromMMPointInt32(point), (CGMouseButton)button); calculateDeltas(&drag, point); - CGEventPost(kCGSessionEventTap, drag); + CGEventPost(kCGHIDEventTap, drag); CFRelease(drag); + CFRelease(source); #else moveMouse(point); #endif } -MMPointInt32 getMousePos(){ +MMPointInt32 location() { #if defined(IS_MACOSX) CGEventRef event = CGEventCreate(NULL); CGPoint point = CGEventGetLocation(event); @@ -152,45 +127,40 @@ MMPointInt32 getMousePos(){ return MMPointInt32FromCGPoint(point); #elif defined(USE_X11) - int x, y; /* This is all we care about. Seriously. */ - Window garb1, garb2; /* Why you can't specify NULL as a parameter */ - int garb_x, garb_y; /* is beyond me. */ + int x, y; /* This is all we care about. Seriously. */ + Window garb1, garb2; /* Why you can't specify NULL as a parameter */ + int garb_x, garb_y; /* is beyond me. */ unsigned int more_garbage; Display *display = XGetMainDisplay(); - XQueryPointer(display, XDefaultRootWindow(display), &garb1, &garb2, - &x, &y, &garb_x, &garb_y, &more_garbage); + XQueryPointer(display, XDefaultRootWindow(display), &garb1, &garb2, &x, &y, + &garb_x, &garb_y, &more_garbage); return MMPointInt32Make(x, y); #elif defined(IS_WINDOWS) POINT point; GetCursorPos(&point); - return MMPointInt32FromPOINT(point); #endif } -/** - * Press down a button, or release it. - * @param down True for down, false for up. - * @param button The button to press down or release. - */ -void toggleMouse(bool down, MMMouseButton button){ +/* Press down a button, or release it. */ +void toggleMouse(bool down, MMMouseButton button) { #if defined(IS_MACOSX) - const CGPoint currentPos = CGPointFromMMPoint(getMousePos()); + const CGPoint currentPos = CGPointFromMMPointInt32(location()); const CGEventType mouseType = MMMouseToCGEventType(down, button); - CGEventRef event = CGEventCreateMouseEvent(NULL, - mouseType, currentPos, (CGMouseButton)button); + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef event = CGEventCreateMouseEvent(source, mouseType, currentPos, (CGMouseButton)button); - CGEventPost(kCGSessionEventTap, event); + CGEventPost(kCGHIDEventTap, event); CFRelease(event); + CFRelease(source); #elif defined(USE_X11) Display *display = XGetMainDisplay(); XTestFakeButtonEvent(display, button, down ? True : False, CurrentTime); XSync(display, false); #elif defined(IS_WINDOWS) // mouse_event(MMMouseToMEventF(down, button), 0, 0, 0, 0); - INPUT mouseInput; mouseInput.type = INPUT_MOUSE; @@ -206,145 +176,62 @@ void toggleMouse(bool down, MMMouseButton button){ void clickMouse(MMMouseButton button){ toggleMouse(true, button); + microsleep(5.0); toggleMouse(false, button); } -/** - * Special function for sending double clicks, needed for Mac OS X. - * @param button Button to click. - */ +/* Special function for sending double clicks, needed for MacOS. */ void doubleClick(MMMouseButton button){ #if defined(IS_MACOSX) - /* Double click for Mac. */ - const CGPoint currentPos = CGPointFromMMPoint(getMousePos()); + const CGPoint currentPos = CGPointFromMMPointInt32(location()); const CGEventType mouseTypeDown = MMMouseToCGEventType(true, button); const CGEventType mouseTypeUP = MMMouseToCGEventType(false, button); - CGEventRef event = CGEventCreateMouseEvent( - NULL, mouseTypeDown, currentPos, kCGMouseButtonLeft); + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef event = CGEventCreateMouseEvent(source, mouseTypeDown, currentPos, kCGMouseButtonLeft); /* Set event to double click. */ CGEventSetIntegerValueField(event, kCGMouseEventClickState, 2); - CGEventPost(kCGHIDEventTap, event); CGEventSetType(event, mouseTypeUP); CGEventPost(kCGHIDEventTap, event); CFRelease(event); - + CFRelease(source); #else - /* Double click for everything else. */ clickMouse(button); microsleep(200); clickMouse(button); - - #endif -} - -/** - * Function used to scroll the screen in the required direction. - * This uses the magnitude to scroll the required amount in the direction. - * TODO Requires further fine tuning based on the requirements. - */ -void scrollMouse(int scrollMagnitude, MMMouseWheelDirection scrollDirection){ - #if defined(IS_WINDOWS) - // Fix for #97 https://github.com/go-vgo/robotgo/issues/97, - // C89 needs variables declared on top of functions (mouseScrollInput) - INPUT mouseScrollInput; - #endif - - /* Direction should only be considered based on the scrollDirection. This - * Should not interfere. */ - int cleanScrollMagnitude = abs(scrollMagnitude); - if (!(scrollDirection == DIRECTION_UP || scrollDirection == DIRECTION_DOWN)) { - return; - } - - /* Set up the OS specific solution */ - #if defined(__APPLE__) - - CGWheelCount wheel = 1; - CGEventRef event; - - /* Make scroll magnitude negative if we're scrolling down. */ - cleanScrollMagnitude = cleanScrollMagnitude * scrollDirection; - - event = CGEventCreateScrollWheelEvent(NULL, - kCGScrollEventUnitLine, wheel, cleanScrollMagnitude, 0); - - CGEventPost(kCGHIDEventTap, event); - - #elif defined(USE_X11) - - int x; - int dir = 4; /* Button 4 is up, 5 is down. */ - Display *display = XGetMainDisplay(); - - if (scrollDirection == DIRECTION_DOWN) { - dir = 5; - } - - for (x = 0; x < cleanScrollMagnitude; x++) { - XTestFakeButtonEvent(display, dir, 1, CurrentTime); - XTestFakeButtonEvent(display, dir, 0, CurrentTime); - } - - XSync(display, false); - - #elif defined(IS_WINDOWS) - - mouseScrollInput.type = INPUT_MOUSE; - mouseScrollInput.mi.dx = 0; - mouseScrollInput.mi.dy = 0; - mouseScrollInput.mi.dwFlags = MOUSEEVENTF_WHEEL; - mouseScrollInput.mi.time = 0; - mouseScrollInput.mi.dwExtraInfo = 0; - mouseScrollInput.mi.mouseData = WHEEL_DELTA * scrollDirection * cleanScrollMagnitude; - - SendInput(1, &mouseScrollInput, sizeof(mouseScrollInput)); - #endif } -void scrollMouseXY(int x, int y){ +/* Function used to scroll the screen in the required direction. */ +void scrollMouseXY(int x, int y) { #if defined(IS_WINDOWS) - // Fix for #97, - // C89 needs variables declared on top of functions (mouseScrollInput) + // Fix for #97, C89 needs variables declared on top of functions (mouseScrollInput) INPUT mouseScrollInputH; INPUT mouseScrollInputV; #endif - /* Direction should only be considered based on the scrollDirection. This - * Should not interfere. */ - - /* Set up the OS specific solution */ - #if defined(__APPLE__) - - CGEventRef event; - - event = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 2, y, x); + #if defined(IS_MACOSX) + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef event = CGEventCreateScrollWheelEvent(source, kCGScrollEventUnitPixel, 2, y, x); CGEventPost(kCGHIDEventTap, event); CFRelease(event); - + CFRelease(source); #elif defined(USE_X11) - int ydir = 4; /* Button 4 is up, 5 is down. */ int xdir = 6; Display *display = XGetMainDisplay(); - if (y < 0) { - ydir = 5; - } - if (x < 0) { - xdir = 7; - } + if (y < 0) { ydir = 5; } + if (x < 0) { xdir = 7; } - int xi; - int yi; + int xi; int yi; for (xi = 0; xi < abs(x); xi++) { XTestFakeButtonEvent(display, xdir, 1, CurrentTime); XTestFakeButtonEvent(display, xdir, 0, CurrentTime); @@ -355,9 +242,7 @@ void scrollMouseXY(int x, int y){ } XSync(display, false); - #elif defined(IS_WINDOWS) - mouseScrollInputH.type = INPUT_MOUSE; mouseScrollInputH.mi.dx = 0; mouseScrollInputH.mi.dy = 0; @@ -379,16 +264,11 @@ void scrollMouseXY(int x, int y){ #endif } -/* - * A crude, fast hypot() approximation to get around the fact that hypot() is - * not a standard ANSI C function. - * - * It is not particularly accurate but that does not matter for our use case. - * - * Taken from this StackOverflow answer: - * http://stackoverflow.com/questions/3506404/fast-hypotenuse-algorithm-for-embedded-processor#3507882 - * - */ +/* A crude, fast hypot() approximation to get around the fact that hypot() is not a standard ANSI C function. */ +#if !defined(M_SQRT2) + #define M_SQRT2 1.4142135623730950488016887 /* Fix for MSVC. */ +#endif + static double crude_hypot(double x, double y){ double big = fabs(x); /* max(|x|, |y|) */ double small = fabs(y); /* min(|x|, |y|) */ @@ -403,15 +283,12 @@ static double crude_hypot(double x, double y){ } bool smoothlyMoveMouse(MMPointInt32 endPoint, double lowSpeed, double highSpeed){ - MMPointInt32 pos = getMousePos(); - MMSizeInt32 screenSize = getMainDisplaySize(); + MMPointInt32 pos = location(); + // MMSizeInt32 screenSize = getMainDisplaySize(); double velo_x = 0.0, velo_y = 0.0; double distance; - while ((distance = - crude_hypot((double)pos.x - endPoint.x, (double)pos.y - endPoint.y) - ) > 1.0) { - + while ((distance =crude_hypot((double)pos.x - endPoint.x, (double)pos.y - endPoint.y)) > 1.0) { double gravity = DEADBEEF_UNIFORM(5.0, 500.0); // double gravity = DEADBEEF_UNIFORM(lowSpeed, highSpeed); double veloDistance; @@ -426,12 +303,10 @@ bool smoothlyMoveMouse(MMPointInt32 endPoint, double lowSpeed, double highSpeed) pos.x += floor(velo_x + 0.5); pos.y += floor(velo_y + 0.5); - /* Make sure we are in the screen boundaries! - * (Strange things will happen if we are not.) */ - if (pos.x >= screenSize.w || pos.y >= screenSize.h) { - return false; - } - + /* Make sure we are in the screen boundaries! (Strange things will happen if we are not.) */ + // if (pos.x >= screenSize.w || pos.y >= screenSize.h) { + // return false; + // } moveMouse(pos); /* Wait 1 - 3 milliseconds. */ diff --git a/mouse/mouse_darwin.go b/mouse/mouse_darwin.go new file mode 100644 index 00000000..de4c9b45 --- /dev/null +++ b/mouse/mouse_darwin.go @@ -0,0 +1,4 @@ +//go:build darwin +// +build darwin + +package mouse diff --git a/mouse/mouse_windows.go b/mouse/mouse_windows.go new file mode 100644 index 00000000..588de029 --- /dev/null +++ b/mouse/mouse_windows.go @@ -0,0 +1,4 @@ +//go:build windows +// +build windows + +package mouse diff --git a/mouse/mouse_x11.go b/mouse/mouse_x11.go new file mode 100644 index 00000000..3b452a3b --- /dev/null +++ b/mouse/mouse_x11.go @@ -0,0 +1,4 @@ +//go:build !darwin && !windows +// +build !darwin,!windows + +package mouse diff --git a/ps.go b/ps.go index e6eddc12..13bf8dee 100644 --- a/ps.go +++ b/ps.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package robotgo @@ -14,17 +14,17 @@ import ps "github.com/vcaesar/gops" // Nps process struct type Nps struct { - Pid int32 + Pid int Name string } // Pids get the all process id -func Pids() ([]int32, error) { +func Pids() ([]int, error) { return ps.Pids() } // PidExists determine whether the process exists -func PidExists(pid int32) (bool, error) { +func PidExists(pid int) (bool, error) { return ps.PidExists(pid) } @@ -45,7 +45,7 @@ func Process() ([]Nps, error) { } // FindName find the process name by the process id -func FindName(pid int32) (string, error) { +func FindName(pid int) (string, error) { return ps.FindName(pid) } @@ -57,16 +57,21 @@ func FindNames() ([]string, error) { // FindIds finds the all processes named with a subset // of "name" (case insensitive), // return matched IDs. -func FindIds(name string) ([]int32, error) { +func FindIds(name string) ([]int, error) { return ps.FindIds(name) } // FindPath find the process path by the process pid -func FindPath(pid int32) (string, error) { +func FindPath(pid int) (string, error) { return ps.FindPath(pid) } +// Run run a cmd shell +func Run(path string) ([]byte, error) { + return ps.Run(path) +} + // Kill kill the process by PID -func Kill(pid int32) error { +func Kill(pid int) error { return ps.Kill(pid) } diff --git a/robot_info_test.go b/robot_info_test.go index 91d9a472..8f890894 100644 --- a/robot_info_test.go +++ b/robot_info_test.go @@ -3,9 +3,9 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. package robotgo_test @@ -29,10 +29,27 @@ func TestGetVer(t *testing.T) { func TestGetScreenSize(t *testing.T) { x, y := robotgo.GetScreenSize() - log.Println("GetScreenSize: ", x, y) + log.Println("Get screen size: ", x, y) + + rect := robotgo.GetScreenRect() + fmt.Println("Get screen rect: ", rect) + + x, y = robotgo.Location() + fmt.Println("Get location: ", x, y) } func TestGetSysScale(t *testing.T) { s := robotgo.SysScale() log.Println("SysScale: ", s) + + f := robotgo.ScaleF() + log.Println("scale: ", f) +} + +func TestGetTitle(t *testing.T) { + // just exercise the function, it used to crash with a segfault + "Maximum + // number of clients reached" + for i := 0; i < 128; i++ { + robotgo.GetTitle() + } } diff --git a/robotgo.go b/robotgo.go index ca9098c6..e521e839 100644 --- a/robotgo.go +++ b/robotgo.go @@ -3,73 +3,65 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. /* - Package robotgo Go native cross-platform system automation. Please make sure Golang, GCC is installed correctly before installing RobotGo; See Requirements: + https://github.com/go-vgo/robotgo#requirements Installation: + +With Go module support (Go 1.11+), just import: + + import "github.com/go-vgo/robotgo" + +Otherwise, to install the robotgo package, run the command: + go get -u github.com/go-vgo/robotgo */ package robotgo /* -//#if defined(IS_MACOSX) - #cgo darwin CFLAGS: -x objective-c -Wno-deprecated-declarations - #cgo darwin LDFLAGS: -framework Cocoa -framework OpenGL -framework IOKit - #cgo darwin LDFLAGS: -framework Carbon -framework CoreFoundation - #cgo darwin LDFLAGS:-L${SRCDIR}/cdeps/mac -lpng -lz -//#elif defined(USE_X11) - // Drop -std=c11 - #cgo linux CFLAGS: -I/usr/src - #cgo linux LDFLAGS: -L/usr/src -lpng -lz -lX11 -lXtst -lm - // #cgo linux LDFLAGS: -lX11-xcb -lxcb -lxcb-xkb -lxkbcommon -lxkbcommon-x11 -//#endif - // #cgo windows LDFLAGS: -lgdi32 -luser32 -lpng -lz - #cgo windows LDFLAGS: -lgdi32 -luser32 - #cgo windows,amd64 LDFLAGS: -L${SRCDIR}/cdeps/win64 -lpng -lz - #cgo windows,386 LDFLAGS: -L${SRCDIR}/cdeps/win32 -lpng -lz -// #include +#cgo darwin CFLAGS: -x objective-c -Wno-deprecated-declarations +#cgo darwin LDFLAGS: -framework Cocoa -framework CoreFoundation -framework IOKit +#cgo darwin LDFLAGS: -framework Carbon -framework OpenGL +// +#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 140400 +#cgo darwin LDFLAGS: -framework ScreenCaptureKit +#endif + +#cgo linux CFLAGS: -I/usr/src +#cgo linux LDFLAGS: -L/usr/src -lm -lX11 -lXtst + +#cgo windows LDFLAGS: -lgdi32 -luser32 +// #include "screen/goScreen.h" -#include "mouse/goMouse.h" -#include "key/goKey.h" -#include "bitmap/goBitmap.h" -//#include "event/goEvent.h" +#include "mouse/mouse_c.h" #include "window/goWindow.h" */ import "C" import ( - // "fmt" + "errors" "image" - // "os" - "reflect" "runtime" - "strconv" - "strings" "time" "unsafe" - // "syscall" - "os/exec" - - "github.com/go-vgo/robotgo/clipboard" - "github.com/vcaesar/imgo" "github.com/vcaesar/tt" ) const ( // Version get the robotgo version - Version = "v0.90.0.1050, MT. Rainier!" + Version = "v1.00.0.1189, MT. Baker!" ) // GetVersion get the robotgo version @@ -77,6 +69,21 @@ func GetVersion() string { return Version } +var ( + // MouseSleep set the mouse default millisecond sleep time + MouseSleep = 0 + // KeySleep set the key default millisecond sleep time + KeySleep = 10 + + // DisplayID set the screen display id + DisplayID = -1 + + // NotPid used the hwnd not pid in windows + NotPid bool + // Scale option the os screen scale + Scale bool +) + type ( // Map a map[string]interface{} Map map[string]interface{} @@ -84,22 +91,39 @@ type ( CHex C.MMRGBHex // CBitmap define CBitmap as C.MMBitmapRef type CBitmap C.MMBitmapRef + // Handle define window Handle as C.MData type + Handle C.MData ) -// Bitmap is Bitmap struct +// Bitmap define the go Bitmap struct +// +// The common type conversion of bitmap: +// +// https://github.com/go-vgo/robotgo/blob/master/docs/keys.md#type-conversion type Bitmap struct { ImgBuf *uint8 - Width int - Height int + Width, Height int + Bytewidth int BitsPixel uint8 BytesPerPixel uint8 } -// MPoint is MPoint struct -type MPoint struct { - x int - y int +// Point is point struct +type Point struct { + X int + Y int +} + +// Size is size structure +type Size struct { + W, H int +} + +// Rect is rect structure +type Rect struct { + Point + Size } // Try handler(err) @@ -122,12 +146,14 @@ func Sleep(tm int) { time.Sleep(time.Duration(tm) * time.Second) } +// Deprecated: use the MilliSleep(), +// // MicroSleep time C.microsleep(tm) func MicroSleep(tm float64) { C.microsleep(C.double(tm)) } -// GoString teans C.char to string +// GoString trans C.char to string func GoString(char *C.char) string { return C.GoString(char) } @@ -157,7 +183,7 @@ func U32ToHex(hex C.uint32_t) C.MMRGBHex { return C.MMRGBHex(hex) } -// U8ToHex teans *C.uint8_t to C.MMRGBHex +// U8ToHex trans *C.uint8_t to C.MMRGBHex func U8ToHex(hex *C.uint8_t) C.MMRGBHex { return C.MMRGBHex(*hex) } @@ -171,6 +197,11 @@ func PadHex(hex C.MMRGBHex) string { return gcolor } +// PadHexs trans CHex to string +func PadHexs(hex CHex) string { + return PadHex(C.MMRGBHex(hex)) +} + // HexToRgb trans hex to rgb func HexToRgb(hex uint32) *C.uint8_t { return C.color_hex_to_rgb(C.uint32_t(hex)) @@ -181,122 +212,125 @@ func RgbToHex(r, g, b uint8) C.uint32_t { return C.color_rgb_to_hex(C.uint8_t(r), C.uint8_t(g), C.uint8_t(b)) } -// GetPxColor get pixel color return C.MMRGBHex -func GetPxColor(x, y int) C.MMRGBHex { +// GetPxColor get the pixel color return C.MMRGBHex +func GetPxColor(x, y int, displayId ...int) C.MMRGBHex { cx := C.int32_t(x) cy := C.int32_t(y) - color := C.get_px_color(cx, cy) + display := displayIdx(displayId...) + color := C.get_px_color(cx, cy, C.int32_t(display)) return color } -// GetPixelColor get pixel color return string -func GetPixelColor(x, y int) string { - cx := C.int32_t(x) - cy := C.int32_t(y) +// GetPixelColor get the pixel color return string +func GetPixelColor(x, y int, displayId ...int) string { + return PadHex(GetPxColor(x, y, displayId...)) +} - color := C.get_pixel_color(cx, cy) - gcolor := C.GoString(color) - C.free(unsafe.Pointer(color)) +// GetLocationColor get the location pos's color +func GetLocationColor(displayId ...int) string { + x, y := Location() + return GetPixelColor(x, y, displayId...) +} - return gcolor +// IsMain is main display +func IsMain(displayId int) bool { + return displayId == GetMainId() +} + +func displayIdx(id ...int) int { + display := -1 + if DisplayID != -1 { + display = DisplayID + } + if len(id) > 0 { + display = id[0] + } + + return display } -// GetMouseColor get the mouse pos's color -func GetMouseColor() string { - x, y := GetMousePos() - return GetPixelColor(x, y) +func getNumDisplays() int { + return int(C.get_num_displays()) } -// ScaleX get primary display horizontal DPI scale factor -func ScaleX() int { - return int(C.scale_x()) +// GetHWNDByPid get the hwnd by pid +func GetHWNDByPid(pid int) int { + return int(C.get_hwnd_by_pid(C.uintptr(pid))) } // SysScale get the sys scale -func SysScale() float64 { - s := C.sys_scale() +func SysScale(displayId ...int) float64 { + display := displayIdx(displayId...) + s := C.sys_scale(C.int32_t(display)) return float64(s) } -// Scaled x * sys-scale -func Scaled(x int) int { - return int(float64(x) * SysScale()) +// Scaled get the screen scaled return scale size +func Scaled(x int, displayId ...int) int { + f := ScaleF(displayId...) + return Scaled0(x, f) +} + +// Scaled0 return int(x * f) +func Scaled0(x int, f float64) int { + return int(float64(x) * f) } -// ScaleY get primary display vertical DPI scale factor -func ScaleY() int { - return int(C.scale_y()) +// Scaled1 return int(x / f) +func Scaled1(x int, f float64) int { + return int(float64(x) / f) } // GetScreenSize get the screen size func GetScreenSize() (int, int) { - size := C.get_screen_size() - // fmt.Println("...", size, size.width) + size := C.getMainDisplaySize() return int(size.w), int(size.h) } -// Scale get the screen scale -func Scale() int { - dpi := map[int]int{ - 0: 100, - // DPI Scaling Level - 96: 100, - 120: 125, - 144: 150, - 168: 175, - 192: 200, - 216: 225, - // Custom DPI - 240: 250, - 288: 300, - 384: 400, - 480: 500, +// GetScreenRect get the screen rect (x, y, w, h) +func GetScreenRect(displayId ...int) Rect { + display := -1 + if len(displayId) > 0 { + display = displayId[0] } - x := ScaleX() - return dpi[x] -} + rect := C.getScreenRect(C.int32_t(display)) + x, y, w, h := int(rect.origin.x), int(rect.origin.y), + int(rect.size.w), int(rect.size.h) -// Mul mul the scale -func Mul(x int) int { - s := Scale() - return x * s / 100 + if runtime.GOOS == "windows" { + // f := ScaleF(displayId...) + f := ScaleF() + x, y, w, h = Scaled0(x, f), Scaled0(y, f), Scaled0(w, f), Scaled0(h, f) + } + return Rect{ + Point{X: x, Y: y}, + Size{W: w, H: h}, + } } // GetScaleSize get the screen scale size -func GetScaleSize() (int, int) { +func GetScaleSize(displayId ...int) (int, int) { x, y := GetScreenSize() - s := Scale() - return x * s / 100, y * s / 100 -} - -// SetXDisplayName set XDisplay name (Linux) -func SetXDisplayName(name string) string { - cname := C.CString(name) - str := C.set_XDisplay_name(cname) - - gstr := C.GoString(str) - C.free(unsafe.Pointer(cname)) - - return gstr -} - -// GetXDisplayName get XDisplay name (Linux) -func GetXDisplayName() string { - name := C.get_XDisplay_name() - gname := C.GoString(name) - C.free(unsafe.Pointer(name)) - - return gname + f := ScaleF(displayId...) + return int(float64(x) * f), int(float64(y) * f) } // CaptureScreen capture the screen return bitmap(c struct), // use `defer robotgo.FreeBitmap(bitmap)` to free the bitmap // // robotgo.CaptureScreen(x, y, w, h int) -func CaptureScreen(args ...int) C.MMBitmapRef { +func CaptureScreen(args ...int) CBitmap { var x, y, w, h C.int32_t + displayId := -1 + if DisplayID != -1 { + displayId = DisplayID + } + + if len(args) > 4 { + displayId = args[4] + } if len(args) > 3 { x = C.int32_t(args[0]) @@ -304,33 +338,141 @@ func CaptureScreen(args ...int) C.MMBitmapRef { w = C.int32_t(args[2]) h = C.int32_t(args[3]) } else { - x = 0 - y = 0 - // Get screen size. - var displaySize C.MMSizeInt32 - displaySize = C.getMainDisplaySize() - w = displaySize.w - h = displaySize.h + // Get the main screen rect. + rect := GetScreenRect(displayId) + if runtime.GOOS == "windows" { + x = C.int32_t(rect.X) + y = C.int32_t(rect.Y) + } + + w = C.int32_t(rect.W) + h = C.int32_t(rect.H) + } + + isPid := 0 + if NotPid || len(args) > 5 { + isPid = 1 } - bit := C.capture_screen(x, y, w, h) - return bit + bit := C.capture_screen(x, y, w, h, C.int32_t(displayId), C.int8_t(isPid)) + return CBitmap(bit) } -// GoCaptureScreen capture the screen and return bitmap(go struct) -func GoCaptureScreen(args ...int) Bitmap { +// CaptureGo capture the screen and return bitmap(go struct) +func CaptureGo(args ...int) Bitmap { bit := CaptureScreen(args...) defer FreeBitmap(bit) return ToBitmap(bit) } -// SaveCapture capture screen and save -func SaveCapture(spath string, args ...int) { +// CaptureImg capture the screen and return image.Image, error +func CaptureImg(args ...int) (image.Image, error) { bit := CaptureScreen(args...) + if bit == nil { + return nil, errors.New("Capture image not found.") + } + defer FreeBitmap(bit) + + return ToImage(bit), nil +} + +// FreeBitmap free and dealloc the C bitmap +func FreeBitmap(bitmap CBitmap) { + // C.destroyMMBitmap(bitmap) + C.bitmap_dealloc(C.MMBitmapRef(bitmap)) +} + +// FreeBitmapArr free and dealloc the C bitmap array +func FreeBitmapArr(bit ...CBitmap) { + for i := 0; i < len(bit); i++ { + FreeBitmap(bit[i]) + } +} + +// ToMMBitmapRef trans CBitmap to C.MMBitmapRef +func ToMMBitmapRef(bit CBitmap) C.MMBitmapRef { + return C.MMBitmapRef(bit) +} + +// ToBitmap trans C.MMBitmapRef to Bitmap +func ToBitmap(bit CBitmap) Bitmap { + bitmap := Bitmap{ + ImgBuf: (*uint8)(bit.imageBuffer), + Width: int(bit.width), + Height: int(bit.height), + Bytewidth: int(bit.bytewidth), + BitsPixel: uint8(bit.bitsPerPixel), + BytesPerPixel: uint8(bit.bytesPerPixel), + } + + return bitmap +} + +// ToCBitmap trans Bitmap to C.MMBitmapRef +func ToCBitmap(bit Bitmap) CBitmap { + cbitmap := C.createMMBitmap_c( + (*C.uint8_t)(bit.ImgBuf), + C.int32_t(bit.Width), + C.int32_t(bit.Height), + C.int32_t(bit.Bytewidth), + C.uint8_t(bit.BitsPixel), + C.uint8_t(bit.BytesPerPixel), + ) + + return CBitmap(cbitmap) +} + +// ToImage convert C.MMBitmapRef to standard image.Image +func ToImage(bit CBitmap) image.Image { + return ToRGBA(bit) +} + +// ToRGBA convert C.MMBitmapRef to standard image.RGBA +func ToRGBA(bit CBitmap) *image.RGBA { + bmp1 := ToBitmap(bit) + return ToRGBAGo(bmp1) +} + +// ImgToCBitmap trans image.Image to CBitmap +func ImgToCBitmap(img image.Image) CBitmap { + return ToCBitmap(ImgToBitmap(img)) +} + +// ByteToCBitmap trans []byte to CBitmap +func ByteToCBitmap(by []byte) CBitmap { + img, _ := ByteToImg(by) + return ImgToCBitmap(img) +} + +// SetXDisplayName set XDisplay name (Linux) +func SetXDisplayName(name string) error { + cname := C.CString(name) + str := C.set_XDisplay_name(cname) + C.free(unsafe.Pointer(cname)) + + return toErr(str) +} + +// GetXDisplayName get XDisplay name (Linux) +func GetXDisplayName() string { + name := C.get_XDisplay_name() + gname := C.GoString(name) + C.free(unsafe.Pointer(name)) + + return gname +} - SaveBitmap(bit, spath) - FreeBitmap(bit) +// CloseMainDisplay close the main X11 display +func CloseMainDisplay() { + C.close_main_display() +} + +// Deprecated: use the ScaledF(), +// +// ScaleX get the primary display horizontal DPI scale factor, drop +func ScaleX() int { + return int(C.scaleX()) } /* @@ -346,43 +488,56 @@ func SaveCapture(spath string, args ...int) { // CheckMouse check the mouse button func CheckMouse(btn string) C.MMMouseButton { // button = args[0].(C.MMMouseButton) - if btn == "left" { - return C.LEFT_BUTTON + m1 := map[string]C.MMMouseButton{ + "left": C.LEFT_BUTTON, + "center": C.CENTER_BUTTON, + "right": C.RIGHT_BUTTON, + "wheelDown": C.WheelDown, + "wheelUp": C.WheelUp, + "wheelLeft": C.WheelLeft, + "wheelRight": C.WheelRight, } - - if btn == "center" { - return C.CENTER_BUTTON - } - - if btn == "right" { - return C.RIGHT_BUTTON + if v, ok := m1[btn]; ok { + return v } return C.LEFT_BUTTON } -// MoveMouse move the mouse -func MoveMouse(x, y int) { - // C.size_t int - Move(x, y) +// MoveScale calculate the os scale factor x, y +func MoveScale(x, y int, displayId ...int) (int, int) { + if Scale || runtime.GOOS == "windows" { + f := ScaleF() + x, y = Scaled1(x, f), Scaled1(y, f) + } + + return x, y } -// Move move the mouse -func Move(x, y int) { +// Move move the mouse to (x, y) +// +// Examples: +// +// robotgo.MouseSleep = 100 // 100 millisecond +// robotgo.Move(10, 10) +func Move(x, y int, displayId ...int) { + x, y = MoveScale(x, y, displayId...) + cx := C.int32_t(x) cy := C.int32_t(y) - C.move_mouse(cx, cy) -} + C.moveMouse(C.MMPointInt32Make(cx, cy)) -// DragMouse drag the mouse -func DragMouse(x, y int, args ...string) { - Drag(x, y, args...) + MilliSleep(MouseSleep) } -// Drag drag the mouse +// Deprecated: use the DragSmooth(), +// +// Drag drag the mouse to (x, y), +// It's not valid now, use the DragSmooth() func Drag(x, y int, args ...string) { - var button C.MMMouseButton = C.LEFT_BUTTON + x, y = MoveScale(x, y) + var button C.MMMouseButton = C.LEFT_BUTTON cx := C.int32_t(x) cy := C.int32_t(y) @@ -390,32 +545,43 @@ func Drag(x, y int, args ...string) { button = CheckMouse(args[0]) } - C.drag_mouse(cx, cy, button) + C.dragMouse(C.MMPointInt32Make(cx, cy), button) + MilliSleep(MouseSleep) } -// DragSmooth drag the mouse smooth +// DragSmooth drag the mouse like smooth to (x, y) +// +// Examples: +// +// robotgo.DragSmooth(10, 10) func DragSmooth(x, y int, args ...interface{}) { - MouseToggle("down") + Toggle("left") + MilliSleep(50) MoveSmooth(x, y, args...) - MouseToggle("up") -} - -// MoveMouseSmooth move the mouse smooth, -// moves mouse to x, y human like, with the mouse button up. -func MoveMouseSmooth(x, y int, args ...interface{}) bool { - return MoveSmooth(x, y, args...) + Toggle("left", "up") } // MoveSmooth move the mouse smooth, // moves mouse to x, y human like, with the mouse button up. // // robotgo.MoveSmooth(x, y int, low, high float64, mouseDelay int) +// +// Examples: +// +// robotgo.MoveSmooth(10, 10) +// robotgo.MoveSmooth(10, 10, 1.0, 2.0) func MoveSmooth(x, y int, args ...interface{}) bool { + // if runtime.GOOS == "windows" { + // f := ScaleF() + // x, y = Scaled0(x, f), Scaled0(y, f) + // } + x, y = MoveScale(x, y) + cx := C.int32_t(x) cy := C.int32_t(y) var ( - mouseDelay = 10 + mouseDelay = 1 low C.double high C.double ) @@ -432,55 +598,59 @@ func MoveSmooth(x, y int, args ...interface{}) bool { high = 3.0 } - cbool := C.move_mouse_smooth(cx, cy, low, high, C.int(mouseDelay)) + cbool := C.smoothlyMoveMouse(C.MMPointInt32Make(cx, cy), low, high) + MilliSleep(MouseSleep + mouseDelay) return bool(cbool) } -// MoveArgs move mose relative args +// MoveArgs get the mouse relative args func MoveArgs(x, y int) (int, int) { - mx, my := GetMousePos() + mx, my := Location() mx = mx + x my = my + y return mx, my } -// MoveRelative move mose relative +// MoveRelative move mouse with relative func MoveRelative(x, y int) { Move(MoveArgs(x, y)) } -// MoveSmoothRelative move mose smooth relative +// MoveSmoothRelative move mouse smooth with relative func MoveSmoothRelative(x, y int, args ...interface{}) { mx, my := MoveArgs(x, y) MoveSmooth(mx, my, args...) } -// GetMousePos get mouse's portion -func GetMousePos() (int, int) { - pos := C.get_mouse_pos() - +// Location get the mouse location position return x, y +func Location() (int, int) { + pos := C.location() x := int(pos.x) y := int(pos.y) - return x, y -} + if Scale || runtime.GOOS == "windows" { + f := ScaleF() + x, y = Scaled0(x, f), Scaled0(y, f) + } -// MouseClick click the mouse -// -// robotgo.MouseClick(button string, double bool) -func MouseClick(args ...interface{}) { - Click(args...) + return x, y } -// Click click the mouse +// Click click the mouse button // // robotgo.Click(button string, double bool) +// +// Examples: +// +// robotgo.Click() // default is left button +// robotgo.Click("right") +// robotgo.Click("wheelLeft") func Click(args ...interface{}) { var ( button C.MMMouseButton = C.LEFT_BUTTON - double C.bool + double bool ) if len(args) > 0 { @@ -488,53 +658,88 @@ func Click(args ...interface{}) { } if len(args) > 1 { - double = C.bool(args[1].(bool)) + double = args[1].(bool) + } + + if !double { + C.clickMouse(button) + } else { + C.doubleClick(button) } - C.mouse_click(button, double) + MilliSleep(MouseSleep) } // MoveClick move and click the mouse // // robotgo.MoveClick(x, y int, button string, double bool) +// +// Examples: +// +// robotgo.MouseSleep = 100 +// robotgo.MoveClick(10, 10) func MoveClick(x, y int, args ...interface{}) { - MoveMouse(x, y) - MouseClick(args...) + Move(x, y) + MilliSleep(50) + Click(args...) } // MovesClick move smooth and click the mouse +// +// use the `robotgo.MouseSleep = 100` func MovesClick(x, y int, args ...interface{}) { MoveSmooth(x, y) - MouseClick(args...) + MilliSleep(50) + Click(args...) } -// MouseToggle toggle the mouse -func MouseToggle(togKey string, args ...interface{}) int { +// Toggle toggle the mouse, support button: +// +// "left", "center", "right", +// "wheelDown", "wheelUp", "wheelLeft", "wheelRight" +// +// Examples: +// +// robotgo.Toggle("left") // default is down +// robotgo.Toggle("left", "up") +func Toggle(key ...interface{}) error { var button C.MMMouseButton = C.LEFT_BUTTON - - if len(args) > 0 { - button = CheckMouse(args[0].(string)) + if len(key) > 0 { + button = CheckMouse(key[0].(string)) } - down := C.CString(togKey) - i := C.mouse_toggle(down, button) + down := true + if len(key) > 1 && key[1].(string) == "up" { + down = false + } + C.toggleMouse(C.bool(down), button) + if len(key) > 2 { + MilliSleep(MouseSleep) + } - C.free(unsafe.Pointer(down)) - return int(i) + return nil } -// ScrollMouse scroll the mouse -func ScrollMouse(x int, direction string) { - cx := C.size_t(x) - cy := C.CString(direction) - C.scroll_mouse(cx, cy) +// MouseDown send mouse down event +func MouseDown(key ...interface{}) error { + return Toggle(key...) +} - C.free(unsafe.Pointer(cy)) +// MouseUp send mouse up event +func MouseUp(key ...interface{}) error { + if len(key) <= 0 { + key = append(key, "left") + } + return Toggle(append(key, "up")...) } -// Scroll scroll the mouse with x, y +// Scroll scroll the mouse to (x, y) // // robotgo.Scroll(x, y, msDelay int) +// +// Examples: +// +// robotgo.Scroll(10, 10) func Scroll(x, y int, args ...int) { var msDelay = 10 if len(args) > 0 { @@ -543,921 +748,257 @@ func Scroll(x, y int, args ...int) { cx := C.int(x) cy := C.int(y) - cz := C.int(msDelay) - C.scroll(cx, cy, cz) + C.scrollMouseXY(cx, cy) + MilliSleep(MouseSleep + msDelay) } -// SetMouseDelay set mouse delay -func SetMouseDelay(delay int) { - cdelay := C.size_t(delay) - C.set_mouse_delay(cdelay) -} - -/* - __ ___ ___________ ____ .______ ______ ___ .______ _______ -| |/ / | ____\ \ / / | _ \ / __ \ / \ | _ \ | \ -| ' / | |__ \ \/ / | |_) | | | | | / ^ \ | |_) | | .--. | -| < | __| \_ _/ | _ < | | | | / /_\ \ | / | | | | -| . \ | |____ | | | |_) | | `--' | / _____ \ | |\ \----.| '--' | -|__|\__\ |_______| |__| |______/ \______/ /__/ \__\ | _| `._____||_______/ - -*/ - -// KeyTap tap the keyboard code; +// ScrollDir scroll the mouse with direction to (x, "up") +// supported: "up", "down", "left", "right" // -// See keys: -// https://github.com/go-vgo/robotgo/blob/master/docs/keys.md +// Examples: // -func KeyTap(tapKey string, args ...interface{}) string { - var ( - akey string - keyT = "null" - keyArr []string - num int - keyDelay = 10 - ) - // var ckeyArr []*C.char - ckeyArr := make([](*C.char), 0) - - // zkey := C.CString(args[0]) - zkey := C.CString(tapKey) - defer C.free(unsafe.Pointer(zkey)) - - if len(args) > 2 && (reflect.TypeOf(args[2]) != reflect.TypeOf(num)) { - num = len(args) - for i := 0; i < num; i++ { - s := args[i].(string) - ckeyArr = append(ckeyArr, (*C.char)(unsafe.Pointer(C.CString(s)))) - } - - str := C.key_Taps(zkey, (**C.char)(unsafe.Pointer(&ckeyArr[0])), - C.int(num), 0) - return C.GoString(str) +// robotgo.ScrollDir(10, "down") +// robotgo.ScrollDir(10, "up") +func ScrollDir(x int, direction ...interface{}) { + d := "down" + if len(direction) > 0 { + d = direction[0].(string) } - if len(args) > 0 { - if reflect.TypeOf(args[0]) == reflect.TypeOf(keyArr) { - - keyArr = args[0].([]string) - num = len(keyArr) - - for i := 0; i < num; i++ { - ckeyArr = append(ckeyArr, (*C.char)(unsafe.Pointer(C.CString(keyArr[i])))) - } - - if len(args) > 1 { - keyDelay = args[1].(int) - } - } else { - akey = args[0].(string) - - if len(args) > 1 { - if reflect.TypeOf(args[1]) == reflect.TypeOf(akey) { - keyT = args[1].(string) - if len(args) > 2 { - keyDelay = args[2].(int) - } - } else { - keyDelay = args[1].(int) - } - } - } - - } else { - akey = "null" - keyArr = []string{"null"} + if d == "down" { + Scroll(0, -x) } - - if akey == "" && len(keyArr) != 0 { - str := C.key_Taps(zkey, (**C.char)(unsafe.Pointer(&ckeyArr[0])), - C.int(num), C.int(keyDelay)) - - return C.GoString(str) + if d == "up" { + Scroll(0, x) } - amod := C.CString(akey) - amodt := C.CString(keyT) - - str := C.key_tap(zkey, amod, amodt, C.int(keyDelay)) + if d == "left" { + Scroll(x, 0) + } + if d == "right" { + Scroll(-x, 0) + } + // MilliSleep(MouseSleep) +} - C.free(unsafe.Pointer(amod)) - C.free(unsafe.Pointer(amodt)) +// ScrollSmooth scroll the mouse smooth, +// default scroll 5 times and sleep 100 millisecond +// +// robotgo.ScrollSmooth(toy, num, sleep, tox) +// +// Examples: +// +// robotgo.ScrollSmooth(-10) +// robotgo.ScrollSmooth(-10, 6, 200, -10) +func ScrollSmooth(to int, args ...int) { + i := 0 + num := 5 + if len(args) > 0 { + num = args[0] + } + tm := 100 + if len(args) > 1 { + tm = args[1] + } + tox := 0 + if len(args) > 2 { + tox = args[2] + } - return C.GoString(str) + for { + Scroll(tox, to) + MilliSleep(tm) + i++ + if i == num { + break + } + } + MilliSleep(MouseSleep) } -// KeyToggle toggle the keyboard +// ScrollRelative scroll mouse with relative // -// See keys: -// https://github.com/go-vgo/robotgo/blob/master/docs/keys.md +// Examples: // -func KeyToggle(key string, args ...string) string { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - ckeyArr := make([](*C.char), 0) - if len(args) > 3 { - num := len(args) +// robotgo.ScrollRelative(10, 10) +func ScrollRelative(x, y int, args ...int) { + mx, my := MoveArgs(x, y) + Scroll(mx, my, args...) +} - for i := 0; i < num; i++ { - ckeyArr = append(ckeyArr, (*C.char)(unsafe.Pointer(C.CString(args[i])))) - } +/* +____ __ ____ __ .__ __. _______ ______ ____ __ ____ +\ \ / \ / / | | | \ | | | \ / __ \ \ \ / \ / / + \ \/ \/ / | | | \| | | .--. | | | | \ \/ \/ / + \ / | | | . ` | | | | | | | | \ / + \ /\ / | | | |\ | | '--' | `--' | \ /\ / + \__/ \__/ |__| |__| \__| |_______/ \______/ \__/ \__/ - str := C.key_Toggles(ckey, (**C.char)(unsafe.Pointer(&ckeyArr[0])), C.int(num)) - return C.GoString(str) - } +*/ +func alertArgs(args ...string) (string, string) { var ( - down, mKey, mKeyT = "null", "null", "null" - // keyDelay = 10 + defaultBtn = "Ok" + cancelBtn = "Cancel" ) if len(args) > 0 { - down = args[0] - - if len(args) > 1 { - mKey = args[1] + defaultBtn = args[0] + } - if len(args) > 2 { - mKeyT = args[2] - } - } + if len(args) > 1 { + cancelBtn = args[1] } - cdown := C.CString(down) - cmKey := C.CString(mKey) - cmKeyT := C.CString(mKeyT) + return defaultBtn, cancelBtn +} - str := C.key_toggle(ckey, cdown, cmKey, cmKeyT) - // str := C.key_Toggle(ckey, cdown, cmKey, cmKeyT, C.int(keyDelay)) +func showAlert(title, msg string, args ...string) bool { + defaultBtn, cancelBtn := alertArgs(args...) - C.free(unsafe.Pointer(cdown)) - C.free(unsafe.Pointer(cmKey)) - C.free(unsafe.Pointer(cmKeyT)) + cTitle := C.CString(title) + cMsg := C.CString(msg) + defaultButton := C.CString(defaultBtn) + cancelButton := C.CString(cancelBtn) - return C.GoString(str) -} + cbool := C.showAlert(cTitle, cMsg, defaultButton, cancelButton) + ibool := int(cbool) -// ReadAll read string from clipboard -func ReadAll() (string, error) { - return clipboard.ReadAll() -} + C.free(unsafe.Pointer(cTitle)) + C.free(unsafe.Pointer(cMsg)) + C.free(unsafe.Pointer(defaultButton)) + C.free(unsafe.Pointer(cancelButton)) -// WriteAll write string to clipboard -func WriteAll(text string) error { - return clipboard.WriteAll(text) + return ibool == 0 } -// CharCodeAt char code at utf-8 -func CharCodeAt(s string, n int) rune { - i := 0 - for _, r := range s { - if i == n { - return r - } - i++ - } - - return 0 +// IsValid valid the window +func IsValid() bool { + abool := C.is_valid() + gbool := bool(abool) + return gbool } -// UnicodeType tap uint32 unicode -func UnicodeType(str uint32) { - cstr := C.uint(str) - C.unicodeType(cstr) +// SetActive set the window active +func SetActive(win Handle) { + SetActiveC(C.MData(win)) } -func toUC(text string) []string { - var uc []string - - for _, r := range text { - textQ := strconv.QuoteToASCII(string(r)) - textUnQ := textQ[1 : len(textQ)-1] - - st := strings.Replace(textUnQ, "\\u", "U", -1) - uc = append(uc, st) - } +// SetActiveC set the window active +func SetActiveC(win C.MData) { + C.set_active(win) +} - return uc +// GetActive get the active window +func GetActive() Handle { + return Handle(GetActiveC()) } -func inputUTF(str string) { - cstr := C.CString(str) - C.input_utf(cstr) - - C.free(unsafe.Pointer(cstr)) -} - -// TypeStr send a string, support UTF-8 -// -// robotgo.TypeStr(string: The string to send, float64: microsleep time, x11) -func TypeStr(str string, args ...float64) { - var tm, tm1 = 0.0, 7.0 - - if len(args) > 0 { - tm = args[0] - } - if len(args) > 1 { - tm1 = args[1] - } - - if runtime.GOOS == "linux" { - strUc := toUC(str) - for i := 0; i < len(strUc); i++ { - rstr := []rune(strUc[i]) - if len(rstr) <= 1 { - ustr := uint32(CharCodeAt(strUc[i], 0)) - UnicodeType(ustr) - } else { - inputUTF(strUc[i]) - MicroSleep(tm1) - } - - MicroSleep(tm) - } - - return - } - - for i := 0; i < len([]rune(str)); i++ { - ustr := uint32(CharCodeAt(str, i)) - UnicodeType(ustr) - - // if len(args) > 0 { - MicroSleep(tm) - // } - } -} - -// PasteStr paste a string, support UTF-8 -func PasteStr(str string) string { - clipboard.WriteAll(str) - if runtime.GOOS == "darwin" { - return KeyTap("v", "command") - } - - return KeyTap("v", "control") -} - -// TypeString send a string, support unicode -// TypeStr(string: The string to send), Wno-deprecated -func TypeString(str string, delay ...int) { - tt.Drop("TypeString", "TypeStr") - var cdelay C.size_t - cstr := C.CString(str) - if len(delay) > 0 { - cdelay = C.size_t(delay[0]) - } - - C.type_string_delayed(cstr, cdelay) - - C.free(unsafe.Pointer(cstr)) -} - -// TypeStrDelay type string delayed -func TypeStrDelay(str string, delay int) { - TypeStr(str) - Sleep(delay) -} - -// TypeStringDelayed type string delayed, Wno-deprecated -func TypeStringDelayed(str string, delay int) { - tt.Drop("TypeStringDelayed", "TypeStrDelay") - TypeStrDelay(str, delay) -} - -// SetKeyDelay set keyboard delay -func SetKeyDelay(delay int) { - C.set_keyboard_delay(C.size_t(delay)) -} - -// SetKeyboardDelay set keyboard delay, Wno-deprecated, -// this function will be removed in version v1.0.0 -func SetKeyboardDelay(delay int) { - tt.Drop("SetKeyboardDelay", "SetKeyDelay") - SetKeyDelay(delay) -} - -// SetDelay set the key and mouse delay -func SetDelay(d ...int) { - v := 10 - if len(d) > 0 { - v = d[0] - } - - SetMouseDelay(v) - SetKeyDelay(v) -} - -/* -.______ __ .___________..___ ___. ___ .______ -| _ \ | | | || \/ | / \ | _ \ -| |_) | | | `---| |----`| \ / | / ^ \ | |_) | -| _ < | | | | | |\/| | / /_\ \ | ___/ -| |_) | | | | | | | | | / _____ \ | | -|______/ |__| |__| |__| |__| /__/ \__\ | _| -*/ - -// GetText get the image text by tesseract ocr -// -// robotgo.GetText(imgPath, lang string) -func GetText(imgPath string, args ...string) (string, error) { - var lang = "eng" - - if len(args) > 0 { - lang = args[0] - if lang == "zh" { - lang = "chi_sim" - } - } - - body, err := exec.Command("tesseract", imgPath, - "stdout", "-l", lang).Output() - if err != nil { - return "", err - } - return string(body), nil -} - -// ToBitmap trans C.MMBitmapRef to Bitmap -func ToBitmap(bit C.MMBitmapRef) Bitmap { - bitmap := Bitmap{ - ImgBuf: (*uint8)(bit.imageBuffer), - Width: int(bit.width), - Height: int(bit.height), - Bytewidth: int(bit.bytewidth), - BitsPixel: uint8(bit.bitsPerPixel), - BytesPerPixel: uint8(bit.bytesPerPixel), - } - - return bitmap -} - -// ToCBitmap trans Bitmap to C.MMBitmapRef -func ToCBitmap(bit Bitmap) C.MMBitmapRef { - cbitmap := C.createMMBitmap( - (*C.uint8_t)(bit.ImgBuf), - C.size_t(bit.Width), - C.size_t(bit.Height), - C.size_t(bit.Bytewidth), - C.uint8_t(bit.BitsPixel), - C.uint8_t(bit.BytesPerPixel), - ) - - return cbitmap -} - -// ToBitmapBytes saves Bitmap to bitmap format in bytes -func ToBitmapBytes(bit C.MMBitmapRef) []byte { - var len C.size_t - ptr := C.saveMMBitmapAsBytes(bit, &len) - if int(len) < 0 { - return nil - } - - bs := C.GoBytes(unsafe.Pointer(ptr), C.int(len)) - C.free(unsafe.Pointer(ptr)) - return bs -} - -// ToMMBitmapRef trans CBitmap to C.MMBitmapRef -func ToMMBitmapRef(bit CBitmap) C.MMBitmapRef { - return C.MMBitmapRef(bit) -} - -// TostringBitmap tostring bitmap to string -func TostringBitmap(bit C.MMBitmapRef) string { - strBit := C.tostring_bitmap(bit) - return C.GoString(strBit) -} - -// TocharBitmap tostring bitmap to C.char -func TocharBitmap(bit C.MMBitmapRef) *C.char { - strBit := C.tostring_bitmap(bit) - return strBit -} - -func internalFindBitmap(bit, sbit C.MMBitmapRef, tolerance float64) (int, int) { - pos := C.find_bitmap(bit, sbit, C.float(tolerance)) - // fmt.Println("pos----", pos) - return int(pos.x), int(pos.y) -} - -// FindCBitmap find bitmap's pos by CBitmap -func FindCBitmap(bmp CBitmap, args ...interface{}) (int, int) { - return FindBitmap(ToMMBitmapRef(bmp), args...) -} - -// FindBitmap find the bitmap's pos -// -// robotgo.FindBitmap(bitmap, subbitamp C.MMBitmapRef, tolerance float64) -// -// |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the -// colors in the bitmaps need to match, with 0 being exact and 1 being any. -// -// This method only automatically free the internal bitmap, -// use `defer robotgo.FreeBitmap(bit)` to free the bitmap -func FindBitmap(bit C.MMBitmapRef, args ...interface{}) (int, int) { - var ( - sbit C.MMBitmapRef - tolerance = 0.01 - ) - - if len(args) > 0 && args[0] != nil { - sbit = args[0].(C.MMBitmapRef) - } else { - sbit = CaptureScreen() - } - - if len(args) > 1 { - tolerance = args[1].(float64) - } - - fx, fy := internalFindBitmap(bit, sbit, tolerance) - // FreeBitmap(bit) - if len(args) <= 0 { - FreeBitmap(sbit) - } - - return fx, fy -} - -// FindPic finding the image by path -// -// robotgo.FindPic(path string, subbitamp C.MMBitmapRef, tolerance float64) -// -// This method only automatically free the internal bitmap, -// use `defer robotgo.FreeBitmap(bit)` to free the bitmap -func FindPic(path string, args ...interface{}) (int, int) { - var ( - sbit C.MMBitmapRef - tolerance = 0.01 - ) - - openbit := OpenBitmap(path) - - if len(args) > 0 && args[0] != nil { - sbit = args[0].(C.MMBitmapRef) - } else { - sbit = CaptureScreen() - } - - if len(args) > 1 { - tolerance = args[1].(float64) - } - - fx, fy := internalFindBitmap(openbit, sbit, tolerance) - FreeBitmap(openbit) - if len(args) <= 0 { - FreeBitmap(sbit) - } - - return fx, fy -} - -// FindEveryBitmap find the every bitmap -func FindEveryBitmap(bit C.MMBitmapRef, args ...interface{}) (int, int) { - var ( - sbit C.MMBitmapRef - tolerance C.float = 0.01 - lpos C.MMPoint - ) - - if len(args) > 0 && args[0] != nil { - sbit = args[0].(C.MMBitmapRef) - } else { - sbit = CaptureScreen() - } - - if len(args) > 1 { - tolerance = C.float(args[1].(float64)) - } - - if len(args) > 2 { - lpos.x = C.size_t(args[2].(int)) - lpos.y = 0 - } else { - lpos.x = 0 - lpos.y = 0 - } - - if len(args) > 3 { - lpos.x = C.size_t(args[2].(int)) - lpos.y = C.size_t(args[3].(int)) - } - - pos := C.find_every_bitmap(bit, sbit, tolerance, &lpos) - // FreeBitmap(bit) - if len(args) <= 0 { - FreeBitmap(sbit) - } - - // fmt.Println("pos----", pos) - return int(pos.x), int(pos.y) -} - -// CountBitmap count of the bitmap -func CountBitmap(bitmap, sbit C.MMBitmapRef, args ...float32) int { - var tolerance C.float = 0.01 - if len(args) > 0 { - tolerance = C.float(args[0]) - } - - count := C.count_of_bitmap(bitmap, sbit, tolerance) - return int(count) -} - -// BitmapClick find the bitmap and click -func BitmapClick(bitmap C.MMBitmapRef, args ...interface{}) { - x, y := FindBitmap(bitmap) - MovesClick(x, y, args...) -} - -// PointInBounds bitmap point in bounds -func PointInBounds(bitmap C.MMBitmapRef, x, y int) bool { - var point C.MMPoint - point.x = C.size_t(x) - point.y = C.size_t(y) - cbool := C.point_in_bounds(bitmap, point) - - return bool(cbool) -} - -// OpenBitmap open the bitmap return C.MMBitmapRef -// -// robotgo.OpenBitmap(path string, type int) -func OpenBitmap(gpath string, args ...int) C.MMBitmapRef { - path := C.CString(gpath) - var mtype C.uint16_t = 1 - - if len(args) > 0 { - mtype = C.uint16_t(args[0]) - } - - bit := C.bitmap_open(path, mtype) - C.free(unsafe.Pointer(path)) - - return bit -} - -// DecodeImg decode the image to image.Image and return -func DecodeImg(path string) (image.Image, string, error) { - return imgo.DecodeFile(path) -} - -// OpenImg open the image return []byte -func OpenImg(path string) []byte { - return imgo.ImgToBytes(path) -} - -// SaveImg save the image by []byte -func SaveImg(b []byte, path string) { - imgo.Save(path, b) -} - -// BitmapStr bitmap from string -func BitmapStr(str string) C.MMBitmapRef { - return BitmapFromStr(str) -} - -// BitmapFromStr bitmap from string -func BitmapFromStr(str string) C.MMBitmapRef { - cs := C.CString(str) - bit := C.bitmap_from_string(cs) - C.free(unsafe.Pointer(cs)) - - return bit -} - -// SaveBitmap save the bitmap to image -// -// robotgo.SaveBimap(bitmap C.MMBitmapRef, path string, type int) -func SaveBitmap(bitmap C.MMBitmapRef, gpath string, args ...int) string { - var mtype C.uint16_t = 1 - if len(args) > 0 { - mtype = C.uint16_t(args[0]) - } - - path := C.CString(gpath) - saveBit := C.bitmap_save(bitmap, path, mtype) - C.free(unsafe.Pointer(path)) - - return C.GoString(saveBit) -} - -// GetPortion get bitmap portion -func GetPortion(bit C.MMBitmapRef, x, y, w, h int) C.MMBitmapRef { - var rect C.MMRect - rect.origin.x = C.size_t(x) - rect.origin.y = C.size_t(y) - rect.size.width = C.size_t(w) - rect.size.height = C.size_t(h) - - pos := C.get_portion(bit, rect) - return pos -} - -// Convert convert the bitmap -// -// robotgo.Convert(opath, spath string, type int) -func Convert(opath, spath string, args ...int) { - var mtype = 1 - if len(args) > 0 { - mtype = args[0] - } - - // C.CString() - bitmap := OpenBitmap(opath) - // fmt.Println("a----", bit_map) - SaveBitmap(bitmap, spath, mtype) -} - -// FreeBitmap free and dealloc bitmap -func FreeBitmap(bitmap C.MMBitmapRef) { - // C.destroyMMBitmap(bitmap) - C.bitmap_dealloc(bitmap) -} - -// ReadBitmap returns false and sets error if |bitmap| is NULL -func ReadBitmap(bitmap C.MMBitmapRef) bool { - abool := C.bitmap_ready(bitmap) - gbool := bool(abool) - return gbool -} - -// CopyBitPB copy bitmap to pasteboard -func CopyBitPB(bitmap C.MMBitmapRef) bool { - abool := C.bitmap_copy_to_pboard(bitmap) - gbool := bool(abool) - - return gbool -} - -// CopyBitpb copy bitmap to pasteboard, Wno-deprecated -func CopyBitpb(bitmap C.MMBitmapRef) bool { - tt.Drop("CopyBitpb", "CopyBitPB") - return CopyBitPB(bitmap) -} - -// DeepCopyBit deep copy bitmap -func DeepCopyBit(bitmap C.MMBitmapRef) C.MMBitmapRef { - bit := C.bitmap_deepcopy(bitmap) - return bit -} - -// GetColor get bitmap color -func GetColor(bitmap C.MMBitmapRef, x, y int) C.MMRGBHex { - color := C.bitmap_get_color(bitmap, C.size_t(x), C.size_t(y)) - - return color -} - -// GetColors get bitmap color retrun string -func GetColors(bitmap C.MMBitmapRef, x, y int) string { - clo := GetColor(bitmap, x, y) - - return PadHex(clo) -} - -// FindColor find bitmap color -// -// robotgo.FindColor(color CHex, bitmap C.MMBitmapRef, tolerance float) -func FindColor(color CHex, args ...interface{}) (int, int) { - var ( - tolerance C.float = 0.01 - bitmap C.MMBitmapRef - ) - - if len(args) > 0 && args[0] != nil { - bitmap = args[0].(C.MMBitmapRef) - } else { - bitmap = CaptureScreen() - } - - if len(args) > 1 { - tolerance = C.float(args[1].(float64)) - } - - pos := C.bitmap_find_color(bitmap, C.MMRGBHex(color), tolerance) - if len(args) <= 0 { - FreeBitmap(bitmap) - } - - x := int(pos.x) - y := int(pos.y) - - return x, y -} - -// FindColorCS findcolor by CaptureScreen -func FindColorCS(color CHex, x, y, w, h int, args ...float64) (int, int) { - var tolerance = 0.01 - - if len(args) > 0 { - tolerance = args[0] - } - - bitmap := CaptureScreen(x, y, w, h) - rx, ry := FindColor(color, bitmap, tolerance) - FreeBitmap(bitmap) - - return rx, ry -} - -// CountColor count bitmap color -func CountColor(color CHex, args ...interface{}) int { - var ( - tolerance C.float = 0.01 - bitmap C.MMBitmapRef - ) - - if len(args) > 0 && args[0] != nil { - bitmap = args[0].(C.MMBitmapRef) - } else { - bitmap = CaptureScreen() - } - - if len(args) > 1 { - tolerance = C.float(args[1].(float64)) - } - - count := C.bitmap_count_of_color(bitmap, C.MMRGBHex(color), tolerance) - if len(args) <= 0 { - FreeBitmap(bitmap) - } - - return int(count) -} - -// CountColorCS count bitmap color by CaptureScreen -func CountColorCS(color CHex, x, y, w, h int, args ...float64) int { - var tolerance = 0.01 - - if len(args) > 0 { - tolerance = args[0] - } - - bitmap := CaptureScreen(x, y, w, h) - rx := CountColor(color, bitmap, tolerance) - FreeBitmap(bitmap) - - return rx -} - -// GetImgSize get the image size -func GetImgSize(imgPath string) (int, int) { - bitmap := OpenBitmap(imgPath) - gbit := ToBitmap(bitmap) - - w := gbit.Width / 2 - h := gbit.Height / 2 - FreeBitmap(bitmap) - - return w, h -} - -/* -____ __ ____ __ .__ __. _______ ______ ____ __ ____ -\ \ / \ / / | | | \ | | | \ / __ \ \ \ / \ / / - \ \/ \/ / | | | \| | | .--. | | | | \ \/ \/ / - \ / | | | . ` | | | | | | | | \ / - \ /\ / | | | |\ | | '--' | `--' | \ /\ / - \__/ \__/ |__| |__| \__| |_______/ \______/ \__/ \__/ - -*/ - -// ShowAlert show a alert window -func ShowAlert(title, msg string, args ...string) int { - var ( - // title string - // msg string - defaultButton = "Ok" - cancelButton = "Cancel" - ) - - if len(args) > 0 { - // title = args[0] - // msg = args[1] - defaultButton = args[0] - } - - if len(args) > 1 { - cancelButton = args[1] - } - - atitle := C.CString(title) - amsg := C.CString(msg) - adefaultButton := C.CString(defaultButton) - acancelButton := C.CString(cancelButton) - - cbool := C.show_alert(atitle, amsg, adefaultButton, acancelButton) - ibool := int(cbool) - - C.free(unsafe.Pointer(atitle)) - C.free(unsafe.Pointer(amsg)) - C.free(unsafe.Pointer(adefaultButton)) - C.free(unsafe.Pointer(acancelButton)) - - return ibool -} - -// IsValid valid the window -func IsValid() bool { - abool := C.is_valid() - gbool := bool(abool) - // fmt.Println("bool---------", gbool) - return gbool -} - -// SetActive set the window active -func SetActive(win C.MData) { - C.set_active(win) -} - -// GetActive get the active window -func GetActive() C.MData { +// GetActiveC get the active window +func GetActiveC() C.MData { mdata := C.get_active() // fmt.Println("active----", mdata) return mdata } // MinWindow set the window min -func MinWindow(pid int32, args ...interface{}) { +func MinWindow(pid int, args ...interface{}) { var ( state = true - hwnd int + isPid int ) if len(args) > 0 { state = args[0].(bool) } - if len(args) > 1 { - hwnd = args[1].(int) + if len(args) > 1 || NotPid { + isPid = 1 } - C.min_window(C.uintptr(pid), C.bool(state), C.uintptr(hwnd)) + C.min_window(C.uintptr(pid), C.bool(state), C.int8_t(isPid)) } // MaxWindow set the window max -func MaxWindow(pid int32, args ...interface{}) { +func MaxWindow(pid int, args ...interface{}) { var ( state = true - hwnd int + isPid int ) if len(args) > 0 { state = args[0].(bool) } - if len(args) > 1 { - hwnd = args[1].(int) + if len(args) > 1 || NotPid { + isPid = 1 } - C.max_window(C.uintptr(pid), C.bool(state), C.uintptr(hwnd)) + C.max_window(C.uintptr(pid), C.bool(state), C.int8_t(isPid)) } // CloseWindow close the window -func CloseWindow(args ...int32) { +func CloseWindow(args ...int) { if len(args) <= 0 { C.close_main_window() return } - var hwnd, isHwnd int32 + var pid, isPid int if len(args) > 0 { - hwnd = args[0] + pid = args[0] } - if len(args) > 1 { - isHwnd = args[1] + if len(args) > 1 || NotPid { + isPid = 1 } - C.close_window(C.uintptr(hwnd), C.uintptr(isHwnd)) + C.close_window_by_PId(C.uintptr(pid), C.int8_t(isPid)) } // SetHandle set the window handle func SetHandle(hwnd int) { chwnd := C.uintptr(hwnd) - C.set_handle(chwnd) + C.setHandle(chwnd) } // SetHandlePid set the window handle by pid -func SetHandlePid(pid int32, args ...int32) { - var isHwnd int32 +func SetHandlePid(pid int, args ...int) { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + } + + C.set_handle_pid_mData(C.uintptr(pid), C.int8_t(isPid)) +} + +// GetHandById get handle mdata by id +func GetHandById(id int, args ...int) Handle { + isPid := 1 if len(args) > 0 { - isHwnd = args[0] + isPid = args[0] } + return GetHandByPid(id, isPid) +} - C.set_handle_pid_mData(C.uintptr(pid), C.uintptr(isHwnd)) +// GetHandByPid get handle mdata by pid +func GetHandByPid(pid int, args ...int) Handle { + return Handle(GetHandByPidC(pid, args...)) } +// Deprecated: use the GetHandByPid(), +// // GetHandPid get handle mdata by pid -func GetHandPid(pid int32, args ...int32) C.MData { - var isHwnd int32 - if len(args) > 0 { - isHwnd = args[0] +func GetHandPid(pid int, args ...int) Handle { + return GetHandByPid(pid, args...) +} + +// GetHandByPidC get handle mdata by pid +func GetHandByPidC(pid int, args ...int) C.MData { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 } - return C.set_handle_pid(C.uintptr(pid), C.uintptr(isHwnd)) + return C.set_handle_pid(C.uintptr(pid), C.int8_t(isPid)) } // GetHandle get the window handle @@ -1468,24 +1009,35 @@ func GetHandle() int { return ghwnd } -// GetBHandle get the window handle, Wno-deprecated +// Deprecated: use the GetHandle(), +// +// # GetBHandle get the window handle, Wno-deprecated +// +// This function will be removed in version v1.0.0 func GetBHandle() int { tt.Drop("GetBHandle", "GetHandle") - hwnd := C.bget_handle() + hwnd := C.b_get_handle() ghwnd := int(hwnd) //fmt.Println("gethwnd---", ghwnd) return ghwnd } -func cgetTitle(hwnd, isHwnd int32) string { - title := C.get_title(C.uintptr(hwnd), C.uintptr(isHwnd)) +func cgetTitle(pid, isPid int) string { + title := C.get_title_by_pid(C.uintptr(pid), C.int8_t(isPid)) gtitle := C.GoString(title) return gtitle } -// GetTitle get the window title -func GetTitle(args ...int32) string { +// GetTitle get the window title return string +// +// Examples: +// +// fmt.Println(robotgo.GetTitle()) +// +// ids, _ := robotgo.FindIds() +// robotgo.GetTitle(ids[0]) +func GetTitle(args ...int) string { if len(args) <= 0 { title := C.get_main_title() gtitle := C.GoString(title) @@ -1499,15 +1051,21 @@ func GetTitle(args ...int32) string { return internalGetTitle(args[0]) } -// GetPID get the process id -func GetPID() int32 { +// GetPid get the process id return int32 +func GetPid() int { pid := C.get_PID() - return int32(pid) + return int(pid) } // internalGetBounds get the window bounds -func internalGetBounds(pid int32, hwnd int) (int, int, int, int) { - bounds := C.get_bounds(C.uintptr(pid), C.uintptr(hwnd)) +func internalGetBounds(pid, isPid int) (int, int, int, int) { + bounds := C.get_bounds(C.uintptr(pid), C.int8_t(isPid)) + return int(bounds.X), int(bounds.Y), int(bounds.W), int(bounds.H) +} + +// internalGetClient get the window client bounds +func internalGetClient(pid, isPid int) (int, int, int, int) { + bounds := C.get_client(C.uintptr(pid), C.int8_t(isPid)) return int(bounds.X), int(bounds.Y), int(bounds.W), int(bounds.H) } @@ -1517,26 +1075,30 @@ func Is64Bit() bool { return bool(b) } -func internalActive(pid int32, hwnd int) { - C.active_PID(C.uintptr(pid), C.uintptr(hwnd)) +func internalActive(pid, isPid int) { + C.active_PID(C.uintptr(pid), C.int8_t(isPid)) } -// ActivePID active the window by PID, +// ActivePid active the window by Pid, // If args[0] > 0 on the Windows platform via a window handle to active -// func ActivePID(pid int32, args ...int) { -// var hwnd int +// func ActivePid(pid int32, args ...int) { +// var isPid int // if len(args) > 0 { -// hwnd = args[0] +// isPid = args[0] // } -// C.active_PID(C.uintptr(pid), C.uintptr(hwnd)) +// C.active_PID(C.uintptr(pid), C.uintptr(isPid)) // } -// ActiveName active window by name +// ActiveName active the window by name +// +// Examples: +// +// robotgo.ActiveName("chrome") func ActiveName(name string) error { pids, err := FindIds(name) if err == nil && len(pids) > 0 { - ActivePID(pids[0]) + return ActivePid(pids[0]) } return err diff --git a/robotgo_fn_v1.go b/robotgo_fn_v1.go new file mode 100644 index 00000000..89cacf9d --- /dev/null +++ b/robotgo_fn_v1.go @@ -0,0 +1,95 @@ +package robotgo + +import "github.com/vcaesar/tt" + +// Deprecated: use the Move(), +// +// MoveMouse move the mouse +func MoveMouse(x, y int) { + Move(x, y) +} + +// Deprecated: use the DragSmooth(), +// +// DragMouse drag the mouse to (x, y), +// It's same with the DragSmooth() now +func DragMouse(x, y int, args ...interface{}) { + Toggle("left") + MilliSleep(50) + // Drag(x, y, args...) + MoveSmooth(x, y, args...) + Toggle("left", "up") +} + +// Deprecated: use the MoveSmooth(), +// +// MoveMouseSmooth move the mouse smooth, +// moves mouse to x, y human like, with the mouse button up. +func MoveMouseSmooth(x, y int, args ...interface{}) bool { + return MoveSmooth(x, y, args...) +} + +// Deprecated: use the function Location() +// +// GetMousePos get the mouse's position return x, y +func GetMousePos() (int, int) { + return Location() +} + +// Deprecated: use the Click(), +// +// # MouseClick click the mouse +// +// robotgo.MouseClick(button string, double bool) +func MouseClick(args ...interface{}) { + Click(args...) +} + +// Deprecated: use the TypeStr(), +// +// # TypeStringDelayed type string delayed, Wno-deprecated +// +// This function will be removed in version v1.0.0 +func TypeStringDelayed(str string, delay int) { + tt.Drop("TypeStringDelayed", "TypeStrDelay") + TypeStrDelay(str, delay) +} + +// Deprecated: use the ScaledF(), +// +// Scale1 get the screen scale (only windows old), drop +func Scale1() int { + dpi := map[int]int{ + 0: 100, + // DPI Scaling Level + 96: 100, + 120: 125, + 144: 150, + 168: 175, + 192: 200, + 216: 225, + // Custom DPI + 240: 250, + 288: 300, + 384: 400, + 480: 500, + } + + x := ScaleX() + return dpi[x] +} + +// Deprecated: use the ScaledF(), +// +// Scale0 return ScaleX() / 0.96, drop +func Scale0() int { + return int(float64(ScaleX()) / 0.96) +} + +// Deprecated: use the ScaledF(), +// +// Mul mul the scale, drop +func Mul(x int) int { + s := Scale1() + return x * s / 100 +} diff --git a/robotgo_mac.go b/robotgo_mac.go new file mode 100644 index 00000000..b8f73573 --- /dev/null +++ b/robotgo_mac.go @@ -0,0 +1,24 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +//go:build darwin +// +build darwin + +package robotgo + +/* +#include +*/ +import "C" + +// GetMainId get the main display id +func GetMainId() int { + return int(C.CGMainDisplayID()) +} diff --git a/robotgo_mac_unix.go b/robotgo_mac_unix.go new file mode 100644 index 00000000..65c759a1 --- /dev/null +++ b/robotgo_mac_unix.go @@ -0,0 +1,23 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +//go:build !windows +// +build !windows + +package robotgo + +// ScaleF get the system scale val +func ScaleF(displayId ...int) float64 { + f := SysScale(displayId...) + if f == 0.0 { + f = 1.0 + } + return f +} diff --git a/robotgo_mac_win.go b/robotgo_mac_win.go index 53d75413..8fd82686 100644 --- a/robotgo_mac_win.go +++ b/robotgo_mac_win.go @@ -3,45 +3,77 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. +//go:build darwin || windows // +build darwin windows package robotgo // GetBounds get the window bounds -func GetBounds(pid int32, args ...int) (int, int, int, int) { - var hwnd int - if len(args) > 0 { - hwnd = args[0] +func GetBounds(pid int, args ...int) (int, int, int, int) { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 } - return internalGetBounds(pid, hwnd) + return internalGetBounds(pid, isPid) +} + +// GetClient get the window client bounds +func GetClient(pid int, args ...int) (int, int, int, int) { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + } + + return internalGetClient(pid, isPid) } // internalGetTitle get the window title -func internalGetTitle(pid int32, args ...int32) string { - var isHwnd int32 - if len(args) > 0 { - isHwnd = args[0] +func internalGetTitle(pid int, args ...int) string { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 } - gtitle := cgetTitle(pid, isHwnd) + gtitle := cgetTitle(pid, isPid) return gtitle } -// ActivePID active the window by PID, +// ActivePid active the window by PID, // // If args[0] > 0 on the Windows platform via a window handle to active -func ActivePID(pid int32, args ...int) error { - var hwnd int - if len(args) > 0 { - hwnd = args[0] +// +// Examples: +// +// ids, _ := robotgo.FindIds() +// robotgo.ActivePid(ids[0]) +func ActivePid(pid int, args ...int) error { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 } - internalActive(pid, hwnd) + internalActive(pid, isPid) return nil } + +// DisplaysNum get the count of displays +func DisplaysNum() int { + return getNumDisplays() +} + +// Alert show a alert window +// Displays alert with the attributes. +// If cancel button is not given, only the default button is displayed +// +// Examples: +// +// robotgo.Alert("hi", "window", "ok", "cancel") +func Alert(title, msg string, args ...string) bool { + return showAlert(title, msg, args...) +} diff --git a/robotgo_ocr.go b/robotgo_ocr.go index 6e1939fb..3249917b 100644 --- a/robotgo_ocr.go +++ b/robotgo_ocr.go @@ -3,17 +3,18 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. +//go:build ocr // +build ocr package robotgo import ( - "github.com/otiai10/gosseract" + "github.com/otiai10/gosseract/v2" ) // GetText get the image text by tesseract ocr diff --git a/robotgo_test.go b/robotgo_test.go index e1ef7858..d6bbcc58 100644 --- a/robotgo_test.go +++ b/robotgo_test.go @@ -3,11 +3,12 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. +//go:build darwin || windows // +build darwin windows package robotgo @@ -39,18 +40,18 @@ func TestSize(t *testing.T) { } func TestMoveMouse(t *testing.T) { - MoveMouse(20, 20) - MilliSleep(10) - x, y := GetMousePos() + Move(20, 20) + MilliSleep(50) + x, y := Location() tt.Equal(t, 20, x) tt.Equal(t, 20, y) } func TestMoveMouseSmooth(t *testing.T) { - b := MoveMouseSmooth(100, 100) - MilliSleep(10) - x, y := GetMousePos() + b := MoveSmooth(100, 100) + MilliSleep(50) + x, y := Location() tt.True(t, b) tt.Equal(t, 100, x) @@ -58,56 +59,80 @@ func TestMoveMouseSmooth(t *testing.T) { } func TestDragMouse(t *testing.T) { - DragMouse(500, 500) - MilliSleep(10) - x, y := GetMousePos() + DragSmooth(500, 500) + MilliSleep(50) + x, y := Location() tt.Equal(t, 500, x) tt.Equal(t, 500, y) } func TestScrollMouse(t *testing.T) { - ScrollMouse(120, "up") + ScrollDir(120, "up") + ScrollDir(100, "right") + + Scroll(0, 120) MilliSleep(100) Scroll(210, 210) + MilliSleep(10) } func TestMoveRelative(t *testing.T) { Move(200, 200) - MilliSleep(10) + MilliSleep(50) MoveRelative(10, -10) - MilliSleep(10) + MilliSleep(50) - x, y := GetMousePos() + x, y := Location() tt.Equal(t, 210, x) tt.Equal(t, 190, y) } func TestMoveSmoothRelative(t *testing.T) { Move(200, 200) - MilliSleep(10) + MilliSleep(50) MoveSmoothRelative(10, -10) - MilliSleep(10) + MilliSleep(50) - x, y := GetMousePos() + x, y := Location() tt.Equal(t, 210, x) tt.Equal(t, 190, y) } func TestMouseToggle(t *testing.T) { - e := MouseToggle("up", "right") - tt.Zero(t, e) + e := Toggle("right") + tt.Nil(t, e) + + e = Toggle("right", "up") + tt.Nil(t, e) + + e = MouseDown("left") + tt.Nil(t, e) + + e = MouseUp("left") + tt.Nil(t, e) } func TestKey(t *testing.T) { e := KeyTap("v", "cmd") - tt.Empty(t, e) + tt.Nil(t, e) + + e = KeyTap("enter") + tt.Nil(t, e) e = KeyToggle("v", "up") - tt.Empty(t, e) + tt.Nil(t, e) + + e = KeyDown("a") + tt.Nil(t, e) + e = KeyUp("a") + tt.Nil(t, e) + + e = KeyPress("b") + tt.Nil(t, e) } func TestClip(t *testing.T) { @@ -124,10 +149,11 @@ func TestTypeStr(t *testing.T) { tt.Equal(t, 115, c) e := PasteStr("s") - tt.Empty(t, e) + tt.Nil(t, e) - uc := toUC("s") - tt.Equal(t, "[s]", uc) + s1 := "abc\\\\cd/s@世界" + uc := ToUC(s1) + tt.Equal(t, "[a b c \\ \\ c d / s @ U4e16 U754c]", uc) } func TestKeyCode(t *testing.T) { @@ -136,24 +162,40 @@ func TestKeyCode(t *testing.T) { k := Keycode["1"] tt.Equal(t, 2, k) + + s := Special["+"] + tt.Equal(t, "=", s) + + tt.Equal(t, "0", Key0) + tt.Equal(t, "a", KeyA) } -func TestBitmap(t *testing.T) { +func TestImage(t *testing.T) { bit := CaptureScreen() + defer FreeBitmap(bit) tt.NotNil(t, bit) - e := SaveBitmap(bit, "robot_test.png") - tt.Empty(t, e) - bit1 := OpenBitmap("robot_test.png") - b := tt.TypeOf(bit, bit1) - tt.True(t, b) - tt.NotNil(t, bit1) + img := ToImage(bit) + err := SavePng(img, "robot_test.png") + tt.Nil(t, err) + + img1, err := CaptureImg(10, 10, 20, 20) + tt.Nil(t, err) + e := Save(img1, "robot_img.jpeg", 50) + tt.Nil(t, e) + + tt.Equal(t, 20, Width(img1)) + tt.Equal(t, 20, Height(img1)) + + bit1 := ImgToBitmap(img1) + tt.Equal(t, bit1.Width, Width(img1)) + tt.Equal(t, bit1.Height, Height(img1)) } func TestPs(t *testing.T) { id, err := Pids() tt.Not(t, "[]", id) - tt.IsType(t, "[]int32", id) + tt.IsType(t, "[]int", id) tt.Nil(t, err) ps, e := Process() @@ -176,9 +218,14 @@ func TestPs(t *testing.T) { id, err = FindIds(n1[0]) tt.Not(t, "[]", id) - tt.IsType(t, "[]int32", id) + tt.IsType(t, "[]int", id) tt.Nil(t, err) + if len(id) > 0 { + e := KeyTap("v", id[0], "cmd") + tt.Nil(t, e) + } + // n, e = FindPath(id[0]) // tt.NotEmpty(t, n) // tt.Nil(t, e) @@ -191,6 +238,6 @@ func TestPs(t *testing.T) { // log.Println("tap...") // }() -// i := ShowAlert("t", "msg") -// tt.Zero(t, i) +// i := Alert("t", "msg") +// tt.True(t, i) // } diff --git a/robotgo_unix.go b/robotgo_unix.go deleted file mode 100644 index 524f96b3..00000000 --- a/robotgo_unix.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// +build !darwin,!windows - -package robotgo - -import ( - "errors" - "log" - - "github.com/robotn/xgb/xproto" - "github.com/robotn/xgbutil" - "github.com/robotn/xgbutil/ewmh" -) - -var xu *xgbutil.XUtil - -// GetBounds get the window bounds -func GetBounds(pid int32, args ...int) (int, int, int, int) { - var hwnd int - if len(args) > 0 { - hwnd = args[0] - - return internalGetBounds(pid, hwnd) - } - - xid, err := GetXId(xu, pid) - if err != nil { - log.Println("GetXid from Pid errors is: ", err) - return 0, 0, 0, 0 - } - - return internalGetBounds(int32(xid), hwnd) -} - -// internalGetTitle get the window title -func internalGetTitle(pid int32, args ...int32) string { - var hwnd int32 - if len(args) > 0 { - hwnd = args[0] - - return cgetTitle(pid, hwnd) - } - - xid, err := GetXId(xu, pid) - if err != nil { - log.Println("GetXid from Pid errors is: ", err) - return "" - } - - return cgetTitle(int32(xid), hwnd) -} - -// ActivePIDC active the window by PID, -// If args[0] > 0 on the unix platform via a xid to active -func ActivePIDC(pid int32, args ...int) { - var hwnd int - if len(args) > 0 { - hwnd = args[0] - - internalActive(pid, hwnd) - return - } - - xid, err := GetXId(xu, pid) - if err != nil { - log.Println("GetXid from Pid errors is: ", err) - return - } - - internalActive(int32(xid), hwnd) -} - -// ActivePID active the window by PID, -// -// If args[0] > 0 on the Windows platform via a window handle to active, -// If args[0] > 0 on the unix platform via a xid to active -func ActivePID(pid int32, args ...int) error { - if xu == nil { - var err error - xu, err = xgbutil.NewConn() - if err != nil { - return err - } - } - - if len(args) > 0 { - err := ewmh.ActiveWindowReq(xu, xproto.Window(pid)) - if err != nil { - return err - } - - return nil - } - - // get the xid from pid - xid, err := GetXidFromPid(xu, pid) - if err != nil { - return err - } - - err = ewmh.ActiveWindowReq(xu, xid) - if err != nil { - return err - } - - return nil -} - -// GetXId get the xid return window and error -func GetXId(xu *xgbutil.XUtil, pid int32) (xproto.Window, error) { - if xu == nil { - var err error - xu, err = xgbutil.NewConn() - if err != nil { - // log.Println("xgbutil.NewConn errors is: ", err) - return 0, err - } - } - - xid, err := GetXidFromPid(xu, pid) - return xid, err -} - -// GetXidFromPid get the xide from pid -func GetXidFromPid(xu *xgbutil.XUtil, pid int32) (xproto.Window, error) { - windows, err := ewmh.ClientListGet(xu) - if err != nil { - return 0, err - } - - for _, window := range windows { - wmPid, err := ewmh.WmPidGet(xu, window) - if err != nil { - return 0, err - } - - if uint(pid) == wmPid { - return window, nil - } - } - - return 0, errors.New("failed to find a window with a matching pid.") -} diff --git a/robotgo_win.go b/robotgo_win.go index eac9a9d4..737ae513 100644 --- a/robotgo_win.go +++ b/robotgo_win.go @@ -3,11 +3,12 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. +//go:build windows // +build windows package robotgo @@ -16,20 +17,19 @@ import ( "syscall" "unsafe" - "github.com/lxn/win" + // "github.com/lxn/win" + "github.com/tailscale/win" ) // FindWindow find window hwnd by name -func FindWindow(str string) win.HWND { - hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr(str)) - +func FindWindow(name string) win.HWND { + hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr(name)) return hwnd } // GetHWND get foreground window hwnd func GetHWND() win.HWND { hwnd := win.GetForegroundWindow() - return hwnd } @@ -49,6 +49,63 @@ func SetActiveWindow(hwnd win.HWND) win.HWND { } // SetFocus set window focus with hwnd -func SetFocus(hWnd win.HWND) win.HWND { - return win.SetFocus(hWnd) +func SetFocus(hwnd win.HWND) win.HWND { + return win.SetFocus(hwnd) +} + +// SetForeg set the window into the foreground by hwnd +func SetForeg(hwnd win.HWND) bool { + return win.SetForegroundWindow(hwnd) +} + +// GetMain get the main display hwnd +func GetMain() win.HWND { + return win.GetActiveWindow() +} + +// GetMainId get the main display id +func GetMainId() int { + return int(GetMain()) +} + +// ScaleF get the system scale value +// if "displayId == -2" this function will get the desktop scale value +func ScaleF(displayId ...int) (f float64) { + if len(displayId) > 0 && displayId[0] != -1 { + if displayId[0] >= 0 { + dpi := GetDPI(win.HWND(displayId[0])) + f = float64(dpi) / 96.0 + } + + if displayId[0] == -2 { + f = float64(GetDPI(GetDesktopWindow())) / 96.0 + } + } else { + f = float64(GetMainDPI()) / 96.0 + } + + if f == 0.0 { + f = 1.0 + } + return f +} + +// GetDesktopWindow get the desktop window hwnd id +func GetDesktopWindow() win.HWND { + return win.GetDesktopWindow() +} + +// GetMainDPI get the display dpi +func GetMainDPI() int { + return int(GetDPI(GetHWND())) +} + +// GetDPI get the window dpi +func GetDPI(hwnd win.HWND) uint32 { + return win.GetDpiForWindow(hwnd) +} + +// GetSysDPI get the system metrics dpi +func GetSysDPI(idx int32, dpi uint32) int32 { + return win.GetSystemMetricsForDpi(idx, dpi) } diff --git a/robotgo_x11.go b/robotgo_x11.go new file mode 100644 index 00000000..d929fba8 --- /dev/null +++ b/robotgo_x11.go @@ -0,0 +1,239 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +//go:build !darwin && !windows +// +build !darwin,!windows + +package robotgo + +import ( + "errors" + "log" + + "github.com/robotn/xgb" + "github.com/robotn/xgb/xinerama" + "github.com/robotn/xgb/xproto" + "github.com/robotn/xgbutil" + "github.com/robotn/xgbutil/ewmh" +) + +var xu *xgbutil.XUtil + +// GetBounds get the window bounds +func GetBounds(pid int, args ...int) (int, int, int, int) { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + return internalGetBounds(pid, isPid) + } + + xid, err := GetXid(xu, pid) + if err != nil { + log.Println("Get Xid from Pid errors is: ", err) + return 0, 0, 0, 0 + } + + return internalGetBounds(int(xid), isPid) +} + +// GetClient get the window client bounds +func GetClient(pid int, args ...int) (int, int, int, int) { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + return internalGetClient(pid, isPid) + } + + xid, err := GetXid(xu, pid) + if err != nil { + log.Println("Get Xid from Pid errors is: ", err) + return 0, 0, 0, 0 + } + + return internalGetClient(int(xid), isPid) +} + +// internalGetTitle get the window title +func internalGetTitle(pid int, args ...int) string { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + return cgetTitle(pid, isPid) + } + + xid, err := GetXid(xu, pid) + if err != nil { + log.Println("Get Xid from Pid errors is: ", err) + return "" + } + + return cgetTitle(int(xid), isPid) +} + +// ActivePidC active the window by Pid, +// If args[0] > 0 on the unix platform via a xid to active +func ActivePidC(pid int, args ...int) error { + var isPid int + if len(args) > 0 || NotPid { + isPid = 1 + internalActive(pid, isPid) + return nil + } + + xid, err := GetXid(xu, pid) + if err != nil { + log.Println("Get Xid from Pid errors is: ", err) + return err + } + + internalActive(int(xid), isPid) + return nil +} + +// ActivePid active the window by Pid, +// +// If args[0] > 0 on the Windows platform via a window handle to active, +// If args[0] > 0 on the unix platform via a xid to active +func ActivePid(pid int, args ...int) error { + if xu == nil { + var err error + xu, err = xgbutil.NewConn() + if err != nil { + return err + } + } + + if len(args) > 0 { + err := ewmh.ActiveWindowReq(xu, xproto.Window(pid)) + if err != nil { + return err + } + + return nil + } + + // get the xid from pid + xid, err := GetXidFromPid(xu, pid) + if err != nil { + return err + } + + err = ewmh.ActiveWindowReq(xu, xid) + if err != nil { + return err + } + + return nil +} + +// GetXid get the xid return window and error +func GetXid(xu *xgbutil.XUtil, pid int) (xproto.Window, error) { + if xu == nil { + var err error + xu, err = xgbutil.NewConn() + if err != nil { + // log.Println("xgbutil.NewConn errors is: ", err) + return 0, err + } + } + + xid, err := GetXidFromPid(xu, pid) + return xid, err +} + +// GetXidFromPid get the xid from pid +func GetXidFromPid(xu *xgbutil.XUtil, pid int) (xproto.Window, error) { + windows, err := ewmh.ClientListGet(xu) + if err != nil { + return 0, err + } + + for _, window := range windows { + wmPid, err := ewmh.WmPidGet(xu, window) + if err != nil { + return 0, err + } + + if uint(pid) == wmPid { + return window, nil + } + } + + return 0, errors.New("failed to find a window with a matching pid.") +} + +// DisplaysNum get the count of displays +func DisplaysNum() int { + c, err := xgb.NewConn() + if err != nil { + return 0 + } + defer c.Close() + + err = xinerama.Init(c) + if err != nil { + return 0 + } + + reply, err := xinerama.QueryScreens(c).Reply() + if err != nil { + return 0 + } + + return int(reply.Number) +} + +// GetMainId get the main display id +func GetMainId() int { + conn, err := xgb.NewConn() + if err != nil { + return -1 + } + + setup := xproto.Setup(conn) + defaultScreen := setup.DefaultScreen(conn) + id := -1 + for i, screen := range setup.Roots { + if defaultScreen.Root == screen.Root { + id = i + break + } + } + return id +} + +// Alert show a alert window +// Displays alert with the attributes. +// If cancel button is not given, only the default button is displayed +// +// Examples: +// +// robotgo.Alert("hi", "window", "ok", "cancel") +func Alert(title, msg string, args ...string) bool { + defaultBtn, cancelBtn := alertArgs(args...) + c := `xmessage -center ` + msg + + ` -title ` + title + ` -buttons ` + defaultBtn + ":0," + if cancelBtn != "" { + c += cancelBtn + ":1" + } + c += ` -default ` + defaultBtn + c += ` -geometry 400x200` + + out, err := Run(c) + if err != nil { + // fmt.Println("Alert: ", err, ". ", string(out)) + return false + } + + if string(out) == "1" { + return false + } + return true +} diff --git a/screen.go b/screen.go new file mode 100644 index 00000000..b0852bb1 --- /dev/null +++ b/screen.go @@ -0,0 +1,63 @@ +// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// https://github.com/go-vgo/robotgo/blob/master/LICENSE +// +// Licensed under the Apache License, Version 2.0 +// +// This file may not be copied, modified, or distributed +// except according to those terms. + +package robotgo + +import ( + "image" + + // "github.com/kbinani/screenshot" + "github.com/vcaesar/screenshot" +) + +// GetDisplayBounds gets the display screen bounds +func GetDisplayBounds(i int) (x, y, w, h int) { + bs := screenshot.GetDisplayBounds(i) + return bs.Min.X, bs.Min.Y, bs.Dx(), bs.Dy() +} + +// GetDisplayRect gets the display rect +func GetDisplayRect(i int) Rect { + x, y, w, h := GetDisplayBounds(i) + return Rect{ + Point{X: x, Y: y}, + Size{W: w, H: h}} +} + +// Capture capture the screenshot, use the CaptureImg default +func Capture(args ...int) (*image.RGBA, error) { + displayId := 0 + if DisplayID != -1 { + displayId = DisplayID + } + + if len(args) > 4 { + displayId = args[4] + } + + var x, y, w, h int + if len(args) > 3 { + x, y, w, h = args[0], args[1], args[2], args[3] + } else { + x, y, w, h = GetDisplayBounds(displayId) + } + + return screenshot.Capture(x, y, w, h) +} + +// SaveCapture capture screen and save the screenshot to image +func SaveCapture(path string, args ...int) error { + img, err := CaptureImg(args...) + if err != nil { + return err + } + + return Save(img, path) +} diff --git a/screen/goScreen.h b/screen/goScreen.h index 648f73f0..a4bab458 100644 --- a/screen/goScreen.h +++ b/screen/goScreen.h @@ -3,91 +3,74 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. #include "../base/types.h" +#include "../base/pubs.h" #include "../base/rgb.h" #include "screengrab_c.h" -#include "screen_c.h" -// #include "../MMBitmap_c.h" +#include -void padHex(MMRGBHex color, char* hex){ +void padHex(MMRGBHex color, char* hex) { // Length needs to be 7 because snprintf includes a terminating null. - // Use %06x to pad hex value with leading 0s. snprintf(hex, 7, "%06x", color); } -char* pad_hex(MMRGBHex color){ +char* pad_hex(MMRGBHex color) { char hex[7]; padHex(color, hex); // destroyMMBitmap(bitmap); char* str = (char*)calloc(100, sizeof(char*)); if (str) { strcpy(str, hex); } - return str; } static uint8_t rgb[3]; -uint8_t* color_hex_to_rgb(uint32_t h){ +uint8_t* color_hex_to_rgb(uint32_t h) { rgb[0] = RED_FROM_HEX(h); rgb[1] = GREEN_FROM_HEX(h); rgb[2] = BLUE_FROM_HEX(h); return rgb; } -uint32_t color_rgb_to_hex(uint8_t r, uint8_t g, uint8_t b){ +uint32_t color_rgb_to_hex(uint8_t r, uint8_t g, uint8_t b) { return RGB_TO_HEX(r, g, b); } -MMRGBHex get_px_color(int32_t x, int32_t y){ +MMRGBHex get_px_color(int32_t x, int32_t y, int32_t display_id) { MMBitmapRef bitmap; MMRGBHex color; - if (!pointVisibleOnMainDisplay(MMPointInt32Make(x, y))){ + if (!pointVisibleOnMainDisplay(MMPointInt32Make(x, y))) { return color; } - bitmap = copyMMBitmapFromDisplayInRect(MMRectInt32Make(x, y, 1, 1)); - // bitmap = MMRectMake(x, y, 1, 1); - + bitmap = copyMMBitmapFromDisplayInRect(MMRectInt32Make(x, y, 1, 1), display_id, 0); color = MMRGBHexAtPoint(bitmap, 0, 0); destroyMMBitmap(bitmap); return color; } -char* get_pixel_color(int32_t x, int32_t y){ - MMRGBHex color = get_px_color(x, y); - - char* s = pad_hex(color); - return s; -} - -MMSizeInt32 get_screen_size(){ - // Get display size. - MMSizeInt32 displaySize = getMainDisplaySize(); - return displaySize; -} - -char* set_XDisplay_name(char* name){ +char* set_XDisplay_name(char* name) { #if defined(USE_X11) setXDisplay(name); - return "success"; + return ""; #else return "SetXDisplayName is only supported on Linux"; #endif } -char* get_XDisplay_name(){ +char* get_XDisplay_name() { #if defined(USE_X11) const char* display = getXDisplay(); + char* sd = (char*)calloc(100, sizeof(char*)); - if (sd) { strcpy(sd, display); } return sd; #else @@ -95,18 +78,51 @@ char* get_XDisplay_name(){ #endif } +void close_main_display() { + #if defined(USE_X11) + XCloseMainDisplay(); + #else + // + #endif +} + +uint32_t get_num_displays() { + #if defined(IS_MACOSX) + uint32_t count = 0; + if (CGGetActiveDisplayList(0, nil, &count) == kCGErrorSuccess) { + return count; + } + return 0; + #elif defined(USE_X11) + return 0; + #elif defined(IS_WINDOWS) + uint32_t count = 0; + if (EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&count)) { + return count; + } + return 0; + #endif +} + +uintptr get_hwnd_by_pid(uintptr pid) { + #if defined(IS_WINDOWS) + HWND hwnd = GetHwndByPid(pid); + return (uintptr)hwnd; + #else + return 0; + #endif +} + +void bitmap_dealloc(MMBitmapRef bitmap) { + if (bitmap != NULL) { + destroyMMBitmap(bitmap); + bitmap = NULL; + } +} + // capture_screen capture screen -MMBitmapRef capture_screen(int32_t x, int32_t y, int32_t w, int32_t h){ - // if (){ - // x = 0; - // y = 0; - // // Get screen size. - // MMSize displaySize = getMainDisplaySize(); - // w = displaySize.width; - // h = displaySize.height; - // } - MMBitmapRef bitmap = copyMMBitmapFromDisplayInRect(MMRectInt32Make(x, y, w, h)); - // printf("%s\n", bitmap); +MMBitmapRef capture_screen(int32_t x, int32_t y, int32_t w, int32_t h, int32_t display_id, int8_t isPid) { + MMBitmapRef bitmap = copyMMBitmapFromDisplayInRect(MMRectInt32Make(x, y, w, h), display_id, isPid); return bitmap; } diff --git a/screen/screen.go b/screen/screen.go new file mode 100644 index 00000000..7424d9d0 --- /dev/null +++ b/screen/screen.go @@ -0,0 +1 @@ +package screen diff --git a/screen/screen.h b/screen/screen.h deleted file mode 100644 index 9cc9887b..00000000 --- a/screen/screen.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#ifndef SCREEN_H -#define SCREEN_H - -#include "../base/types.h" - -#if defined(_MSC_VER) - #include "../base/ms_stdbool.h" -#else - #include -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Returns the size of the main display. */ -MMSizeInt32 getMainDisplaySize(void); - -/* Convenience function that returns whether the given point is in the bounds - * of the main screen. */ -bool pointVisibleOnMainDisplay(MMPointInt32 point); - -#ifdef __cplusplus -} -#endif - -#endif /* SCREEN_H */ diff --git a/screen/screen_c.h b/screen/screen_c.h index 9f9f2cd9..732feaea 100644 --- a/screen/screen_c.h +++ b/screen/screen_c.h @@ -1,14 +1,74 @@ -#include "screen.h" //#include "../base/os.h" #if defined(IS_MACOSX) #include #elif defined(USE_X11) #include + #include // #include "../base/xdisplay_c.h" #endif -MMSizeInt32 getMainDisplaySize(void){ +intptr scaleX(); + +double sys_scale(int32_t display_id) { + #if defined(IS_MACOSX) + CGDirectDisplayID displayID = (CGDirectDisplayID) display_id; + if (displayID == -1) { + displayID = CGMainDisplayID(); + } + + CGDisplayModeRef modeRef = CGDisplayCopyDisplayMode(displayID); + double pixelWidth = CGDisplayModeGetPixelWidth(modeRef); + double targetWidth = CGDisplayModeGetWidth(modeRef); + + return pixelWidth / targetWidth; + #elif defined(USE_X11) + Display *dpy = XOpenDisplay(NULL); + + int scr = 0; /* Screen number */ + double xres = ((((double) DisplayWidth(dpy, scr)) * 25.4) / + ((double) DisplayWidthMM(dpy, scr))); + + char *rms = XResourceManagerString(dpy); + if (rms) { + XrmDatabase db = XrmGetStringDatabase(rms); + if (db) { + XrmValue value; + char *type = NULL; + + if (XrmGetResource(db, "Xft.dpi", "String", &type, &value)) { + if (value.addr) { + xres = atof(value.addr); + } + } + + XrmDestroyDatabase(db); + } + } + XCloseDisplay (dpy); + + return xres / 96.0; + #elif defined(IS_WINDOWS) + double s = scaleX() / 96.0; + return s; + #endif +} + +intptr scaleX(){ + #if defined(IS_MACOSX) + return 0; + #elif defined(USE_X11) + return 0; + #elif defined(IS_WINDOWS) + // Get desktop dc + HDC desktopDc = GetDC(NULL); + // Get native resolution + intptr horizontalDPI = GetDeviceCaps(desktopDc, LOGPIXELSX); + return horizontalDPI; + #endif +} + +MMSizeInt32 getMainDisplaySize(void) { #if defined(IS_MACOSX) CGDirectDisplayID displayID = CGMainDisplayID(); CGRect displayRect = CGDisplayBounds(displayID); @@ -19,15 +79,51 @@ MMSizeInt32 getMainDisplaySize(void){ Display *display = XGetMainDisplay(); const int screen = DefaultScreen(display); - return MMSizeInt32Make((int32_t)DisplayWidth(display, screen), - (int32_t)DisplayHeight(display, screen)); + return MMSizeInt32Make( + (int32_t)DisplayWidth(display, screen), + (int32_t)DisplayHeight(display, screen)); +#elif defined(IS_WINDOWS) + return MMSizeInt32Make( + (int32_t)GetSystemMetrics(SM_CXSCREEN), + (int32_t)GetSystemMetrics(SM_CYSCREEN)); +#endif +} + +MMRectInt32 getScreenRect(int32_t display_id) { +#if defined(IS_MACOSX) + CGDirectDisplayID displayID = (CGDirectDisplayID) display_id; + if (display_id == -1) { + displayID = CGMainDisplayID(); + } + CGRect displayRect = CGDisplayBounds(displayID); + + CGPoint point = displayRect.origin; + CGSize size = displayRect.size; + return MMRectInt32Make( + (int32_t)point.x, (int32_t)point.y, + (int32_t)size.width, (int32_t)size.height); +#elif defined(USE_X11) + Display *display = XGetMainDisplay(); + const int screen = DefaultScreen(display); + + return MMRectInt32Make( + (int32_t)0, (int32_t)0, + (int32_t)DisplayWidth(display, screen), + (int32_t)DisplayHeight(display, screen)); #elif defined(IS_WINDOWS) - if (GetSystemMetrics(SM_CMONITORS) == 1) { - return MMSizeInt32Make((int32_t)GetSystemMetrics(SM_CXSCREEN), - (int32_t)GetSystemMetrics(SM_CYSCREEN)); - } else { - return MMSizeInt32Make((int32_t)GetSystemMetrics(SM_CXVIRTUALSCREEN), - (int32_t)GetSystemMetrics(SM_CYVIRTUALSCREEN)); + if (GetSystemMetrics(SM_CMONITORS) == 1 + || display_id == -1 || display_id == 0) { + return MMRectInt32Make( + (int32_t)0, + (int32_t)0, + (int32_t)GetSystemMetrics(SM_CXSCREEN), + (int32_t)GetSystemMetrics(SM_CYSCREEN)); + } else { + return MMRectInt32Make( + (int32_t)GetSystemMetrics(SM_XVIRTUALSCREEN), + (int32_t)GetSystemMetrics(SM_YVIRTUALSCREEN), + (int32_t)GetSystemMetrics(SM_CXVIRTUALSCREEN), + (int32_t)GetSystemMetrics(SM_CYVIRTUALSCREEN)); } #endif } diff --git a/screen/screengrab.h b/screen/screengrab.h deleted file mode 100644 index b40badd5..00000000 --- a/screen/screengrab.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#ifndef SCREENGRAB_H -#define SCREENGRAB_H - -#include "../base/types.h" -#include "../base/MMBitmap_c.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Returns a raw bitmap of screengrab of the display (to be destroyed()'d by - * caller), or NULL on error. */ -MMBitmapRef copyMMBitmapFromDisplayInRect(MMRectInt32 rect); - -#ifdef __cplusplus -} -#endif - -#endif /* SCREENGRAB_H */ diff --git a/screen/screengrab_c.h b/screen/screengrab_c.h index 358f6a3e..68f674da 100644 --- a/screen/screengrab_c.h +++ b/screen/screengrab_c.h @@ -1,82 +1,126 @@ -#include "screengrab.h" -#include "../base/bmp_io_c.h" -#include "../base/endian.h" +#include "../base/bitmap_free_c.h" #include /* malloc() */ #if defined(IS_MACOSX) #include #include #include + #include #elif defined(USE_X11) #include #include #include "../base/xdisplay_c.h" #elif defined(IS_WINDOWS) - // #include "windows.h" - // #include #include #endif +#include "screen_c.h" + +#if defined(IS_MACOSX) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 140400 + static CGImageRef capture15(CGDirectDisplayID id, CGRect diIntersectDisplayLocal, CGColorSpaceRef colorSpace) { + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + __block CGImageRef image1 = nil; + [SCShareableContent getShareableContentWithCompletionHandler:^(SCShareableContent* content, NSError* error) { + @autoreleasepool { + if (error) { + dispatch_semaphore_signal(semaphore); + return; + } + + SCDisplay* target = nil; + for (SCDisplay *display in content.displays) { + if (display.displayID == id) { + target = display; + break; + } + } + if (!target) { + dispatch_semaphore_signal(semaphore); + return; + } + + SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:target excludingWindows:@[]]; + SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init]; + config.queueDepth = 5; + config.sourceRect = diIntersectDisplayLocal; + config.width = diIntersectDisplayLocal.size.width * sys_scale(id); + config.height = diIntersectDisplayLocal.size.height * sys_scale(id); + config.scalesToFit = false; + config.captureResolution = 1; + + [SCScreenshotManager captureImageWithFilter:filter + configuration:config + completionHandler:^(CGImageRef img, NSError* error) { + if (!error) { + image1 = CGImageCreateCopyWithColorSpace(img, colorSpace); + } + dispatch_semaphore_signal(semaphore); + }]; + } + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + dispatch_release(semaphore); + return image1; + } +#endif -MMBitmapRef copyMMBitmapFromDisplayInRect(MMRectInt32 rect){ +MMBitmapRef copyMMBitmapFromDisplayInRect(MMRectInt32 rect, int32_t display_id, int8_t isPid) { #if defined(IS_MACOSX) - MMBitmapRef bitmap = NULL; uint8_t *buffer = NULL; size_t bufferSize = 0; - CGDirectDisplayID displayID = CGMainDisplayID(); - - CGImageRef image = CGDisplayCreateImageForRect(displayID, - CGRectMake(rect.origin.x, - rect.origin.y, - rect.size.w, - rect.size.h)); + CGDirectDisplayID displayID = (CGDirectDisplayID) display_id; + if (displayID == -1 || displayID == 0) { + displayID = CGMainDisplayID(); + } + MMPointInt32 o = rect.origin; MMSizeInt32 s = rect.size; + #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 140400 + CGColorSpaceRef color = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + CGImageRef image = capture15(displayID, CGRectMake(o.x, o.y, s.w, s.h), color); + CGColorSpaceRelease(color); + #else + // This API is deprecated in macos 15, use ScreenCaptureKit's captureScreenshot + CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(o.x, o.y, s.w, s.h)); + #endif if (!image) { return NULL; } - + CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(image)); - if (!imageData) { return NULL; } bufferSize = CFDataGetLength(imageData); buffer = malloc(bufferSize); - CFDataGetBytes(imageData, CFRangeMake(0, bufferSize), buffer); - bitmap = createMMBitmap(buffer, - CGImageGetWidth(image), - CGImageGetHeight(image), - CGImageGetBytesPerRow(image), - CGImageGetBitsPerPixel(image), - CGImageGetBitsPerPixel(image) / 8); + bitmap = createMMBitmap_c(buffer, + CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBytesPerRow(image), + CGImageGetBitsPerPixel(image), CGImageGetBitsPerPixel(image) / 8); CFRelease(imageData); - CGImageRelease(image); return bitmap; #elif defined(USE_X11) MMBitmapRef bitmap; + Display *display; + if (display_id == -1) { + display = XOpenDisplay(NULL); + } else { + display = XGetMainDisplay(); + } - Display *display = XOpenDisplay(NULL); - XImage *image = XGetImage(display, - XDefaultRootWindow(display), - (int)rect.origin.x, - (int)rect.origin.y, - (unsigned int)rect.size.w, - (unsigned int)rect.size.h, - AllPlanes, ZPixmap); + MMPointInt32 o = rect.origin; MMSizeInt32 s = rect.size; + XImage *image = XGetImage(display, XDefaultRootWindow(display), + (int)o.x, (int)o.y, (unsigned int)s.w, (unsigned int)s.h, + AllPlanes, ZPixmap); XCloseDisplay(display); - if (image == NULL) return NULL; - - bitmap = createMMBitmap((uint8_t *)image->data, - rect.size.w, - rect.size.h, - (size_t)image->bytes_per_line, - (uint8_t)image->bits_per_pixel, - (uint8_t)image->bits_per_pixel / 8); - image->data = NULL; /* Steal ownership of bitmap data so we don't have to - * copy it. */ + if (image == NULL) { return NULL; } + + bitmap = createMMBitmap_c((uint8_t *)image->data, + s.w, s.h, (size_t)image->bytes_per_line, + (uint8_t)image->bits_per_pixel, (uint8_t)image->bits_per_pixel / 8); + image->data = NULL; /* Steal ownership of bitmap data so we don't have to copy it. */ XDestroyImage(image); return bitmap; @@ -87,52 +131,52 @@ MMBitmapRef copyMMBitmapFromDisplayInRect(MMRectInt32 rect){ HBITMAP dib; BITMAPINFO bi; + int32_t x = rect.origin.x, y = rect.origin.y; + int32_t w = rect.size.w, h = rect.size.h; + /* Initialize bitmap info. */ bi.bmiHeader.biSize = sizeof(bi.bmiHeader); - bi.bmiHeader.biWidth = (long)rect.size.w; - bi.bmiHeader.biHeight = -(long)rect.size.h; /* Non-cartesian, please */ + bi.bmiHeader.biWidth = (long) w; + bi.bmiHeader.biHeight = -(long) h; /* Non-cartesian, please */ bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; - bi.bmiHeader.biSizeImage = (DWORD)(4 * rect.size.w * rect.size.h); + bi.bmiHeader.biSizeImage = (DWORD)(4 * w * h); bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; - screen = GetDC(NULL); /* Get entire screen */ - if (screen == NULL) return NULL; + HWND hwnd; + if (display_id == -1 || isPid == 0) { + // screen = GetDC(NULL); /* Get entire screen */ + hwnd = GetDesktopWindow(); + } else { + hwnd = (HWND) (uintptr) display_id; + } + screen = GetDC(hwnd); + + if (screen == NULL) { return NULL; } + // Todo: Use DXGI + screenMem = CreateCompatibleDC(screen); /* Get screen data in display device context. */ dib = CreateDIBSection(screen, &bi, DIB_RGB_COLORS, &data, NULL, 0); /* Copy the data into a bitmap struct. */ - if ((screenMem = CreateCompatibleDC(screen)) == NULL || - SelectObject(screenMem, dib) == NULL || - !BitBlt(screenMem, - (int)0, - (int)0, - (int)rect.size.w, - (int)rect.size.h, - screen, - rect.origin.x, - rect.origin.y, - SRCCOPY)) { - + BOOL b = (screenMem == NULL) || + SelectObject(screenMem, dib) == NULL || + !BitBlt(screenMem, (int)0, (int)0, (int)w, (int)h, screen, x, y, SRCCOPY); + if (b) { /* Error copying data. */ - ReleaseDC(NULL, screen); + ReleaseDC(hwnd, screen); DeleteObject(dib); - if (screenMem != NULL) DeleteDC(screenMem); + if (screenMem != NULL) { DeleteDC(screenMem); } return NULL; } - bitmap = createMMBitmap(NULL, - rect.size.w, - rect.size.h, - 4 * rect.size.w, - (uint8_t)bi.bmiHeader.biBitCount, - 4); + bitmap = createMMBitmap_c(NULL, w, h, 4 * w, (uint8_t)bi.bmiHeader.biBitCount, 4); /* Copy the data to our pixel buffer. */ if (bitmap != NULL) { @@ -140,7 +184,7 @@ MMBitmapRef copyMMBitmapFromDisplayInRect(MMRectInt32 rect){ memcpy(bitmap->imageBuffer, data, bitmap->bytewidth * bitmap->height); } - ReleaseDC(NULL, screen); + ReleaseDC(hwnd, screen); DeleteObject(dib); DeleteDC(screenMem); diff --git a/test/index.html b/test/index.html new file mode 100644 index 00000000..e18582cd --- /dev/null +++ b/test/index.html @@ -0,0 +1,38 @@ +

Type and check the console

+ + \ No newline at end of file diff --git a/test/main.go b/test/main.go deleted file mode 100644 index 26664119..00000000 --- a/test/main.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -package main - -import ( - "fmt" - "reflect" - - "github.com/go-vgo/robotgo" -) - -func aRobotgo() { - abool := robotgo.ShowAlert("test", "robotgo") - if abool == 0 { - fmt.Println("ok@@@", "ok") - } - - x, y := robotgo.GetMousePos() - fmt.Println("pos:", x, y) - - robotgo.MoveMouse(x, y) - robotgo.MoveMouse(100, 200) - - robotgo.MouseToggle("up") - - for i := 0; i < 1080; i += 1000 { - fmt.Println(i) - robotgo.MoveMouse(800, i) - } - - fmt.Println(robotgo.GetPixelColor(x, y)) - - color := robotgo.GetPixelColor(100, 200) - fmt.Println("color@@@", color) - - robotgo.TypeString("Hello World") - // robotgo.KeyTap("a", "control") - robotgo.KeyTap("f1", "control") - // robotgo.KeyTap("enter") - // robotgo.KeyToggle("enter", "down") - robotgo.TypeString("en") - - abitmap := robotgo.CaptureScreen() - fmt.Println("all...", abitmap) - - bitmap := robotgo.CaptureScreen(10, 20, 30, 40) - fmt.Println("...", bitmap) - - fx, fy := robotgo.FindBitmap(bitmap) - fmt.Println("FindBitmap------", fx, fy) - - robotgo.SaveBitmap(bitmap, "test.png", 1) - - var bitmapTest robotgo.Bitmap - bitTest := robotgo.OpenBitmap("test.png") - bitmapTest = robotgo.ToBitmap(bitTest) - fmt.Println("...type", reflect.TypeOf(bitTest), reflect.TypeOf(bitmapTest)) - - // robotgo.MouseClick() - robotgo.ScrollMouse(10, "up") -} - -func main() { - aRobotgo() -} diff --git a/wayland_n.go b/wayland_n.go new file mode 100644 index 00000000..bc07c4d1 --- /dev/null +++ b/wayland_n.go @@ -0,0 +1,2 @@ +// +bulid linux,next +package robotgo diff --git a/window/alert.h b/window/alert.h deleted file mode 100644 index 9eb5e9c5..00000000 --- a/window/alert.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#ifndef ALERT_H -#define ALERT_H - -#if defined(_MSC_VER) - #include "ms_stdbool.h" -#else - #include -#endif - -/* Displays alert with given attributes, and blocks execution until the user - * responds. Returns 0 if defaultButton was pressed, 1 if cancelButton was - * pressed, or -1 if an error occurred. */ -int showAlert(const char *title, const char *msg, - const char *defaultButton, const char *cancelButton); - -#endif /* ALERT_H */ diff --git a/window/alert_c.h b/window/alert_c.h index 46a2048d..290786d4 100644 --- a/window/alert_c.h +++ b/window/alert_c.h @@ -1,182 +1,42 @@ -#include "alert.h" // #include "os.h" -#include - #if defined(IS_MACOSX) #include -#elif defined(USE_X11) - #include /* For fputs() */ - #include /* For exit() */ - #include /* For wait() */ - #include /* For fork() */ - #include /* For pid_t */ - #include "../base/snprintf.h" /* For asprintf() */ -#endif - -#if defined(USE_X11) - -enum { - TASK_SUCCESS = 0, - FORK_FAILED = -1, - EXEC_FAILED = -2 -}; - -/* - * Unfortunately, X has no standard method of displaying alerts, so instead we - * have to rely on the shell command "xmessage" (or nicer-looking equivalents). - * - * The return value and arguments are the same as those from to runTask() - * (see below). - */ -static int xmessage(char *argv[], int *exit_status); - -#elif defined(IS_MACOSX) - #define CFStringCreateWithUTF8String(string) \ - ((string) == NULL ? NULL : CFStringCreateWithCString(NULL, \ - string, \ - kCFStringEncodingUTF8)) #endif -int showAlert(const char *title, const char *msg, const char *defaultButton, - const char *cancelButton) -{ #if defined(IS_MACOSX) - CFStringRef alertHeader = CFStringCreateWithUTF8String(title); - CFStringRef alertMessage = CFStringCreateWithUTF8String(msg); - CFStringRef defaultButtonTitle = CFStringCreateWithUTF8String(defaultButton); - CFStringRef cancelButtonTitle = CFStringCreateWithUTF8String(cancelButton); - CFOptionFlags responseFlags; - SInt32 err = CFUserNotificationDisplayAlert(0.0, - kCFUserNotificationNoteAlertLevel, - NULL, - NULL, - NULL, - alertHeader, - alertMessage, - defaultButtonTitle, - cancelButtonTitle, - NULL, - &responseFlags); - - if (alertHeader != NULL) CFRelease(alertHeader); - if (alertMessage != NULL) CFRelease(alertMessage); - if (defaultButtonTitle != NULL) CFRelease(defaultButtonTitle); - if (cancelButtonTitle != NULL) CFRelease(cancelButtonTitle); - - if (err != 0) { return -1; } - return (responseFlags == kCFUserNotificationDefaultResponse) ? 0 : 1; -#elif defined(USE_X11) - /* Note that args[0] is set by the xmessage() function. */ - const char *args[10] = {NULL, msg, "-title", title, "-center"}; - int response, ret; - char *buttonList = NULL; /* To be free()'d. */ - - if (defaultButton == NULL) defaultButton = "OK"; - - if (cancelButton == NULL) { - asprintf(&buttonList, "%s:2", defaultButton); - } else { - asprintf(&buttonList, "%s:2,%s:3", defaultButton, cancelButton); - } - - if (buttonList == NULL) { return -1; /* asprintf() failed. */ } - args[5] = "-buttons"; - args[6] = buttonList; - args[7] = "-default"; - args[8] = defaultButton; - args[9] = NULL; - - ret = xmessage((char **)args, &response); - if (buttonList != NULL) { - free(buttonList); - buttonList = NULL; - } - - if (ret != TASK_SUCCESS) { - if (ret == EXEC_FAILED) { - fputs("xmessage or equivalent not found.\n", stderr); - } - return -1; + CFStringRef CFStringCreateWithUTF8String(const char *title) { + if (title == NULL) { return NULL; } + return CFStringCreateWithCString(NULL, title, kCFStringEncodingUTF8); } - - return (response == 2) ? 0 : 1; -#else - /* TODO: Display custom buttons instead of the pre-defined "OK" - * and "Cancel". */ - int response = MessageBox(NULL, msg, title, - (cancelButton == NULL) ? MB_OK : MB_OKCANCEL); - return (response == IDOK) ? 0 : 1; #endif -} - -#if defined(USE_X11) - -/* - * Attempts to run the given task synchronously with the given arguments. - * - * If |exit_status| is non-NULL and the task ran successfully, |exit_status| is - * set to the exit code of the task on return. - * - * Returns -1 if process could not be forked, -2 if the task could not be run, - * or 0 if the task was ran successfully. - */ -static int runTask(const char *taskname, char * const argv[], int *exit_status); - -static int xmessage(char *argv[], int *exit_status) { - // static const char * const MSG_PROGS[] = {"gmessage", "gxmessage", - // "kmessage", "xmessage"}; - static const char * const MSG_PROGS[] = {"xmessage"}; - static int PREV_MSG_INDEX = -1; - #define MSG_PROGS_LEN (sizeof(MSG_PROGS) / sizeof(MSG_PROGS[0])) - - char *prog = NULL; - int ret; - - /* Save some fork()'ing and attempt to use last program if possible. */ - if (PREV_MSG_INDEX >= 0) { - assert(PREV_MSG_INDEX < MSG_PROGS_LEN); - - prog = argv[0] = (char *)MSG_PROGS[PREV_MSG_INDEX]; - ret = runTask(prog, argv, exit_status); - } else { - /* Otherwise, try running each xmessage alternative until one works or - * we run out of options. */ - size_t i; - for (i = 0; i < MSG_PROGS_LEN; ++i) { - prog = argv[0] = (char *)MSG_PROGS[i]; - ret = runTask(prog, argv, exit_status); - if (ret != EXEC_FAILED) break; - } - - if (ret == TASK_SUCCESS) PREV_MSG_INDEX = i; - } - - return ret; -} - -static int runTask(const char *taskname, char * const argv[], int *exit_status) { - pid_t pid = fork(); - int status; - switch (pid) { - case -1: /* Failed to fork */ - perror("fork"); - return FORK_FAILED; /* Failed to fork. */ - case 0: /* Child process */ - if (strcmp(argv[0], "xmessage") == 0){ - execvp(taskname, argv); - perror("execvp failed"); - } - exit(42); /* Failed to run task. */ - default: /* Parent process */ - wait(&status); /* Block execution until finished. */ - - if (!WIFEXITED(status) || (status = WEXITSTATUS(status)) == 42) { - return EXEC_FAILED; /* Task failed to run. */ - } - if (exit_status != NULL) *exit_status = status; - return TASK_SUCCESS; /* Success! */ - } +int showAlert(const char *title, const char *msg, + const char *defaultButton, const char *cancelButton) { + #if defined(IS_MACOSX) + CFStringRef alertHeader = CFStringCreateWithUTF8String(title); + CFStringRef alertMessage = CFStringCreateWithUTF8String(msg); + CFStringRef defaultButtonTitle = CFStringCreateWithUTF8String(defaultButton); + CFStringRef cancelButtonTitle = CFStringCreateWithUTF8String(cancelButton); + CFOptionFlags responseFlags; + + SInt32 err = CFUserNotificationDisplayAlert( + 0.0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL, alertHeader, alertMessage, + defaultButtonTitle, cancelButtonTitle, NULL, &responseFlags); + + if (alertHeader != NULL) CFRelease(alertHeader); + if (alertMessage != NULL) CFRelease(alertMessage); + if (defaultButtonTitle != NULL) CFRelease(defaultButtonTitle); + if (cancelButtonTitle != NULL) CFRelease(cancelButtonTitle); + + if (err != 0) { return -1; } + return (responseFlags == kCFUserNotificationDefaultResponse) ? 0 : 1; + #elif defined(USE_X11) + return 0; + #else + /* TODO: Display custom buttons instead of the pre-defined "OK" and "Cancel". */ + int response = MessageBox(NULL, msg, title, + (cancelButton == NULL) ? MB_OK : MB_OKCANCEL ); + return (response == IDOK) ? 0 : 1; + #endif } -#endif diff --git a/window/arr.h b/window/arr.h deleted file mode 100644 index 26bc8351..00000000 --- a/window/arr.h +++ /dev/null @@ -1,26 +0,0 @@ -// #include -// #include -// #include - -struct Arr{ - int len; - int cnu; - char** pName; - int *pId; -}; - -// int init_Arr(struct Arr *pArray, int len){ -// pArray->pName = (char**)malloc(sizeof(char*)*len); -// pArray->pId = (int*)malloc(sizeof(int)*len); -// if(NULL == pArray->pName){ -// printf("false \n"); -// return 1; -// }else{ -// pArray->len = len; -// pArray->cnu = 0; -// printf("true %d \n", pArray->len); -// return 0; -// } - -// return 0; -// } \ No newline at end of file diff --git a/window/goWindow.h b/window/goWindow.h index ea56f6f0..4e442a99 100644 --- a/window/goWindow.h +++ b/window/goWindow.h @@ -3,62 +3,32 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. #include "alert_c.h" #include "window.h" #include "win_sys.h" -int show_alert(const char *title, const char *msg, - const char *defaultButton, const char *cancelButton){ - - int alert = showAlert(title, msg, defaultButton, cancelButton); - return alert; -} - -intptr scale_x(){ - return scaleX(); -} - -intptr scale_y(){ - return scaleY(); -} - -bool is_valid(){ - bool abool = IsValid(); - return abool; -} - -// int find_window(char* name){ -// int z = findwindow(name); -// return z; -// } - -void min_window(uintptr pid, bool state, uintptr isHwnd){ +void min_window(uintptr pid, bool state, int8_t isPid){ #if defined(IS_MACOSX) // return 0; AXUIElementRef axID = AXUIElementCreateApplication(pid); - - AXUIElementSetAttributeValue(axID, kAXMinimizedAttribute, - state ? kCFBooleanTrue : kCFBooleanFalse); + AXUIElementSetAttributeValue(axID, kAXMinimizedAttribute, + state ? kCFBooleanTrue : kCFBooleanFalse); #elif defined(USE_X11) // Ignore X errors XDismissErrors(); // SetState((Window)pid, STATE_MINIMIZE, state); #elif defined(IS_WINDOWS) - if (isHwnd == 0) { - HWND hwnd = GetHwndByPId(pid); - win_min(hwnd, state); - } else { - win_min((HWND)pid, state); - } + HWND hwnd = getHwnd(pid, isPid); + win_min(hwnd, state); #endif } -void max_window(uintptr pid, bool state, uintptr isHwnd){ +void max_window(uintptr pid, bool state, int8_t isPid){ #if defined(IS_MACOSX) // return 0; #elif defined(USE_X11) @@ -66,26 +36,13 @@ void max_window(uintptr pid, bool state, uintptr isHwnd){ // SetState((Window)pid, STATE_MINIMIZE, false); // SetState((Window)pid, STATE_MAXIMIZE, state); #elif defined(IS_WINDOWS) - if (isHwnd == 0) { - HWND hwnd = GetHwndByPId(pid); - win_max(hwnd, state); - } else { - win_max((HWND)pid, state); - } + HWND hwnd = getHwnd(pid, isPid); + win_max(hwnd, state); #endif } -void close_window(uintptr pid, uintptr isHwnd){ - close_window_by_PId(pid, isHwnd); -} - -bool set_handle(uintptr handle){ - bool hwnd = setHandle(handle); - return hwnd; -} - uintptr get_handle(){ - MData mData = GetActive(); + MData mData = get_active(); #if defined(IS_MACOSX) return (uintptr)mData.CgID; @@ -96,32 +53,17 @@ uintptr get_handle(){ #endif } -uintptr bget_handle(){ - uintptr hwnd = getHandle(); - return hwnd; -} - -void set_active(const MData win){ - SetActive(win); -} - -void active_PID(uintptr pid, uintptr isHwnd){ - MData win = set_handle_pid(pid, isHwnd); - SetActive(win); -} - -MData get_active(){ - MData mdata = GetActive(); - return mdata; -} - -char* get_title(uintptr pid, uintptr isHwnd){ - char* title = get_title_by_pid(pid, isHwnd); - // printf("title::::%s\n", title ); - return title; +uintptr b_get_handle() { + #if defined(IS_MACOSX) + return (uintptr)pub_mData.CgID; + #elif defined(USE_X11) + return (uintptr)pub_mData.XWin; + #elif defined(IS_WINDOWS) + return (uintptr)pub_mData.HWnd; + #endif } -int32 get_PID(void){ - int pid = WGetPID(); - return pid; +void active_PID(uintptr pid, int8_t isPid){ + MData win = set_handle_pid(pid, isPid); + set_active(win); } diff --git a/window/process.h b/window/process.h deleted file mode 100644 index 03249678..00000000 --- a/window/process.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// #include -#include -#if defined(IS_MACOSX) - #if defined (__x86_64__) - #define RobotGo_64 - #else - #define RobotGo_32 - #endif - // #include - // #include - // #include - - // Apple process API - #include - #include - #include - - #ifdef MAC_OS_X_VERSION_10_11 - #define kAXValueCGPointType kAXValueTypeCGPoint - #define kAXValueCGSizeType kAXValueTypeCGSize - #endif - - #ifndef EXC_MASK_GUARD - #define EXC_MASK_GUARD 0 - #endif -#elif defined(USE_X11) - #if defined (__x86_64__) - #define RobotGo_64 - #else - #define RobotGo_32 - #endif - - #include - #include - - #ifndef X_HAVE_UTF8_STRING - #error It appears that X_HAVE_UTF8_STRING is not defined - \ - please verify that your version of XLib is supported - #endif -#elif defined(IS_WINDOWS) - #if defined (_WIN64) - #define RobotGo_64 - #else - #define RobotGo_32 - #endif - - #include - #include -#endif - -typedef signed char int8; // Signed 8-Bit integer -typedef signed short int16; // Signed 16-Bit integer -typedef signed int int32; // Signed 32-Bit integer -typedef signed long long int64; // Signed 64-Bit integer - -typedef unsigned char uint8; // Unsigned 8-Bit integer -typedef unsigned short uint16; // Unsigned 16-Bit integer -typedef unsigned int uint32; // Unsigned 32-Bit integer -typedef unsigned long long uint64; // Unsigned 64-Bit integer - -typedef float real32; // 32-Bit float value -typedef double real64; // 64-Bit float value - -#ifdef RobotGo_64 - - typedef int64 intptr; // Signed pointer integer - typedef uint64 uintptr; // Unsigned pointer integer - -#else - - typedef int32 intptr; // Signed pointer integer - typedef uint32 uintptr; // Unsigned pointer integer - -#endif -// - -struct _PData{ - int32 ProcID; // The process ID - - char* Name; // Name of process - char* Path; // Path of process - - bool Is64Bit; // Process is 64-Bit - -#if defined(IS_MACOSX) - - task_t Handle; // The mach task - -#elif defined(USE_X11) - - uint32 Handle; // Unused handle - -#elif defined(IS_WINDOWS) - - HANDLE Handle; // Process handle - -#endif -}; - -struct _PPData{ - int32 ProcID; // The process ID - - char** Name; // Name of process - char** Path; // Path of process - - bool Is64Bit; // Process is 64-Bit - -#if defined(IS_MACOSX) - - task_t Handle; // The mach task - -#elif defined(USE_X11) - - uint32 Handle; // Unused handle - -#elif defined(IS_WINDOWS) - - HANDLE Handle; // Process handle - -#endif -}; - -typedef struct _PData PData; diff --git a/window/pub.h b/window/pub.h index 2cf99d21..57f9e594 100644 --- a/window/pub.h +++ b/window/pub.h @@ -3,12 +3,17 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. // #include "../base/os.h" +#if defined(IS_MACOSX) + #include +#elif defined(USE_X11) + #include +#endif struct _MData{ #if defined(IS_MACOSX) @@ -23,49 +28,39 @@ struct _MData{ }; typedef struct _MData MData; +MData pub_mData; -MData mData; - -struct _Bounds{ - int32 X; // Top left X coordinate - int32 Y; // Top left Y coordinate - int32 W; // Total bounds width - int32 H; // Total bounds height +struct _Bounds { + int32_t X; // Top left X coordinate + int32_t Y; // Top left Y coordinate + int32_t W; // bounds width + int32_t H; // bounds height }; - typedef struct _Bounds Bounds; #if defined(IS_MACOSX) - static Boolean(*gAXIsProcessTrustedWithOptions) (CFDictionaryRef); - static CFStringRef* gkAXTrustedCheckOptionPrompt; AXError _AXUIElementGetWindow(AXUIElementRef, CGWindowID* out); - static AXUIElementRef GetUIElement(CGWindowID win){ intptr pid = 0; // double_t pid = 0; - // Create array storing window CGWindowID window[1] = { win }; - CFArrayRef wlist = CFArrayCreate(NULL, - (const void**)window, 1, NULL); + CFArrayRef wlist = CFArrayCreate(NULL, (const void**)window, 1, NULL); // Get window info CFArrayRef info = CGWindowListCreateDescriptionFromArray(wlist); CFRelease(wlist); // Check whether the resulting array is populated - if (info != NULL && CFArrayGetCount(info) > 0){ + if (info != NULL && CFArrayGetCount(info) > 0) { // Retrieve description from info array CFDictionaryRef desc = (CFDictionaryRef)CFArrayGetValueAtIndex(info, 0); - // Get window PID - CFNumberRef data =(CFNumberRef) - CFDictionaryGetValue(desc, kCGWindowOwnerPID); - - if (data != NULL){ + CFNumberRef data = (CFNumberRef) CFDictionaryGetValue(desc, kCGWindowOwnerPID); + if (data != NULL) { CFNumberGetValue(data, kCFNumberIntType, &pid); } @@ -74,17 +69,15 @@ typedef struct _Bounds Bounds; } // Check if PID was retrieved - if (pid <= 0) {return NULL;} + if (pid <= 0) { return NULL; } // Create an accessibility object using retrieved PID AXUIElementRef application = AXUIElementCreateApplication(pid); - if (application == 0) {return NULL;} CFArrayRef windows = NULL; // Get all windows associated with the app - AXUIElementCopyAttributeValues(application, - kAXWindowsAttribute, 0, 1024, &windows); + AXUIElementCopyAttributeValues(application, kAXWindowsAttribute, 0, 1024, &windows); // Reference to resulting value AXUIElementRef result = NULL; @@ -94,14 +87,11 @@ typedef struct _Bounds Bounds; // Loop all windows in the process for (CFIndex i = 0; i < count; ++i){ // Get the element at the index - AXUIElementRef element = (AXUIElementRef) - CFArrayGetValueAtIndex(windows, i); - + AXUIElementRef element = (AXUIElementRef) CFArrayGetValueAtIndex(windows, i); CGWindowID temp = 0; // Use undocumented API to get WindowID _AXUIElementGetWindow(element, &temp); - // Check results if (temp == win) { // Retain element CFRetain(element); @@ -117,15 +107,11 @@ typedef struct _Bounds Bounds; return result; } #elif defined(USE_X11) - // Error Handling - typedef int (*XErrorHandler) (Display*, XErrorEvent*); static int XHandleError(Display* dp, XErrorEvent* e) { return 0; } - XErrorHandler mOld; - void XDismissErrors (void) { Display *rDisplay = XOpenDisplay(NULL); // Save old handler and dismiss errors @@ -135,15 +121,15 @@ typedef struct _Bounds Bounds; // Reinstate old handler XSetErrorHandler(mOld); + XCloseDisplay(rDisplay); } // Definitions - struct Hints{ unsigned long Flags; unsigned long Funcs; unsigned long Decorations; - signed long Mode; + signed long Mode; unsigned long Stat; }; @@ -182,12 +168,11 @@ typedef struct _Bounds Bounds; WM_ACTIVE = XInternAtom(rDisplay, "_NET_ACTIVE_WINDOW", True); WM_HINTS = XInternAtom(rDisplay, "_MOTIF_WM_HINTS", True); WM_EXTENTS = XInternAtom(rDisplay, "_NET_FRAME_EXTENTS", True); + XCloseDisplay(rDisplay); } - - // Functions - static void* GetWindowProperty(MData win, Atom atom, uint32* items){ + static void* GetWindowProperty(MData win, Atom atom, uint32_t* items) { // Property variables Atom type; int format; unsigned long nItems; @@ -198,37 +183,34 @@ typedef struct _Bounds Bounds; // Check the atom if (atom != None) { // Retrieve and validate the specified property - if (!XGetWindowProperty(rDisplay, win.XWin, atom, 0, - BUFSIZ, False, AnyPropertyType, &type, &format, - &nItems, &bAfter, &result) && result && nItems) { + if (!XGetWindowProperty(rDisplay, win.XWin, atom, 0, + BUFSIZ, False, AnyPropertyType, &type, &format, &nItems, &bAfter, &result) + && result && nItems) { // Copy items result if (items != NULL) { - *items = (uint32) nItems; + *items = (uint32_t) nItems; } - + XCloseDisplay(rDisplay); return result; } } // Reset the items result if valid - if (items != NULL) {*items = 0;} - - // Free the result if it got allocated + if (items != NULL) { *items = 0; } if (result != NULL) { - XFree (result); + XFree(result); } + XCloseDisplay(rDisplay); return NULL; } ////// - #define STATE_TOPMOST 0 #define STATE_MINIMIZE 1 #define STATE_MAXIMIZE 2 - ////// static void SetDesktopForWindow(MData win){ Display *rDisplay = XOpenDisplay(NULL); @@ -236,7 +218,6 @@ typedef struct _Bounds Bounds; if (WM_DESKTOP != None && WM_CURDESK != None) { // Get desktop property long* desktop = (long*)GetWindowProperty(win, WM_DESKTOP,NULL); - // Check result value if (desktop != NULL) { // Retrieve the screen number @@ -255,40 +236,53 @@ typedef struct _Bounds Bounds; e.data.l[1] = CurrentTime; // Send the message - XSendEvent(rDisplay, - root, False, SubstructureNotifyMask | - SubstructureRedirectMask, (XEvent*) &e); + XSendEvent(rDisplay, root, False, SubstructureNotifyMask | SubstructureRedirectMask, + (XEvent*) &e); XFree(desktop); } } + XCloseDisplay(rDisplay); } static Bounds GetFrame(MData win){ Bounds frame; // Retrieve frame bounds if (WM_EXTENTS != None) { - long* result; uint32 nItems = 0; + long* result; uint32_t nItems = 0; // Get the window extents property result = (long*) GetWindowProperty(win, WM_EXTENTS, &nItems); - - // Verify the results if (result != NULL) { if (nItems == 4) { - frame.X = (int32) result[0]; - frame.Y = (int32) result[2]; - frame.W = (int32) result[0] + (int32) result[1]; - frame.H = (int32) result[2] + (int32) result[3]; + frame.X = (int32_t) result[0]; + frame.Y = (int32_t) result[2]; + frame.W = (int32_t) result[0] + (int32_t) result[1]; + frame.H = (int32_t) result[2] + (int32_t) result[3]; } XFree(result); } } - return frame; } #elif defined(IS_WINDOWS) - // + HWND getHwnd(uintptr pid, int8_t isPid); + + void win_min(HWND hwnd, bool state){ + if (state) { + ShowWindow(hwnd, SW_MINIMIZE); + } else { + ShowWindow(hwnd, SW_RESTORE); + } + } + + void win_max(HWND hwnd, bool state){ + if (state) { + ShowWindow(hwnd, SW_MAXIMIZE); + } else { + ShowWindow(hwnd, SW_RESTORE); + } + } #endif \ No newline at end of file diff --git a/window/win32.h b/window/win32.h deleted file mode 100644 index 8935aefc..00000000 --- a/window/win32.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://github.com/go-vgo/robotgo/blob/master/LICENSE -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// #include "../base/os.h" - -#if defined(IS_WINDOWS) - typedef struct{ - HWND hWnd; - DWORD dwPid; - }WNDINFO; - - BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam){ - WNDINFO* pInfo = (WNDINFO*)lParam; - DWORD dwProcessId = 0; - GetWindowThreadProcessId(hWnd, &dwProcessId); - - if (dwProcessId == pInfo->dwPid) { - pInfo->hWnd = hWnd; - return FALSE; - } - return TRUE; - } - - HWND GetHwndByPId(DWORD dwProcessId){ - WNDINFO info = {0}; - info.hWnd = NULL; - info.dwPid = dwProcessId; - EnumWindows(EnumWindowsProc, (LPARAM)&info); - // printf("%d\n", info.hWnd); - return info.hWnd; - } - - // window - void win_min(HWND hwnd, bool state){ - if (state) { - ShowWindow(hwnd, SW_MINIMIZE); - } else { - ShowWindow(hwnd, SW_RESTORE); - } - } - - void win_max(HWND hwnd, bool state){ - if (state) { - ShowWindow(hwnd, SW_MAXIMIZE); - } else { - ShowWindow(hwnd, SW_RESTORE); - } - } -#endif \ No newline at end of file diff --git a/window/win_sys.h b/window/win_sys.h index 4795d770..2185ebb3 100644 --- a/window/win_sys.h +++ b/window/win_sys.h @@ -3,126 +3,75 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. -// #include "../base/os.h" - -Bounds get_client(uintptr pid, uintptr isHwnd); - -intptr scaleX(){ - #if defined(IS_MACOSX) - return 0; - #elif defined(USE_X11) - return 0; - #elif defined(IS_WINDOWS) - // Get desktop dc - HDC desktopDc = GetDC(NULL); - // Get native resolution - intptr horizontalDPI = GetDeviceCaps(desktopDc, LOGPIXELSX); - // intptr verticalDPI = GetDeviceCaps(desktopDc, LOGPIXELSY); - return horizontalDPI; - #endif -} - -double sys_scale() { - #if defined(IS_MACOSX) - - CGDirectDisplayID displayID = CGMainDisplayID(); - CGDisplayModeRef modeRef = CGDisplayCopyDisplayMode(displayID); - - double pixelWidth = CGDisplayModeGetPixelWidth(modeRef); - double targetWidth = CGDisplayModeGetWidth(modeRef); - - return pixelWidth / targetWidth; - #elif defined(USE_X11) - - double xres; - Display *dpy; - - char *displayname = NULL; - int scr = 0; /* Screen number */ - - dpy = XOpenDisplay (displayname); - xres = ((((double) DisplayWidth(dpy, scr)) * 25.4) / - ((double) DisplayWidthMM(dpy, scr))); - - XCloseDisplay (dpy); - - return xres + 0.5; - #elif defined(IS_WINDOWS) - double s = scaleX() / 96.0; - return s; - #endif -} +// #if defined(USE_X11) +// #include +// #endif -intptr scaleY(){ - #if defined(IS_MACOSX) - return 0; - #elif defined(USE_X11) - return 0; - #elif defined(IS_WINDOWS) - // Get desktop dc - HDC desktopDc = GetDC(NULL); - // Get native resolution - intptr verticalDPI = GetDeviceCaps(desktopDc, LOGPIXELSY); - return verticalDPI; - #endif -} +Bounds get_client(uintptr pid, int8_t isPid); -Bounds get_bounds(uintptr pid, uintptr isHwnd){ +Bounds get_bounds(uintptr pid, int8_t isPid){ // Check if the window is valid Bounds bounds; - if (!IsValid()) { return bounds; } + if (!is_valid()) { return bounds; } #if defined(IS_MACOSX) - // Bounds bounds; AXValueRef axp = NULL; AXValueRef axs = NULL; AXUIElementRef AxID = AXUIElementCreateApplication(pid); + AXUIElementRef AxWin = NULL; + + // Get the window from the application + if (AXUIElementCopyAttributeValue(AxID, kAXFocusedWindowAttribute, (CFTypeRef *)&AxWin) + != kAXErrorSuccess || AxWin == NULL) { + // If no focused window, try to get the main window + if (AXUIElementCopyAttributeValue(AxID, kAXMainWindowAttribute, (CFTypeRef *)&AxWin) + != kAXErrorSuccess || AxWin == NULL) { + goto exit; + } + } // Determine the current point of the window - if (AXUIElementCopyAttributeValue( - AxID, kAXPositionAttribute, (CFTypeRef*) &axp) - != kAXErrorSuccess || axp == NULL){ + if (AXUIElementCopyAttributeValue(AxWin, kAXPositionAttribute, (CFTypeRef*) &axp) + != kAXErrorSuccess || axp == NULL) { goto exit; } // Determine the current size of the window - if (AXUIElementCopyAttributeValue( - AxID, kAXSizeAttribute, (CFTypeRef*) &axs) - != kAXErrorSuccess || axs == NULL){ + if (AXUIElementCopyAttributeValue(AxWin, kAXSizeAttribute, (CFTypeRef*) &axs) + != kAXErrorSuccess || axs == NULL) { goto exit; } CGPoint p; CGSize s; // Attempt to convert both values into atomic types if (AXValueGetValue(axp, kAXValueCGPointType, &p) && - AXValueGetValue(axs, kAXValueCGSizeType, &s)){ + AXValueGetValue(axs, kAXValueCGSizeType, &s)) { bounds.X = p.x; bounds.Y = p.y; bounds.W = s.width; bounds.H = s.height; } - - // return bounds; + exit: if (axp != NULL) { CFRelease(axp); } if (axs != NULL) { CFRelease(axs); } + if (AxWin != NULL) { CFRelease(AxWin); } + if (AxID != NULL) { CFRelease(AxID); } return bounds; - #elif defined(USE_X11) - // Ignore X errors XDismissErrors(); MData win; win.XWin = (Window)pid; - Bounds client = get_client(pid, isHwnd); + Bounds client = get_client(pid, isPid); Bounds frame = GetFrame(win); bounds.X = client.X - frame.X; @@ -131,14 +80,8 @@ Bounds get_bounds(uintptr pid, uintptr isHwnd){ bounds.H = client.H + frame.H; return bounds; - #elif defined(IS_WINDOWS) - HWND hwnd; - if (isHwnd == 0) { - hwnd= GetHwndByPId(pid); - } else { - hwnd = (HWND)pid; - } + HWND hwnd = getHwnd(pid, isPid); RECT rect = { 0 }; GetWindowRect(hwnd, &rect); @@ -149,21 +92,17 @@ Bounds get_bounds(uintptr pid, uintptr isHwnd){ bounds.H = rect.bottom - rect.top; return bounds; - #endif } -Bounds get_client(uintptr pid, uintptr isHwnd){ +Bounds get_client(uintptr pid, int8_t isPid) { // Check if the window is valid Bounds bounds; - if (!IsValid()) { return bounds; } + if (!is_valid()) { return bounds; } #if defined(IS_MACOSX) - - return get_bounds(pid, isHwnd); - + return get_bounds(pid, isPid); #elif defined(USE_X11) - Display *rDisplay = XOpenDisplay(NULL); // Ignore X errors @@ -175,11 +114,10 @@ Bounds get_client(uintptr pid, uintptr isHwnd){ Window root, parent; Window* children; unsigned int count; - int32 x = 0, y = 0; + int32_t x = 0, y = 0; // Check if the window is the root - XQueryTree(rDisplay, win.XWin, - &root, &parent, &children, &count); + XQueryTree(rDisplay, win.XWin, &root, &parent, &children, &count); if (children) { XFree(children); } // Retrieve window attributes @@ -187,12 +125,9 @@ Bounds get_client(uintptr pid, uintptr isHwnd){ XGetWindowAttributes(rDisplay, win.XWin, &attr); // Coordinates must be translated - if (parent != attr.root){ - XTranslateCoordinates(rDisplay, win.XWin, attr.root, attr.x, - attr.y, &x, &y, &parent); - } - // Coordinates can be left alone - else { + if (parent != attr.root) { + XTranslateCoordinates(rDisplay, win.XWin, attr.root, attr.x, attr.y, &x, &y, &parent); + } else { x = attr.x; y = attr.y; } @@ -202,16 +137,11 @@ Bounds get_client(uintptr pid, uintptr isHwnd){ bounds.Y = y; bounds.W = attr.width; bounds.H = attr.height; - return bounds; + XCloseDisplay(rDisplay); + return bounds; #elif defined(IS_WINDOWS) - HWND hwnd; - if (isHwnd == 0) { - hwnd= GetHwndByPId(pid); - } else { - hwnd = (HWND)pid; - } - + HWND hwnd = getHwnd(pid, isPid); RECT rect = { 0 }; GetClientRect(hwnd, &rect); @@ -229,6 +159,5 @@ Bounds get_client(uintptr pid, uintptr isHwnd){ bounds.H = rect.bottom - rect.top; return bounds; - #endif -} \ No newline at end of file +} diff --git a/window/window.go b/window/window.go new file mode 100644 index 00000000..1788c404 --- /dev/null +++ b/window/window.go @@ -0,0 +1 @@ +package window diff --git a/window/window.h b/window/window.h index 8eda37be..a7cf867a 100644 --- a/window/window.h +++ b/window/window.h @@ -3,35 +3,29 @@ // https://github.com/go-vgo/robotgo/blob/master/LICENSE // // Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed +// http://www.apache.org/licenses/LICENSE-2.0> +// +// This file may not be copied, modified, or distributed // except according to those terms. -// #include "../base/os.h" -// #include -#include "process.h" #include "pub.h" -#include "win32.h" bool setHandle(uintptr handle); -bool IsValid(); +bool is_valid(); bool IsAxEnabled(bool options); -MData GetActive(void); -void initWindow(); + +MData get_active(void); +void initWindow(uintptr handle); char* get_title_by_hand(MData m_data); void close_window_by_Id(MData m_data); -//int findwindow() - +// int findwindow() uintptr initHandle = 0; void initWindow(uintptr handle){ #if defined(IS_MACOSX) - - mData.CgID = 0; - mData.AxID = 0; - + pub_mData.CgID = 0; + pub_mData.AxID = 0; #elif defined(USE_X11) Display *rDisplay = XOpenDisplay(NULL); // If atoms loaded @@ -40,12 +34,11 @@ void initWindow(uintptr handle){ if (rDisplay != NULL) {LoadAtoms();} } - mData.XWin = 0; - + pub_mData.XWin = 0; + XCloseDisplay(rDisplay); #elif defined(IS_WINDOWS) - mData.HWnd = 0; + pub_mData.HWnd = 0; #endif - setHandle(handle); } @@ -57,9 +50,8 @@ bool Is64Bit() { return false; } -MData set_handle_pid(uintptr pid, uintptr isHwnd){ +MData set_handle_pid(uintptr pid, int8_t isPid){ MData win; - #if defined(IS_MACOSX) // Handle to a AXUIElementRef win.AxID = AXUIElementCreateApplication(pid); @@ -67,103 +59,91 @@ MData set_handle_pid(uintptr pid, uintptr isHwnd){ win.XWin = (Window)pid; // Handle to an X11 window #elif defined(IS_WINDOWS) // win.HWnd = (HWND)pid; // Handle to a window HWND - if (isHwnd == 0) { - win.HWnd = GetHwndByPId(pid); - } else { - win.HWnd = (HWND)pid; - } + win.HWnd = getHwnd(pid, isPid); #endif return win; } -void set_handle_pid_mData(uintptr pid, uintptr isHwnd){ - MData win = set_handle_pid(pid, isHwnd); - mData = win; +void set_handle_pid_mData(uintptr pid, int8_t isPid){ + MData win = set_handle_pid(pid, isPid); + pub_mData = win; } -bool IsValid(){ +bool is_valid() { initWindow(initHandle); if (!IsAxEnabled(true)) { - printf("%s\n", "Window:Accessibility API is disabled!\n" - "Failed to enable access for assistive devices."); + printf("%s\n", "Window: Accessibility API is disabled! " + "Failed to enable access for assistive devices. \n"); } - MData actdata = GetActive(); + MData actdata = get_active(); #if defined(IS_MACOSX) - - mData.CgID = actdata.CgID; - mData.AxID = actdata.AxID; - - if (mData.CgID == 0 || mData.AxID == 0)return false; + pub_mData.CgID = actdata.CgID; + pub_mData.AxID = actdata.AxID; + if (pub_mData.CgID == 0 || pub_mData.AxID == 0) { return false; } CFTypeRef r = NULL; - // Attempt to get the window role - if (AXUIElementCopyAttributeValue(mData.AxID, - kAXRoleAttribute,&r) == kAXErrorSuccess && r){ - CFRelease (r); + if (AXUIElementCopyAttributeValue(pub_mData.AxID, kAXRoleAttribute, &r) == kAXErrorSuccess && r){ + CFRelease(r); return true; } return false; - #elif defined(USE_X11) - mData.XWin = actdata.XWin; - if (mData.XWin == 0) {return false;} + pub_mData.XWin = actdata.XWin; + if (pub_mData.XWin == 0) { return false; } Display *rDisplay = XOpenDisplay(NULL); // Check for a valid X-Window display - if (rDisplay == NULL) {return false;} + if (rDisplay == NULL) { return false; } // Ignore X errors XDismissErrors(); // Get the window PID property - void* result = GetWindowProperty(mData, WM_PID,NULL); - if (result == NULL) {return false;} + void* result = GetWindowProperty(pub_mData, WM_PID,NULL); + if (result == NULL) { + XCloseDisplay(rDisplay); + return false; + } // Free result and return true XFree(result); - return true; + XCloseDisplay(rDisplay); + return true; #elif defined(IS_WINDOWS) - mData.HWnd = actdata.HWnd; - - if (mData.HWnd == 0) { + pub_mData.HWnd = actdata.HWnd; + if (pub_mData.HWnd == 0) { return false; } - return IsWindow(mData.HWnd) != 0; - + return IsWindow(pub_mData.HWnd) != 0; #endif } bool IsAxEnabled(bool options){ #if defined(IS_MACOSX) - // Statically load all required functions one time static dispatch_once_t once; dispatch_once (&once, ^{ // Open the framework - void* handle = dlopen("/System/Library/Frameworks/Application" - "Services.framework/ApplicationServices", RTLD_LAZY); + void* handle = dlopen("/System/Library/Frameworks/Application" + "Services.framework/ApplicationServices", RTLD_LAZY); // Validate the handle if (handle != NULL) { - *(void**) (&gAXIsProcessTrustedWithOptions) = - dlsym (handle, "AXIsProcessTrustedWithOptions"); - - gkAXTrustedCheckOptionPrompt = (CFStringRef*) - dlsym (handle, "kAXTrustedCheckOptionPrompt"); + *(void**) (&gAXIsProcessTrustedWithOptions) = dlsym (handle, "AXIsProcessTrustedWithOptions"); + gkAXTrustedCheckOptionPrompt = (CFStringRef*) dlsym (handle, "kAXTrustedCheckOptionPrompt"); } }); // Check for new OSX 10.9 function if (gAXIsProcessTrustedWithOptions) { // Check whether to show prompt - CFBooleanRef displayPrompt = options ? - kCFBooleanTrue : kCFBooleanFalse; + CFBooleanRef displayPrompt = options ? kCFBooleanTrue : kCFBooleanFalse; // Convert display prompt value into a dictionary const void* k[] = { *gkAXTrustedCheckOptionPrompt }; @@ -172,7 +152,6 @@ bool IsAxEnabled(bool options){ // Determine whether the process is actually trusted bool result = (*gAXIsProcessTrustedWithOptions)(o); - // Free memory CFRelease(o); return result; @@ -185,7 +164,6 @@ bool IsAxEnabled(bool options){ return AXAPIEnabled() || AXIsProcessTrusted(); #pragma clang diagnostic pop } - #elif defined(USE_X11) return true; #elif defined(IS_WINDOWS) @@ -197,15 +175,15 @@ bool IsAxEnabled(bool options){ bool setHandle(uintptr handle){ #if defined(IS_MACOSX) // Release the AX element - if (mData.AxID != NULL){ - CFRelease(mData.AxID); + if (pub_mData.AxID != NULL) { + CFRelease(pub_mData.AxID); } // Reset both values - mData.CgID = 0; - mData.AxID = 0; + pub_mData.CgID = 0; + pub_mData.AxID = 0; - if (handle == 0){ + if (handle == 0) { // return 0; return true; } @@ -213,92 +191,64 @@ bool setHandle(uintptr handle){ // Retrieve the window element CGWindowID cgID = (CGWindowID)handle; AXUIElementRef axID = GetUIElement(cgID); - if (axID != NULL){ - mData.CgID = cgID; - mData.AxID = axID; + pub_mData.CgID = cgID; + pub_mData.AxID = axID; // return 0; return true; } // return 1; return false; - #elif defined(USE_X11) - - mData.XWin = (Window)handle; - - if (handle == 0){ + pub_mData.XWin = (Window)handle; + if (handle == 0) { return true; } - if (IsValid()){ + if (is_valid()) { return true; } - mData.XWin = 0; + pub_mData.XWin = 0; return false; #elif defined(IS_WINDOWS) - - mData.HWnd = (HWND)handle; - + pub_mData.HWnd = (HWND)handle; if (handle == 0) { return true; } - if (IsValid()) { + if (is_valid()) { return true; } - mData.HWnd = 0; + pub_mData.HWnd = 0; return false; - #endif } -// uint32 uintptr -uintptr getHandle() { - #if defined(IS_MACOSX) - return (uintptr)mData.CgID; - #elif defined(USE_X11) - return (uintptr)mData.XWin; - #elif defined(IS_WINDOWS) - return (uintptr)mData.HWnd; - #endif -} - bool IsTopMost(void){ // Check the window validity - if (!IsValid()) {return false;} + if (!is_valid()) { return false; } #if defined(IS_MACOSX) - return false; // WARNING: Unavailable - #elif defined(USE_X11) - // Ignore X errors // XDismissErrors (); // return GetState (mData.XWin, STATE_TOPMOST); - #elif defined(IS_WINDOWS) - - return (GetWindowLongPtr(mData.HWnd, GWL_EXSTYLE) - & WS_EX_TOPMOST) != 0; - + return (GetWindowLongPtr(pub_mData.HWnd, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0; #endif } bool IsMinimized(void){ // Check the window validity - if (!IsValid()) {return false;} + if (!is_valid()) { return false; } #if defined(IS_MACOSX) - CFBooleanRef data = NULL; - // Determine whether the window is minimized - if (AXUIElementCopyAttributeValue(mData.AxID, - kAXMinimizedAttribute, (CFTypeRef*) &data) - == kAXErrorSuccess && data != NULL) { + if (AXUIElementCopyAttributeValue(pub_mData.AxID, kAXMinimizedAttribute, + (CFTypeRef*) &data) == kAXErrorSuccess && data != NULL) { // Convert resulting data into a bool bool result = CFBooleanGetValue(data); CFRelease(data); @@ -306,65 +256,44 @@ bool IsMinimized(void){ } return false; - #elif defined(USE_X11) - // Ignore X errors // XDismissErrors(); // return GetState(mData.XWin, STATE_MINIMIZE); - #elif defined(IS_WINDOWS) - - return (GetWindowLongPtr(mData.HWnd, GWL_STYLE) - & WS_MINIMIZE) != 0; - + return (GetWindowLongPtr(pub_mData.HWnd, GWL_STYLE) & WS_MINIMIZE) != 0; #endif } ////// - bool IsMaximized(void){ // Check the window validity - if (!IsValid()) {return false;} + if (!is_valid()) { return false; } #if defined(IS_MACOSX) - return false; // WARNING: Unavailable - #elif defined(USE_X11) - // Ignore X errors // XDismissErrors(); // return GetState(mData.XWin, STATE_MAXIMIZE); - #elif defined(IS_WINDOWS) - - return (GetWindowLongPtr(mData.HWnd, GWL_STYLE) - & WS_MAXIMIZE) != 0; - + return (GetWindowLongPtr(pub_mData.HWnd, GWL_STYLE) & WS_MAXIMIZE) != 0; #endif } -void SetActive(const MData win){ +void set_active(const MData win) { // Check if the window is valid - if (!IsValid()) { return; } + if (!is_valid()) { return; } #if defined(IS_MACOSX) - // Attempt to raise the specified window object - if (AXUIElementPerformAction(win.AxID, kAXRaiseAction) - != kAXErrorSuccess) { + if (AXUIElementPerformAction(win.AxID, kAXRaiseAction) != kAXErrorSuccess) { pid_t pid = 0; // Attempt to retrieve the PID of the window - if (AXUIElementGetPid(win.AxID, &pid) - != kAXErrorSuccess || !pid) {return;} + if (AXUIElementGetPid(win.AxID, &pid) != kAXErrorSuccess || !pid) { return; } // Ignore deprecated warnings #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - // NOTE: Until Apple actually removes - // these functions, there's no real - // reason to switch to the NS* flavor - ProcessSerialNumber psn; // Attempt to retrieve the process psn if (GetProcessForPID(pid, &psn) == 0) { @@ -374,9 +303,7 @@ void SetActive(const MData win){ #pragma clang diagnostic pop } - #elif defined(USE_X11) - // Ignore X errors XDismissErrors(); @@ -407,26 +334,21 @@ void SetActive(const MData win){ } else { // Attempt to raise the specified window XRaiseWindow(rDisplay, win.XWin); - // Set the specified window's input focus - XSetInputFocus(rDisplay, win.XWin, - RevertToParent, CurrentTime); + XSetInputFocus(rDisplay, win.XWin, RevertToParent, CurrentTime); } - + XCloseDisplay(rDisplay); #elif defined(IS_WINDOWS) - if (IsMinimized()) { ShowWindow(win.HWnd, SW_RESTORE); } SetForegroundWindow(win.HWnd); - #endif } -MData GetActive(void){ +MData get_active(void) { #if defined(IS_MACOSX) - MData result; // Ignore deprecated warnings #pragma clang diagnostic push @@ -434,8 +356,7 @@ MData GetActive(void){ ProcessSerialNumber psn; pid_t pid; // Attempt to retrieve the front process - if (GetFrontProcess(&psn) != 0 || - GetProcessPID(&psn, &pid) != 0) { + if (GetFrontProcess(&psn) != 0 || GetProcessPID(&psn, &pid) != 0) { return result; } @@ -443,34 +364,30 @@ MData GetActive(void){ // Create accessibility object using focused PID AXUIElementRef focused = AXUIElementCreateApplication(pid); - if (focused == NULL) {return result; }// Verify + if (focused == NULL) { return result; } // Verify AXUIElementRef element; + CGWindowID win = 0; // Retrieve the currently focused window - if (AXUIElementCopyAttributeValue(focused, - kAXFocusedWindowAttribute, (CFTypeRef*) - &element) == kAXErrorSuccess && element) { + if (AXUIElementCopyAttributeValue(focused, kAXFocusedWindowAttribute, (CFTypeRef*) &element) + == kAXErrorSuccess && element) { - CGWindowID win = 0; // Use undocumented API to get WID - if (_AXUIElementGetWindow(element, &win) - == kAXErrorSuccess && win) { + if (_AXUIElementGetWindow(element, &win) == kAXErrorSuccess && win) { // Manually set internals result.CgID = win; result.AxID = element; - } - // Something went wrong - else { + } else { CFRelease(element); } + } else { + result.CgID = win; + result.AxID = element; } - CFRelease(focused); return result; - #elif defined(USE_X11) - MData result; Display *rDisplay = XOpenDisplay(NULL); // Check X-Window display @@ -494,6 +411,7 @@ MData GetActive(void){ if (window != 0) { // Set and return the foreground window result.XWin = (Window)window; + XCloseDisplay(rDisplay); return result; } } @@ -502,17 +420,16 @@ MData GetActive(void){ Window window = None; int revert = RevertToNone; XGetInputFocus(rDisplay, &window, &revert); + XCloseDisplay(rDisplay); // Return foreground window result.XWin = window; return result; - #elif defined(IS_WINDOWS) - // Attempt to get the foreground window multiple times in case MData result; - uint8 times = 0; + uint8_t times = 0; while (++times < 20) { HWND handle; handle = GetForegroundWindow(); @@ -521,106 +438,100 @@ MData GetActive(void){ result.HWnd = (HWND)handle; return result; } - Sleep (20); + Sleep(20); } return result; - #endif } - void SetTopMost(bool state){ // Check window validity - if (!IsValid()) {return;} + if (!is_valid()) { return; } #if defined(IS_MACOSX) - // WARNING: Unavailable - #elif defined(USE_X11) - // Ignore X errors // XDismissErrors(); - // SetState(mData.XWin, STATE_TOPMOST, state); - + // SetState(pub_mData.XWin, STATE_TOPMOST, state); #elif defined(IS_WINDOWS) - - SetWindowPos(mData.HWnd, - state ? HWND_TOPMOST : HWND_NOTOPMOST, + SetWindowPos(pub_mData.HWnd, state ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - #endif } -void close_main_window (){ +void close_main_window () { // Check if the window is valid - if (!IsValid()) { return; } + if (!is_valid()) { return; } - close_window_by_Id(mData); + close_window_by_Id(pub_mData); } -void close_window_by_PId(uintptr pid, uintptr isHwnd){ - MData win = set_handle_pid(pid, isHwnd); +void close_window_by_PId(uintptr pid, int8_t isPid){ + MData win = set_handle_pid(pid, isPid); close_window_by_Id(win); } - // CloseWindow void close_window_by_Id(MData m_data){ // Check window validity - if (!IsValid()) { return; } + if (!is_valid()) { return; } #if defined(IS_MACOSX) AXUIElementRef b = NULL; - // Retrieve the close button of this window - if (AXUIElementCopyAttributeValue(m_data.AxID, - kAXCloseButtonAttribute, (CFTypeRef*) &b) + if (AXUIElementCopyAttributeValue(m_data.AxID, kAXCloseButtonAttribute, (CFTypeRef*) &b) == kAXErrorSuccess && b != NULL) { // Simulate button press on the close button AXUIElementPerformAction(b, kAXPressAction); CFRelease(b); } - #elif defined(USE_X11) - Display *rDisplay = XOpenDisplay(NULL); - // Ignore X errors XDismissErrors(); // Close the window XDestroyWindow(rDisplay, m_data.XWin); - + XCloseDisplay(rDisplay); #elif defined(IS_WINDOWS) - PostMessage(m_data.HWnd, WM_CLOSE, 0, 0); #endif } char* get_main_title(){ // Check if the window is valid - if (!IsValid()) { return "IsValid failed."; } - - return get_title_by_hand(mData); + if (!is_valid()) { return "is_valid failed."; } + + return get_title_by_hand(pub_mData); +} + +char* get_title_by_pid(uintptr pid, int8_t isPid){ + MData win = set_handle_pid(pid, isPid); + return get_title_by_hand(win); } -char* get_title_by_pid(uintptr pid, uintptr isHwnd){ - MData win = set_handle_pid(pid, isHwnd); - return get_title_by_hand(win); +char* named(void *result) { + char *name = (char*)calloc(strlen(result)+1, sizeof(char*)); + char *rptr = (char*)result; + char *nptr = name; + while (*rptr) { + *nptr = *rptr; + nptr++; + rptr++; + } + *nptr = '\0'; + + return name; } char* get_title_by_hand(MData m_data){ // Check if the window is valid - if (!IsValid()) {return "IsValid failed.";} - + if (!is_valid()) { return "is_valid failed."; } #if defined(IS_MACOSX) - CFStringRef data = NULL; - // Determine the current title of the window - if (AXUIElementCopyAttributeValue(m_data.AxID, - kAXTitleAttribute, (CFTypeRef*) &data) - == kAXErrorSuccess && data != NULL) { + if (AXUIElementCopyAttributeValue(m_data.AxID, kAXTitleAttribute, (CFTypeRef*) &data) == + kAXErrorSuccess && data != NULL) { char conv[512]; // Convert result to a C-String CFStringGetCString(data, conv, 512, kCFStringEncodingUTF8); @@ -633,20 +544,17 @@ char* get_title_by_hand(MData m_data){ } return ""; - #elif defined(USE_X11) - void* result; // Ignore X errors XDismissErrors(); // Get window title (UTF-8) result = GetWindowProperty(m_data, WM_NAME, NULL); - // Check result value if (result != NULL) { // Convert result to a string - char *name = (char*)result; + char* name = named(result); XFree(result); if (name != NULL) { return name; } @@ -654,19 +562,17 @@ char* get_title_by_hand(MData m_data){ // Get window title (ASCII) result = GetWindowProperty(m_data, XA_WM_NAME, NULL); - // Check result value if (result != NULL) { // Convert result to a string - char *name = (char*)result; + char* name = named(result); XFree(result); + return name; } return ""; - #elif defined(IS_WINDOWS) - if (GetWindowText(m_data.HWnd, m_data.Title, 512) > 0){ char* name = m_data.Title; @@ -676,44 +582,34 @@ char* get_title_by_hand(MData m_data){ } return ""; - #endif } -int32 WGetPID(void){ +int32_t get_PID(void) { // Check window validity - if (!IsValid()) { return 0; } - + if (!is_valid()) { return 0; } #if defined(IS_MACOSX) - pid_t pid = 0; // Attempt to retrieve the window pid - if (AXUIElementGetPid(mData.AxID, &pid)== kAXErrorSuccess) { - return pid; - } - + if (AXUIElementGetPid(pub_mData.AxID, &pid)== kAXErrorSuccess) { + return pid; + } return 0; - #elif defined(USE_X11) - // Ignore X errors XDismissErrors(); // Get the window PID - long* result = (long*)GetWindowProperty(mData, WM_PID,NULL); - + long* result = (long*)GetWindowProperty(pub_mData, WM_PID,NULL); // Check result and convert it if (result == NULL) { return 0; } - int32 pid = (int32) *result; + + int32_t pid = (int32_t) *result; XFree(result); return pid; - #elif defined(IS_WINDOWS) - - DWORD id = 0; - GetWindowThreadProcessId(mData.HWnd, &id); + DWORD id = 0; + GetWindowThreadProcessId(pub_mData.HWnd, &id); return id; - #endif } - diff --git a/windows_n.go b/windows_n.go new file mode 100644 index 00000000..613fb790 --- /dev/null +++ b/windows_n.go @@ -0,0 +1,2 @@ +// +bulid windows,next +package robotgo