├── .github
├── CONTRIBUTING.md
└── ISSUE_TEMPLATE.md
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── appveyor.yml
├── binding.gyp
├── index.d.ts
├── index.js
├── package-lock.json
├── package.json
├── src
├── MMBitmap.c
├── MMBitmap.h
├── MMPointArray.c
├── MMPointArray.h
├── UTHashTable.c
├── UTHashTable.h
├── alert.c
├── alert.h
├── base64.c
├── base64.h
├── bitmap_find.c
├── bitmap_find.h
├── bmp_io.c
├── bmp_io.h
├── color_find.c
├── color_find.h
├── deadbeef_rand.c
├── deadbeef_rand.h
├── endian.h
├── inline_keywords.h
├── io.c
├── io.h
├── keycode.c
├── keycode.h
├── keypress.c
├── keypress.h
├── microsleep.h
├── mouse.c
├── mouse.h
├── ms_stdbool.h
├── ms_stdint.h
├── os.h
├── pasteboard.c
├── pasteboard.h
├── png_io.c
├── png_io.h
├── rgb.h
├── robotjs.cc
├── screen.c
├── screen.h
├── screengrab.c
├── screengrab.h
├── snprintf.c
├── snprintf.h
├── str_io.c
├── str_io.h
├── types.h
├── uthash.h
├── xdisplay.c
├── xdisplay.h
├── zlib_util.c
└── zlib_util.h
└── test
├── bitmap.js
├── integration
├── keyboard.js
├── mouse.js
└── screen.js
├── keyboard.js
├── mouse.js
└── screen.js
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## How to contribute
2 |
3 | * Please try to match the style of the code around the feature/bug you're working on.
4 | * Use tabs not spaces.
5 | * Please make sure your pull request only includes changes to the lines you're working on. For example, disable the whitespace extension when using Atom.
6 | * All pull requests must include code for every platform (Mac, Windows, and Linux) before they can be merged. The exception is platform specific features. Feel free to submit a pull request with code for one platform and others can fill in the gaps to help get it merged.
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Expected Behavior
4 |
5 |
6 |
7 | ## Current Behavior
8 |
9 |
10 |
11 | ## Possible Solution
12 |
13 |
14 |
15 | ## Steps to Reproduce (for bugs)
16 |
17 |
18 | 1.
19 | 2.
20 | 3.
21 | 4.
22 |
23 | ## Context
24 |
25 |
26 |
27 | ## Your Environment
28 |
29 | * RobotJS version:
30 | * Node.js version:
31 | * npm version:
32 | * Operating System:
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | node_modules/
3 | prebuilds/
4 | /.idea
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: cpp
3 |
4 | env:
5 | matrix:
6 | - TRAVIS_NODE_VERSION="8"
7 | - TRAVIS_NODE_VERSION="10"
8 | - TRAVIS_NODE_VERSION="12"
9 | - TRAVIS_NODE_VERSION="stable"
10 |
11 | os:
12 | - linux
13 | - osx
14 |
15 | cache:
16 | directories:
17 | - node_modules
18 |
19 | git:
20 | depth: 5
21 |
22 | addons:
23 | apt:
24 | sources:
25 | - ubuntu-toolchain-r-test
26 | packages:
27 | - libx11-dev
28 | - zlib1g-dev
29 | - libpng12-dev
30 | - libxtst-dev
31 | - g++-4.8
32 | - gcc-4.8
33 |
34 | before_install:
35 | - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh
36 | - nvm install $TRAVIS_NODE_VERSION
37 | - PATH=$PATH:`pwd`/node_modules/.bin
38 | # print versions
39 | - node --version
40 | - npm --version
41 |
42 | # use g++-4.8 on Linux
43 | - if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi
44 | - $CXX --version
45 |
46 | install:
47 | - npm install
48 |
49 | script:
50 | - if [ "$TRAVIS_OS_NAME" = "osx" ]; then npm test; fi
51 | - if [ "$TRAVIS_OS_NAME" = "linux" ]; then xvfb-run npm test; fi
52 |
53 | after_success:
54 | - if [[ $TRAVIS_TAG != "" ]]; then npm run prebuild -- -u $GITHUB_TOKEN; fi
55 |
56 | notifications:
57 | webhooks:
58 | urls:
59 | - https://webhooks.gitter.im/e/e737dd5170be50cdba95
60 | on_success: change
61 | on_failure: always
62 | on_start: never
63 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright (c) 2014 Jason Stallings
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |

2 |
3 |

4 |
5 | > Node.js Desktop Automation. Control the mouse, keyboard, and read the screen.
6 |
7 | RobotJS supports Mac, [Windows](https://github.com/octalmage/robotjs/issues/2), and [Linux](https://github.com/octalmage/robotjs/issues/17).
8 |
9 | This is a work in progress so the exported functions could change at any time before the first stable release (1.0.0). [Ideas?](https://github.com/octalmage/robotjs/issues/4)
10 |
11 | [Check out some of the cool things people are making with RobotJS](https://github.com/octalmage/robotjs/wiki/Projects-using-RobotJS)! Have your own rad RobotJS project? Feel free to add it!
12 |
13 | 

14 |
15 | ## Contents
16 |
17 | - [Installation](#installation)
18 | - [Examples](#examples)
19 | - [API](https://robotjs.io/docs/syntax)
20 | - [Building](#building)
21 | - [Plans](#plans)
22 | - [Progress](#progress)
23 | - [FAQ](#faq)
24 | - [License](#license)
25 |
26 | ## Installation
27 |
28 | Install RobotJS using npm:
29 |
30 | ```
31 | npm install robotjs
32 | ```
33 | It's that easy! npm will download one of the prebuilt [binaries](https://github.com/octalmage/robotjs/releases/latest) for your OS.
34 |
35 | You can get npm [here](https://nodejs.org/en/download/) if you don't have it installed.
36 |
37 | If you need to build RobotJS, see the [building](#building) section. Instructions for [Electron](https://github.com/octalmage/robotjs/wiki/Electron).
38 |
39 | ## Examples
40 |
41 | ##### [Mouse](https://github.com/octalmage/robotjs/wiki/Syntax#mouse)
42 |
43 | 
44 |
45 | ```JavaScript
46 | // Move the mouse across the screen as a sine wave.
47 | var robot = require("robotjs");
48 |
49 | // Speed up the mouse.
50 | robot.setMouseDelay(2);
51 |
52 | var twoPI = Math.PI * 2.0;
53 | var screenSize = robot.getScreenSize();
54 | var height = (screenSize.height / 2) - 10;
55 | var width = screenSize.width;
56 |
57 | for (var x = 0; x < width; x++)
58 | {
59 | y = height * Math.sin((twoPI * x) / width) + height;
60 | robot.moveMouse(x, y);
61 | }
62 | ```
63 |
64 | ##### [Keyboard](https://github.com/octalmage/robotjs/wiki/Syntax#keyboard)
65 |
66 | ```JavaScript
67 | // Type "Hello World" then press enter.
68 | var robot = require("robotjs");
69 |
70 | // Type "Hello World".
71 | robot.typeString("Hello World");
72 |
73 | // Press enter.
74 | robot.keyTap("enter");
75 | ```
76 |
77 | ##### [Screen](https://github.com/octalmage/robotjs/wiki/Syntax#screen)
78 |
79 | ```JavaScript
80 | // Get pixel color under the mouse.
81 | var robot = require("robotjs");
82 |
83 | // Get mouse position.
84 | var mouse = robot.getMousePos();
85 |
86 | // Get pixel color in hex format.
87 | var hex = robot.getPixelColor(mouse.x, mouse.y);
88 | console.log("#" + hex + " at x:" + mouse.x + " y:" + mouse.y);
89 | ```
90 | Read the [Wiki](https://github.com/octalmage/robotjs/wiki) for more information!
91 |
92 | ## [API](http://robotjs.io/docs/syntax)
93 |
94 | The RobotJS API is hosted at .
95 |
96 | ## Building
97 |
98 | Please ensure you have the required dependencies before installing:
99 |
100 | * Windows
101 | * windows-build-tools npm package (`npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe)
102 | * Mac
103 | * Xcode Command Line Tools.
104 | * Linux
105 | * Python (v2.7 recommended, v3.x.x is not supported).
106 | * make.
107 | * A C/C++ compiler like GCC.
108 | * libxtst-dev and libpng++-dev (`sudo apt-get install libxtst-dev libpng++-dev`).
109 |
110 | Install node-gyp using npm:
111 |
112 | ```
113 | npm install -g node-gyp
114 | ```
115 |
116 | Then build:
117 |
118 | ```
119 | node-gyp rebuild
120 | ```
121 |
122 | See the [node-gyp readme](https://github.com/nodejs/node-gyp#installation) for more details.
123 |
124 | ## Plans
125 |
126 | * √ Control the mouse by changing the mouse position, left/right clicking, and dragging.
127 | * √ Control the keyboard by pressing keys, holding keys down, and typing words.
128 | * √ Read pixel color from the screen and capture the screen.
129 | * Find an image on screen, read pixels from an image.
130 | * Possibly include window management?
131 |
132 | ## Progress
133 |
134 | | Module | Status | Notes |
135 | | ------------- |-------------: | ------- |
136 | | Mouse | 100% | All planned features implemented. |
137 | | Keyboard | 100% | All planned features implemented. |
138 | | Screen | 85% | Image search, pixel search. |
139 | | Bitmap | 0% | Saving/opening, png support. |
140 |
141 | ## FAQ
142 |
143 | #### Does RobotJS support global hotkeys?
144 |
145 | Not currently, and I don't know if it ever will. I personally use [Electron](http://electron.atom.io/)/[NW.js](http://nwjs.io/) for global hotkeys, and this works well. Later on I might add hotkey support or create a separate module. See [#55](https://github.com/octalmage/robotjs/issues/55) for details.
146 |
147 | #### Can I take a screenshot with RobotJS?
148 |
149 | Soon! This is a bit more complicated than the rest of the features, so I saved it for last. Luckily the code is already there, I just need to write the bindings, and I've already started. Subscribe to [#13](https://github.com/octalmage/robotjs/issues/13) for updates.
150 |
151 | #### Why is <insert key> missing from the keyboard functions?
152 |
153 | We've been implementing keys as we need them. Feel free to create an issue or submit a pull request!
154 |
155 | #### How about multi-monitor support?
156 |
157 | The library doesn't have explicit multi-monitor support, so anything that works is kind of on accident. Subscribe to [#88](https://github.com/octalmage/robotjs/issues/88) for updates.
158 |
159 | For any other questions please [submit an issue](https://github.com/octalmage/robotjs/issues/new).
160 |
161 | ## Story
162 |
163 | I'm a huge fan of [AutoHotkey](https://www.autohotkey.com/), and I've used it for a very long time. AutoHotkey is great for automation and it can do a bunch of things that are very difficult in other languages. For example, it's [imagesearch](https://www.autohotkey.com/docs/commands/ImageSearch.htm) and [pixel](https://www.autohotkey.com/docs/commands/PixelGetColor.htm) related functions are hard to reproduce on Mac, especially in scripting languages. These functions are great for automating apps that can't be automated like [Netflix](http://blueshirtdesign.com/apps/autoflix/). This has never been a big deal since I've always used Windows at work, but for the past few years I've been using Mac exclusively.
164 |
165 | I like AutoHotkey, but I like Node.js more. By developing RobotJS I get an AutoHotkey replacement on Mac (finally!), and I get to use my favorite language.
166 |
167 | **TLDR:** There's nothing like AutoHotkey on Mac, so I'm making it.
168 |
169 | ## License
170 |
171 | MIT
172 |
173 | Based on [autopy](https://github.com/msanders/autopy).
174 | Maintained by [Jason Stallings](http://jason.stallin.gs).
175 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | # http://www.appveyor.com/docs/appveyor-yml
2 |
3 | # Test against these versions of Io.js and Node.js.
4 | environment:
5 | matrix:
6 | # node.js
7 | - nodejs_version: "10"
8 | - nodejs_version: "12"
9 | - nodejs_version: "14"
10 | - nodejs_version: "Stable"
11 |
12 | cache:
13 | - node_modules
14 |
15 | clone_depth: 5
16 |
17 | platform:
18 | - x86
19 | - x64
20 |
21 | # Install scripts. (runs after repo cloning)
22 | install:
23 | # Get the latest stable version of Node 0.STABLE.latest
24 | - ps: Install-Product node $env:nodejs_version
25 | - npm -g install npm
26 | - set PATH=%APPDATA%\npm;%PATH%
27 | # Typical npm stuff.
28 | - npm install
29 |
30 | test_script:
31 | # Output useful info for debugging.
32 | - node --version
33 | - npm --version
34 | # run tests
35 | - npm test
36 |
37 | on_success:
38 | - IF defined APPVEYOR_REPO_TAG_NAME npm run prebuild -- -u %GITHUB_TOKEN%
39 |
40 | build: off
41 | version: "{build}"
42 |
--------------------------------------------------------------------------------
/binding.gyp:
--------------------------------------------------------------------------------
1 | {
2 | 'targets': [{
3 | 'target_name': 'robotjs',
4 | 'include_dirs': [
5 | "
3 | #include
4 |
5 | MMBitmapRef createMMBitmap(uint8_t *buffer,
6 | size_t width,
7 | size_t height,
8 | size_t bytewidth,
9 | uint8_t bitsPerPixel,
10 | uint8_t bytesPerPixel)
11 | {
12 | MMBitmapRef bitmap = malloc(sizeof(MMBitmap));
13 | if (bitmap == NULL) return NULL;
14 |
15 | bitmap->imageBuffer = buffer;
16 | bitmap->width = width;
17 | bitmap->height = height;
18 | bitmap->bytewidth = bytewidth;
19 | bitmap->bitsPerPixel = bitsPerPixel;
20 | bitmap->bytesPerPixel = bytesPerPixel;
21 |
22 | return bitmap;
23 | }
24 |
25 | void destroyMMBitmap(MMBitmapRef bitmap)
26 | {
27 | assert(bitmap != NULL);
28 |
29 | if (bitmap->imageBuffer != NULL) {
30 | free(bitmap->imageBuffer);
31 | bitmap->imageBuffer = NULL;
32 | }
33 |
34 | free(bitmap);
35 | }
36 |
37 | void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint)
38 | {
39 | if (bitmapBuffer != NULL)
40 | {
41 | free(bitmapBuffer);
42 | }
43 | }
44 |
45 | MMBitmapRef copyMMBitmap(MMBitmapRef bitmap)
46 | {
47 | uint8_t *copiedBuf = NULL;
48 |
49 | assert(bitmap != NULL);
50 | if (bitmap->imageBuffer != NULL) {
51 | const size_t bufsize = bitmap->height * bitmap->bytewidth;
52 | copiedBuf = malloc(bufsize);
53 | if (copiedBuf == NULL) return NULL;
54 |
55 | memcpy(copiedBuf, bitmap->imageBuffer, bufsize);
56 | }
57 |
58 | return createMMBitmap(copiedBuf,
59 | bitmap->width,
60 | bitmap->height,
61 | bitmap->bytewidth,
62 | bitmap->bitsPerPixel,
63 | bitmap->bytesPerPixel);
64 | }
65 |
66 | MMBitmapRef copyMMBitmapFromPortion(MMBitmapRef source, MMRect rect)
67 | {
68 | assert(source != NULL);
69 |
70 | if (source->imageBuffer == NULL || !MMBitmapRectInBounds(source, rect)) {
71 | return NULL;
72 | } else {
73 | uint8_t *copiedBuf = NULL;
74 | const size_t bufsize = rect.size.height * source->bytewidth;
75 | const size_t offset = (source->bytewidth * rect.origin.y) +
76 | (rect.origin.x * source->bytesPerPixel);
77 |
78 | /* Don't go over the bounds, programmer! */
79 | assert((bufsize + offset) <= (source->bytewidth * source->height));
80 |
81 | copiedBuf = malloc(bufsize);
82 | if (copiedBuf == NULL) return NULL;
83 |
84 | memcpy(copiedBuf, source->imageBuffer + offset, bufsize);
85 |
86 | return createMMBitmap(copiedBuf,
87 | rect.size.width,
88 | rect.size.height,
89 | source->bytewidth,
90 | source->bitsPerPixel,
91 | source->bytesPerPixel);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/src/MMBitmap.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef MMBITMAP_H
3 | #define MMBITMAP_H
4 |
5 | #include "types.h"
6 | #include "rgb.h"
7 | #include
8 | #include
9 |
10 | #ifdef __cplusplus
11 | extern "C"
12 | {
13 | #endif
14 |
15 | struct _MMBitmap {
16 | uint8_t *imageBuffer; /* Pixels stored in Quad I format; i.e., origin is in
17 | * top left. Length should be height * bytewidth. */
18 | size_t width; /* Never 0, unless image is NULL. */
19 | size_t height; /* Never 0, unless image is NULL. */
20 | size_t bytewidth; /* The aligned width (width + padding). */
21 | uint8_t bitsPerPixel; /* Should be either 24 or 32. */
22 | uint8_t bytesPerPixel; /* For convenience; should be bitsPerPixel / 8. */
23 | };
24 |
25 | typedef struct _MMBitmap MMBitmap;
26 | typedef MMBitmap *MMBitmapRef;
27 |
28 | /* Creates new MMBitmap with the given values.
29 | * Follows the Create Rule (caller is responsible for destroy()'ing object). */
30 | MMBitmapRef createMMBitmap(uint8_t *buffer, size_t width, size_t height,
31 | size_t bytewidth, uint8_t bitsPerPixel,
32 | uint8_t bytesPerPixel);
33 |
34 | /* Releases memory occupied by MMBitmap. */
35 | void destroyMMBitmap(MMBitmapRef bitmap);
36 |
37 | /* Releases memory occupied by MMBitmap. Acts via CallBack method*/
38 | void destroyMMBitmapBuffer(char * bitmapBuffer, void * hint);
39 |
40 | /* Returns copy of MMBitmap, to be destroy()'d by caller. */
41 | MMBitmapRef copyMMBitmap(MMBitmapRef bitmap);
42 |
43 | /* Returns copy of one MMBitmap juxtaposed in another (to be destroy()'d
44 | * by the caller.), or NULL on error. */
45 | MMBitmapRef copyMMBitmapFromPortion(MMBitmapRef source, MMRect rect);
46 |
47 | #define MMBitmapPointInBounds(image, p) ((p).x < (image)->width && \
48 | (p).y < (image)->height)
49 | #define MMBitmapRectInBounds(image, r) \
50 | (((r).origin.x + (r).size.width <= (image)->width) && \
51 | ((r).origin.y + (r).size.height <= (image)->height))
52 |
53 | #define MMBitmapGetBounds(image) MMRectMake(0, 0, image->width, image->height)
54 |
55 | /* Get pointer to pixel of MMBitmapRef. No bounds checking is performed (check
56 | * yourself before calling this with MMBitmapPointInBounds(). */
57 | #define MMRGBColorRefAtPoint(image, x, y) \
58 | (MMRGBColor *)(assert(MMBitmapPointInBounds(bitmap, MMPointMake(x, y))), \
59 | ((image)->imageBuffer) + (((image)->bytewidth * (y)) \
60 | + ((x) * (image)->bytesPerPixel)))
61 |
62 | /* Dereference pixel of MMBitmapRef. Again, no bounds checking is performed. */
63 | #define MMRGBColorAtPoint(image, x, y) *MMRGBColorRefAtPoint(image, x, y)
64 |
65 | /* Hex/integer value of color at point. */
66 | #define MMRGBHexAtPoint(image, x, y) \
67 | hexFromMMRGB(MMRGBColorAtPoint(image, x, y))
68 |
69 | /* Increment either point.x or point.y depending on the position of point.x.
70 | * That is, if x + 1 is >= width, increment y and start x at the beginning.
71 | * Otherwise, increment x.
72 | *
73 | * This is used as a convenience macro to scan rows when calling functions such
74 | * as findColorInRectAt() and findBitmapInBitmapAt(). */
75 | #define ITER_NEXT_POINT(pixel, width, start_x) \
76 | do { \
77 | if (++(pixel).x >= (width)) { \
78 | (pixel).x = start_x; \
79 | ++(point).y; \
80 | } \
81 | } while (0);
82 |
83 | #ifdef __cplusplus
84 | }
85 | #endif
86 |
87 | #endif /* MMBITMAP_H */
--------------------------------------------------------------------------------
/src/MMPointArray.c:
--------------------------------------------------------------------------------
1 | #include "MMPointArray.h"
2 | #include
3 |
4 | MMPointArrayRef createMMPointArray(size_t initialCount)
5 | {
6 | MMPointArrayRef pointArray = calloc(1, sizeof(MMPointArray));
7 |
8 | if (initialCount == 0) initialCount = 1;
9 |
10 | pointArray->_allocedCount = initialCount;
11 | pointArray->array = malloc(pointArray->_allocedCount * sizeof(MMPoint));
12 | if (pointArray->array == NULL) return NULL;
13 |
14 | return pointArray;
15 | }
16 |
17 | void destroyMMPointArray(MMPointArrayRef pointArray)
18 | {
19 | if (pointArray->array != NULL) {
20 | free(pointArray->array);
21 | pointArray->array = NULL;
22 | }
23 |
24 | free(pointArray);
25 | }
26 |
27 | void MMPointArrayAppendPoint(MMPointArrayRef pointArray, MMPoint point)
28 | {
29 | const size_t newCount = ++(pointArray->count);
30 | if (pointArray->_allocedCount < newCount) {
31 | do {
32 | /* Double size each time to avoid calls to realloc(). */
33 | pointArray->_allocedCount <<= 1;
34 | } while (pointArray->_allocedCount < newCount);
35 | pointArray->array = realloc(pointArray->array,
36 | sizeof(point) *
37 | pointArray->_allocedCount);
38 | }
39 |
40 | pointArray->array[pointArray->count - 1] = point;
41 | }
42 |
--------------------------------------------------------------------------------
/src/MMPointArray.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef MMARRAY_H
3 | #define MMARRAY_H
4 |
5 | #include "types.h"
6 |
7 | struct _MMPointArray {
8 | MMPoint *array; /* Pointer to actual data. */
9 | size_t count; /* Number of elements in array. */
10 | size_t _allocedCount; /* Private; do not use outside of MMPointArray.c. */
11 | };
12 |
13 | typedef struct _MMPointArray MMPointArray;
14 | typedef MMPointArray *MMPointArrayRef;
15 |
16 | /* Creates array of an initial size (the maximum size is still limitless).
17 | * This follows the "Create" Rule; i.e., responsibility for "destroying" the
18 | * array is given to the caller. */
19 | MMPointArrayRef createMMPointArray(size_t initialCount);
20 |
21 | /* Frees memory occupied by |pointArray|. Does not accept NULL. */
22 | void destroyMMPointArray(MMPointArrayRef pointArray);
23 |
24 | /* Appends a point to an array, increasing the internal size if necessary. */
25 | void MMPointArrayAppendPoint(MMPointArrayRef pointArray, MMPoint point);
26 |
27 | /* Retrieve point from array. */
28 | #define MMPointArrayGetItem(a, i) ((a)->array)[i]
29 |
30 | /* Set point in array. */
31 | #define MMPointArraySetItem(a, i, item) ((a)->array[i] = item)
32 |
33 | #endif /* MMARRAY_H */
34 |
--------------------------------------------------------------------------------
/src/UTHashTable.c:
--------------------------------------------------------------------------------
1 | #include "UTHashTable.h"
2 | #include
3 | #include
4 |
5 | /* Base struct class (all nodes must contain at least the elements in
6 | * this struct). */
7 | struct _UTHashNode {
8 | UTHashNode_HEAD
9 | };
10 |
11 | typedef struct _UTHashNode UTHashNode;
12 |
13 | void initHashTable(UTHashTable *table, size_t initialCount, size_t nodeSize)
14 | {
15 | assert(table != NULL);
16 | assert(nodeSize >= sizeof(UTHashNode));
17 |
18 | table->uttable = NULL; /* Must be set to NULL for uthash. */
19 | table->allocedNodeCount = (initialCount == 0) ? 1 : initialCount;
20 | table->nodeCount = 0;
21 | table->nodeSize = nodeSize;
22 | table->nodes = calloc(table->nodeSize, nodeSize * table->allocedNodeCount);
23 | }
24 |
25 | void destroyHashTable(UTHashTable *table)
26 | {
27 | UTHashNode *uttable = table->uttable;
28 | UTHashNode *node;
29 |
30 | /* Let uthash do its magic. */
31 | while (uttable != NULL) {
32 | node = uttable; /* Grab pointer to first item. */
33 | HASH_DEL(uttable, node); /* Delete it (table advances to next). */
34 | }
35 |
36 | /* Only giant malloc'd block containing each node must be freed. */
37 | if (table->nodes != NULL) free(table->nodes);
38 | table->uttable = table->nodes = NULL;
39 | }
40 |
41 | void *getNewNode(UTHashTable *table)
42 | {
43 | /* Increment node count, resizing table if necessary. */
44 | const size_t newNodeCount = ++(table->nodeCount);
45 | if (table->allocedNodeCount < newNodeCount) {
46 | do {
47 | /* Double size each time to avoid calls to realloc(). */
48 | table->allocedNodeCount <<= 1;
49 | } while (table->allocedNodeCount < newNodeCount);
50 |
51 | table->nodes = realloc(table->nodes, table->nodeSize *
52 | table->allocedNodeCount);
53 | }
54 |
55 | return (char *)table->nodes + (table->nodeSize * (table->nodeCount - 1));
56 | }
57 |
--------------------------------------------------------------------------------
/src/UTHashTable.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef UTHASHTABLE_H
3 | #define UTHASHTABLE_H
4 |
5 | #include
6 | #include "uthash.h"
7 |
8 | /* All node structs must begin with this (note that there is NO semicolon). */
9 | #define UTHashNode_HEAD UT_hash_handle hh;
10 |
11 | /* This file contains convenience macros and a standard struct for working with
12 | * uthash hash tables.
13 | *
14 | * The main purpose of this is for convenience of creating/freeing nodes. */
15 | struct _UTHashTable {
16 | void *uttable; /* The uthash table -- must start out as NULL. */
17 | void *nodes; /* Contiguous array of nodes. */
18 | size_t allocedNodeCount; /* Node count currently allocated for. */
19 | size_t nodeCount; /* Current node count. */
20 | size_t nodeSize; /* Size of each node. */
21 | };
22 |
23 | typedef struct _UTHashTable UTHashTable;
24 |
25 | /* Initiates a hash table to the default values. |table| should point to an
26 | * already allocated UTHashTable struct.
27 | *
28 | * If the |initialCount| argument in initHashTable is given, |nodes| is
29 | * allocated immediately to the maximum size and new nodes are simply slices of
30 | * that array. This can save calls to malloc if many nodes are to be added, and
31 | * the a reasonable maximum number is known ahead of time.
32 | *
33 | * If the node count goes over this maximum, or if |initialCount| is 0, the
34 | * array is dynamically reallocated to fit the size.
35 | */
36 | void initHashTable(UTHashTable *table, size_t initialCount, size_t nodeSize);
37 |
38 | /* Frees memory occupied by a UTHashTable's members.
39 | *
40 | * Note that this does NOT free memory for the UTHashTable pointed to by
41 | * |table| itself; if that was allocated on the heap, you must free() it
42 | * yourself after calling this. */
43 | void destroyHashTable(UTHashTable *table);
44 |
45 | /* Returns memory allocated for a new node. Responsibility for freeing this is
46 | * up to the destroyHashTable() macro; this should NOT be freed by the caller.
47 | *
48 | * This is intended to be used with a HASH_ADD() macro, e.g.:
49 | * {%
50 | * struct myNode *uttable = utHashTable->uttable;
51 | * struct myNode *node = getNewNode(utHashTable);
52 | * node->key = 42;
53 | * node->value = someValue;
54 | * HASH_ADD_INT(uttable, key, node);
55 | * utHashTable->uttable = uttable;
56 | * %}
57 | *
58 | * Or, use the UTHASHTABLE_ADD_INT or UTHASHTABLE_ADD_STR macros
59 | * for convenience (they are exactly equivalent):
60 | * {%
61 | * struct myNode *node = getNewNode(utHashTable);
62 | * node->key = 42;
63 | * node->value = someValue;
64 | * UTHASHTABLE_ADD_INT(utHashTable, key, node, struct myNode);
65 | * %}
66 | */
67 | void *getNewNode(UTHashTable *table);
68 |
69 | #define UTHASHTABLE_ADD_INT(tablePtr, keyName, node, nodeType) \
70 | do { \
71 | nodeType *uttable = (tablePtr)->uttable; \
72 | HASH_ADD_INT(uttable, keyName, node); \
73 | (tablePtr)->uttable = uttable; \
74 | } while (0)
75 |
76 | #define UTHASHTABLE_ADD_STR(tablePtr, keyName, node, nodeType) \
77 | do { \
78 | nodeType *uttable = (tablePtr)->uttable; \
79 | HASH_ADD_STR(uttable, keyName, node); \
80 | (tablePtr)->uttable = uttable; \
81 | } while (0)
82 |
83 | #endif /* MMHASHTABLE_H */
84 |
--------------------------------------------------------------------------------
/src/alert.c:
--------------------------------------------------------------------------------
1 | #include "alert.h"
2 | #include "os.h"
3 | #include
4 |
5 | #if defined(IS_MACOSX)
6 | #include
7 | #elif defined(USE_X11)
8 | #include /* For fputs() */
9 | #include /* For exit() */
10 | #include /* For wait() */
11 | #include /* For fork() */
12 | #include /* For pid_t */
13 | #include "snprintf.h" /* For asprintf() */
14 | #endif
15 |
16 | #if defined(USE_X11)
17 |
18 | enum {
19 | TASK_SUCCESS = 0,
20 | FORK_FAILED = -1,
21 | EXEC_FAILED = -2
22 | };
23 |
24 | /*
25 | * Unfortunately, X has no standard method of displaying alerts, so instead we
26 | * have to rely on the shell command "xmessage" (or nicer-looking equivalents).
27 | *
28 | * The return value and arguments are the same as those from to runTask()
29 | * (see below).
30 | */
31 | static int xmessage(char *argv[], int *exit_status);
32 |
33 | #elif defined(IS_MACOSX)
34 | #define CFStringCreateWithUTF8String(string) \
35 | ((string) == NULL ? NULL : CFStringCreateWithCString(NULL, \
36 | string, \
37 | kCFStringEncodingUTF8))
38 | #endif
39 |
40 | int showAlert(const char *title, const char *msg, const char *defaultButton,
41 | const char *cancelButton)
42 | {
43 | #if defined(IS_MACOSX)
44 | CFStringRef alertHeader = CFStringCreateWithUTF8String(title);
45 | CFStringRef alertMessage = CFStringCreateWithUTF8String(msg);
46 | CFStringRef defaultButtonTitle = CFStringCreateWithUTF8String(defaultButton);
47 | CFStringRef cancelButtonTitle = CFStringCreateWithUTF8String(cancelButton);
48 | CFOptionFlags responseFlags;
49 | SInt32 err = CFUserNotificationDisplayAlert(0.0,
50 | kCFUserNotificationNoteAlertLevel,
51 | NULL,
52 | NULL,
53 | NULL,
54 | alertHeader,
55 | alertMessage,
56 | defaultButtonTitle,
57 | cancelButtonTitle,
58 | NULL,
59 | &responseFlags);
60 | if (alertHeader != NULL) CFRelease(alertHeader);
61 | if (alertMessage != NULL) CFRelease(alertMessage);
62 | if (defaultButtonTitle != NULL) CFRelease(defaultButtonTitle);
63 | if (cancelButtonTitle != NULL) CFRelease(cancelButtonTitle);
64 |
65 | if (err != 0) return -1;
66 | return (responseFlags == kCFUserNotificationDefaultResponse) ? 0 : 1;
67 | #elif defined(USE_X11)
68 | /* Note that args[0] is set by the xmessage() function. */
69 | const char *args[10] = {NULL, msg, "-title", title, "-center"};
70 | int response, ret;
71 | char *buttonList = NULL; /* To be free()'d. */
72 |
73 | if (defaultButton == NULL) defaultButton = "OK";
74 |
75 | if (cancelButton == NULL) {
76 | asprintf(&buttonList, "%s:2", defaultButton);
77 | } else {
78 | asprintf(&buttonList, "%s:2,%s:3", defaultButton, cancelButton);
79 | }
80 |
81 | if (buttonList == NULL) return -1; /* asprintf() failed. */
82 | args[5] = "-buttons";
83 | args[6] = buttonList;
84 | args[7] = "-default";
85 | args[8] = defaultButton;
86 | args[9] = NULL;
87 |
88 | ret = xmessage((char **)args, &response);
89 | if (buttonList != NULL) {
90 | free(buttonList);
91 | buttonList = NULL;
92 | }
93 |
94 | if (ret != TASK_SUCCESS) {
95 | if (ret == EXEC_FAILED) {
96 | fputs("xmessage or equivalent not found.\n", stderr);
97 | }
98 | return -1;
99 | }
100 |
101 | return (response == 2) ? 0 : 1;
102 | #else
103 | /* TODO: Display custom buttons instead of the pre-defined "OK"
104 | * and "Cancel". */
105 | int response = MessageBox(NULL, msg, title,
106 | (cancelButton == NULL) ? MB_OK : MB_OKCANCEL);
107 | return (response == IDOK) ? 0 : 1;
108 | #endif
109 | }
110 |
111 | #if defined(USE_X11)
112 |
113 | /*
114 | * Attempts to run the given task synchronously with the given arguments.
115 | *
116 | * If |exit_status| is non-NULL and the task ran successfully, |exit_status| is
117 | * set to the exit code of the task on return.
118 | *
119 | * Returns -1 if process could not be forked, -2 if the task could not be run,
120 | * or 0 if the task was ran successfully.
121 | */
122 | static int runTask(const char *taskname, char * const argv[], int *exit_status);
123 |
124 | static int xmessage(char *argv[], int *exit_status)
125 | {
126 | static const char * const MSG_PROGS[] = {"gmessage", "gxmessage",
127 | "kmessage", "xmessage"};
128 | static int PREV_MSG_INDEX = -1;
129 | #define MSG_PROGS_LEN (sizeof(MSG_PROGS) / sizeof(MSG_PROGS[0]))
130 |
131 | char *prog = NULL;
132 | int ret;
133 |
134 | /* Save some fork()'ing and attempt to use last program if possible. */
135 | if (PREV_MSG_INDEX >= 0) {
136 | assert(PREV_MSG_INDEX < MSG_PROGS_LEN);
137 |
138 | prog = argv[0] = (char *)MSG_PROGS[PREV_MSG_INDEX];
139 | ret = runTask(prog, argv, exit_status);
140 | } else {
141 | /* Otherwise, try running each xmessage alternative until one works or
142 | * we run out of options. */
143 | size_t i;
144 | for (i = 0; i < MSG_PROGS_LEN; ++i) {
145 | prog = argv[0] = (char *)MSG_PROGS[i];
146 | ret = runTask(prog, argv, exit_status);
147 | if (ret != EXEC_FAILED) break;
148 | }
149 |
150 | if (ret == TASK_SUCCESS) PREV_MSG_INDEX = i;
151 | }
152 |
153 | return ret;
154 | }
155 |
156 | static int runTask(const char *taskname, char * const argv[], int *exit_status)
157 | {
158 | pid_t pid;
159 | int status;
160 |
161 | switch (pid = fork()) {
162 | case -1: /* Failed to fork */
163 | perror("fork");
164 | return FORK_FAILED; /* Failed to fork. */
165 | case 0: /* Child process */
166 | execvp(taskname, argv);
167 | exit(42); /* Failed to run task. */
168 | default: /* Parent process */
169 | wait(&status); /* Block execution until finished. */
170 |
171 | if (!WIFEXITED(status) || (status = WEXITSTATUS(status)) == 42) {
172 | return EXEC_FAILED; /* Task failed to run. */
173 | }
174 | if (exit_status != NULL) *exit_status = status;
175 | return TASK_SUCCESS; /* Success! */
176 | }
177 | }
178 |
179 | #endif
180 |
--------------------------------------------------------------------------------
/src/alert.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef ALERT_H
3 | #define ALERT_H
4 |
5 | #if defined(_MSC_VER)
6 | #include "ms_stdbool.h"
7 | #else
8 | #include
9 | #endif
10 |
11 | /* Displays alert with given attributes, and blocks execution until the user
12 | * responds. Returns 0 if defaultButton was pressed, 1 if cancelButton was
13 | * pressed, or -1 if an error occurred. */
14 | int showAlert(const char *title, const char *msg, const char *defaultButton,
15 | const char *cancelButton);
16 |
17 | #endif /* ALERT_H */
18 |
--------------------------------------------------------------------------------
/src/base64.c:
--------------------------------------------------------------------------------
1 | #include "base64.h"
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | /* Encoding table as described in RFC1113. */
8 | const static uint8_t b64_encode_table[] =
9 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
10 | "abcdefghijklmnopqrstuvwxyz0123456789+/";
11 |
12 | /* Decoding table. */
13 | const static int8_t b64_decode_table[256] = {
14 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00-0F */
15 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10-1F */
16 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 20-2F */
17 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 30-3F */
18 | -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 40-4F */
19 | 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 50-5F */
20 | -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 60-6F */
21 | 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 70-7F */
22 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80-8F */
23 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90-9F */
24 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0-AF */
25 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0-BF */
26 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0-CF */
27 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0-DF */
28 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0-EF */
29 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 /* F0-FF */
30 | };
31 |
32 | uint8_t *base64decode(const uint8_t *src, const size_t buflen, size_t *retlen)
33 | {
34 | int8_t digit, lastdigit;
35 | size_t i, j;
36 | uint8_t *decoded;
37 | const size_t maxlen = ((buflen + 3) / 4) * 3;
38 |
39 | /* Sanity check */
40 | assert(src != NULL);
41 |
42 | digit = lastdigit = j = 0;
43 | decoded = malloc(maxlen + 1);
44 | if (decoded == NULL) return NULL;
45 | for (i = 0; i < buflen; ++i) {
46 | if ((digit = b64_decode_table[src[i]]) != -1) {
47 | /* Decode block */
48 | switch (i % 4) {
49 | case 1:
50 | decoded[j++] = ((lastdigit << 2) | ((digit & 0x30) >> 4));
51 | break;
52 | case 2:
53 | decoded[j++] = (((lastdigit & 0xF) << 4) | ((digit & 0x3C) >> 2));
54 | break;
55 | case 3:
56 | decoded[j++] = (((lastdigit & 0x03) << 6) | digit);
57 | break;
58 | }
59 | lastdigit = digit;
60 | }
61 | }
62 |
63 | if (retlen != NULL) *retlen = j;
64 | decoded[j] = '\0';
65 | return decoded; /* Must be free()'d by caller */
66 | }
67 |
68 | uint8_t *base64encode(const uint8_t *src, const size_t buflen, size_t *retlen)
69 | {
70 | size_t i, j;
71 | const size_t maxlen = (((buflen + 3) & ~3)) * 4;
72 | uint8_t *encoded = malloc(maxlen + 1);
73 | if (encoded == NULL) return NULL;
74 |
75 | /* Sanity check */
76 | assert(src != NULL);
77 | assert(buflen > 0);
78 |
79 | j = 0;
80 | for (i = 0; i < buflen + 1; ++i) {
81 | /* Encode block */
82 | switch (i % 3) {
83 | case 0:
84 | encoded[j++] = b64_encode_table[src[i] >> 2];
85 | encoded[j++] = b64_encode_table[((src[i] & 0x03) << 4) |
86 | ((src[i + 1] & 0xF0) >> 4)];
87 | break;
88 | case 1:
89 | encoded[j++] = b64_encode_table[((src[i] & 0x0F) << 2) |
90 | ((src[i + 1] & 0xC0) >> 6)];
91 | break;
92 | case 2:
93 | encoded[j++] = b64_encode_table[(src[i] & 0x3F)];
94 | break;
95 | }
96 | }
97 |
98 | /* Add padding if necessary */
99 | if ((j % 4) != 0) {
100 | const size_t with_padding = ((j + 3) & ~3); /* Align to 4 bytes */
101 | do {
102 | encoded[j++] = '=';
103 | } while (j < with_padding);
104 | }
105 |
106 | assert(j <= maxlen);
107 |
108 | if (retlen != NULL) *retlen = j;
109 | encoded[j] = '\0';
110 | return encoded; /* Must be free()'d by caller */
111 | }
112 |
--------------------------------------------------------------------------------
/src/base64.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef BASE64_H
3 | #define BASE64_H
4 |
5 | #include
6 |
7 | #if defined(_MSC_VER)
8 | #include "ms_stdint.h"
9 | #else
10 | #include
11 | #endif
12 |
13 | /* Decode a base64 encoded string discarding line breaks and noise.
14 | *
15 | * Returns a new string to be free()'d by caller, or NULL on error.
16 | * Returned string is guaranteed to be NUL-terminated.
17 | *
18 | * If |retlen| is not NULL, it is set to the length of the returned string
19 | * (minus the NUL-terminator) on successful return. */
20 | uint8_t *base64decode(const uint8_t *buf, const size_t buflen, size_t *retlen);
21 |
22 | /* Encode a base64 encoded string without line breaks or noise.
23 | *
24 | * Returns a new string to be free()'d by caller, or NULL on error.
25 | * Returned string is guaranteed to be NUL-terminated with the correct padding.
26 | *
27 | * If |retlen| is not NULL, it is set to the length of the returned string
28 | * (minus the NUL-terminator) on successful return. */
29 | uint8_t *base64encode(const uint8_t *buf, const size_t buflen, size_t *retlen);
30 |
31 | #endif /* BASE64_H */
32 |
--------------------------------------------------------------------------------
/src/bitmap_find.c:
--------------------------------------------------------------------------------
1 | #include "bitmap_find.h"
2 | #include "UTHashTable.h"
3 | #include
4 |
5 | /* Node to be used in hash table. */
6 | struct shiftNode {
7 | UTHashNode_HEAD /* Make structure hashable */
8 | MMRGBHex color; /* Key */
9 | MMPoint offset; /* Value */
10 | };
11 |
12 | /* --- Hash table helper functions --- */
13 |
14 | /* Adds hex-color/offset pair to jump table. */
15 | static void addNodeToTable(UTHashTable *table, MMRGBHex color, MMPoint offset);
16 |
17 | /* Returns node associated with color in jump table, or NULL if it
18 | * doesn't exist. */
19 | static struct shiftNode *nodeForColor(UTHashTable *table, MMRGBHex color);
20 |
21 | /* Returns nonzero (true) if table has key, or zero (false) if not. */
22 | #define tableHasKey(table, color) (nodeForColor(table, color) != NULL)
23 |
24 | /* --- Boyer-Moore helper functions --- */
25 |
26 | /* Calculates the first table for use in a Boyer-Moore search algorithm.
27 | * Table is in the form [colors: shift_values], where colors are those in
28 | * |needle|, and the shift values are each color's distance from the rightmost
29 | * offset. All other colors are assumed to have a shift value equal to the
30 | * length of needle.
31 | */
32 | static void initBadShiftTable(UTHashTable *jumpTable, MMBitmapRef needle);
33 |
34 | /* Frees memory occupied by calling initBadShiftTable().
35 | * Currently this is just an alias for destroyHashTable(). */
36 | #define destroyBadShiftTable(jumpTable) destroyHashTable(jumpTable)
37 |
38 | /* Returns true if |needle| is found in |haystack| at |offset|. */
39 | static int needleAtOffset(MMBitmapRef needle, MMBitmapRef haystack,
40 | MMPoint offset, float tolerance);
41 | /* --- --- */
42 |
43 | /* An modification of the Boyer-Moore-Horspool Algorithm, only applied to
44 | * bitmaps and colors instead of strings and characters.
45 | *
46 | * TODO: The Boyer-Moore algorithm (with the second jump table) would probably
47 | * be more efficient, but this was simpler (for now).
48 | *
49 | * The jump table (|badShiftTable|) is passed as a parameter to avoid being
50 | * recalculated each time. It should be a pointer to a UTHashTable init'd with
51 | * initBadShiftTable().
52 | *
53 | * Returns 0 and sets |point| to the starting point of |needle| in |haystack|
54 | * if |needle| was found in |haystack|, or returns -1 if not. */
55 | static int findBitmapInRectAt(MMBitmapRef needle,
56 | MMBitmapRef haystack,
57 | MMPoint *point,
58 | MMRect rect,
59 | float tolerance,
60 | MMPoint startPoint,
61 | UTHashTable *badShiftTable)
62 | {
63 | const size_t scanHeight = rect.size.height - needle->height;
64 | const size_t scanWidth = rect.size.width - needle->width;
65 | MMPoint pointOffset = startPoint;
66 | /* const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1); */
67 |
68 | /* Sanity check */
69 | if (needle->height > haystack->height || needle->width > haystack->width ||
70 | !MMBitmapRectInBounds(haystack, rect)) {
71 | return -1;
72 | }
73 |
74 | assert(point != NULL);
75 | assert(needle != NULL);
76 | assert(needle->height > 0 && needle->width > 0);
77 | assert(haystack != NULL);
78 | assert(haystack->height > 0 && haystack->width > 0);
79 | assert(badShiftTable != NULL);
80 |
81 | /* Search |haystack|, while |needle| can still be within it. */
82 | while (pointOffset.y <= scanHeight) {
83 | /* struct shiftNode *node = NULL;
84 | MMRGBHex lastColor; */
85 |
86 | while (pointOffset.x <= scanWidth) {
87 | /* Check offset in |haystack| for |needle|. */
88 | if (needleAtOffset(needle, haystack, pointOffset, tolerance)) {
89 | ++pointOffset.x;
90 | ++pointOffset.y;
91 | *point = pointOffset;
92 | return 0;
93 | }
94 |
95 | /* Otherwise, calculate next x offset to check. */
96 | /*
97 | * Note that here we are getting the skip value based on the last
98 | * color of |needle|, no matter where we didn't match. The
99 | * alternative of pretending that the mismatched color was the previous
100 | * color is slower in the normal case.
101 | */
102 | /* lastColor = MMRGBHexAtPoint(haystack, pointOffset.x + lastPoint.x,
103 | pointOffset.y + lastPoint.y); */
104 |
105 | /* TODO: This fails on certain edge cases (issue#7). */
106 | /* When a color is encountered that does not occur in |needle|, we can
107 | * safely skip ahead for the whole length of |needle|.
108 | * Otherwise, use the value stored in the jump table. */
109 | /* node = nodeForColor(badShiftTable, lastColor);
110 | pointOffset.x += (node == NULL) ? needle->width : (node->offset).x; */
111 |
112 | /* For now, be naive. */
113 | ++pointOffset.x;
114 | }
115 |
116 | pointOffset.x = rect.origin.x;
117 |
118 | /* lastColor = MMRGBHexAtPoint(haystack, pointOffset.x + lastPoint.x,
119 | pointOffset.y + lastPoint.y);
120 | node = nodeForColor(badShiftTable, lastColor);
121 | pointOffset.y += node == NULL ? lastPoint.y : (node->offset).y; */
122 |
123 | /* TODO: The above commented out code fails at certain edge cases, e.g.:
124 | * Needle: [B, b
125 | * b, b,
126 | * B, b]
127 | * Haystack: [w, w, w, w, w
128 | * w, w, w, w, b
129 | * w, w, w, b, b
130 | * w, w, w, w, b]
131 | * The previous algorithm noticed that the first 3 x 3 block had nothing
132 | * in common with the image, and thus, after scanning the first row,
133 | * skipped three blocks downward to scan the next (which didn't exist,
134 | * so the loop ended). However, the needle was hidden IN-BETWEEN this
135 | * jump -- skipping was appropriate for scanning the column but not
136 | * the row.
137 | *
138 | * I need to figure out a more optimal solution; temporarily I am just
139 | * scanning every single y coordinate, only skipping on x's. This
140 | * always works, but is probably not optimal.
141 | */
142 | ++pointOffset.y;
143 | }
144 |
145 | return -1;
146 | }
147 |
148 | int findBitmapInRect(MMBitmapRef needle,
149 | MMBitmapRef haystack,
150 | MMPoint *point,
151 | MMRect rect,
152 | float tolerance)
153 | {
154 | UTHashTable badShiftTable;
155 | int ret;
156 |
157 | initBadShiftTable(&badShiftTable, needle);
158 | ret = findBitmapInRectAt(needle, haystack, point, rect,
159 | tolerance, MMPointZero, &badShiftTable);
160 | destroyBadShiftTable(&badShiftTable);
161 | return ret;
162 | }
163 |
164 | MMPointArrayRef findAllBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack,
165 | MMRect rect, float tolerance)
166 | {
167 | MMPointArrayRef pointArray = createMMPointArray(0);
168 | MMPoint point = MMPointZero;
169 | UTHashTable badShiftTable;
170 |
171 | initBadShiftTable(&badShiftTable, needle);
172 | while (findBitmapInRectAt(needle, haystack, &point, rect,
173 | tolerance, point, &badShiftTable) == 0) {
174 | const size_t scanWidth = (haystack->width - needle->width) + 1;
175 | MMPointArrayAppendPoint(pointArray, point);
176 | ITER_NEXT_POINT(point, scanWidth, 0);
177 | }
178 | destroyBadShiftTable(&badShiftTable);
179 |
180 | return pointArray;
181 | }
182 |
183 | size_t countOfBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack,
184 | MMRect rect, float tolerance)
185 | {
186 | size_t count = 0;
187 | MMPoint point = MMPointZero;
188 | UTHashTable badShiftTable;
189 |
190 | initBadShiftTable(&badShiftTable, needle);
191 | while (findBitmapInRectAt(needle, haystack, &point, rect,
192 | tolerance, point, &badShiftTable) == 0) {
193 | const size_t scanWidth = (haystack->width - needle->width) + 1;
194 | ++count;
195 | ITER_NEXT_POINT(point, scanWidth, 0);
196 | }
197 | destroyBadShiftTable(&badShiftTable);
198 |
199 | return count;
200 | }
201 |
202 | /* --- Boyer-Moore helper functions --- */
203 |
204 | static void initBadShiftTable(UTHashTable *jumpTable, MMBitmapRef needle)
205 | {
206 | const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1);
207 | const size_t maxColors = needle->width * needle->height;
208 | MMPoint scan;
209 |
210 | /* Allocate max size initially to avoid a million calls to malloc(). */
211 | initHashTable(jumpTable, maxColors, sizeof(struct shiftNode));
212 |
213 | /* Populate jumpTable with analysis of |needle|. */
214 | for (scan.y = lastPoint.y; ; --scan.y) {
215 | for (scan.x = lastPoint.x; ; --scan.x) {
216 | MMRGBHex color = MMRGBHexAtPoint(needle, scan.x, scan.y);
217 | if (!tableHasKey(jumpTable, color)) {
218 | addNodeToTable(jumpTable, color,
219 | MMPointMake(needle->width - scan.x,
220 | needle->height - scan.y));
221 | }
222 |
223 | if (scan.x == 0) break; /* Avoid infinite loop from unsigned type. */
224 | }
225 | if (scan.y == 0) break;
226 | }
227 | }
228 |
229 | static int needleAtOffset(MMBitmapRef needle, MMBitmapRef haystack,
230 | MMPoint offset, float tolerance)
231 | {
232 | const MMPoint lastPoint = MMPointMake(needle->width - 1, needle->height - 1);
233 | MMPoint scan;
234 |
235 | /* Note that |needle| is searched backwards, in accordance with the
236 | * Boyer-Moore search algorithm. */
237 | for (scan.y = lastPoint.y; ; --scan.y) {
238 | for (scan.x = lastPoint.x; ; --scan.x) {
239 | MMRGBHex ncolor = MMRGBHexAtPoint(needle, scan.x, scan.y);
240 | MMRGBHex hcolor = MMRGBHexAtPoint(haystack, offset.x + scan.x,
241 | offset.y + scan.y);
242 | if (!MMRGBHexSimilarToColor(ncolor, hcolor, tolerance)) return 0;
243 | if (scan.x == 0) break; /* Avoid infinite loop from unsigned type. */
244 | }
245 | if (scan.y == 0) break;
246 | }
247 |
248 | return 1;
249 | }
250 |
251 | /* --- Hash table helper functions --- */
252 |
253 | static void addNodeToTable(UTHashTable *table,
254 | MMRGBHex hexColor,
255 | MMPoint offset)
256 | {
257 | struct shiftNode *node = getNewNode(table);
258 | node->color = hexColor;
259 | node->offset = offset;
260 | UTHASHTABLE_ADD_INT(table, color, node, struct shiftNode);
261 | }
262 |
263 | static struct shiftNode *nodeForColor(UTHashTable *table,
264 | MMRGBHex color)
265 | {
266 | struct shiftNode *uttable = table->uttable;
267 | struct shiftNode *node;
268 | HASH_FIND_INT(uttable, &color, node);
269 | return node;
270 | }
271 |
--------------------------------------------------------------------------------
/src/bitmap_find.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef BITMAP_H
3 | #define BITMAP_H
4 |
5 | #include "types.h"
6 | #include "MMBitmap.h"
7 | #include "MMPointArray.h"
8 |
9 | /* Convenience wrapper around findBitmapInRect(), where |rect| is the bounds
10 | * of |haystack|. */
11 | #define findBitmapInBitmap(needle, haystack, pointPtr, tol) \
12 | findBitmapInRect(needle, haystack, pointPtr, MMBitmapGetBounds(haystack), tol)
13 |
14 | /* Returns 0 and sets |point| to the origin of |needle| in |haystack| if
15 | * |needle| was found in |haystack| inside of |rect|, or returns -1 if not.
16 | *
17 | * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the
18 | * colors in the bitmaps need to match, with 0 being exact and 1 being any.
19 | */
20 | int findBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack,
21 | MMPoint *point, MMRect rect, float tolerance);
22 |
23 | /* Convenience wrapper around findAllBitmapInRect(), where |rect| is the bounds
24 | * of |haystack|. */
25 | #define findAllBitmapInBitmap(needle, haystack, tolerance) \
26 | findAllBitmapInRect(needle, haystack, \
27 | MMBitmapGetBounds(haystack), tolerance)
28 |
29 | /* Returns MMPointArray of all occurrences of |needle| in |haystack| inside of
30 | * |rect|. Note that an is returned regardless of whether |needle| was found;
31 | * check array->count to see if it actually was.
32 | *
33 | * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the
34 | * colors in the bitmaps need to match, with 0 being exact and 1 being any.
35 | *
36 | * Responsibility for freeing the MMPointArray with destroyMMPointArray() is
37 | * given to the caller.
38 | */
39 | MMPointArrayRef findAllBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack,
40 | MMRect rect, float tolerance);
41 |
42 | /* Convenience wrapper around countOfBitmapInRect(), where |rect| is the bounds
43 | * of |haystack|. */
44 | #define countOfBitmapInBitmap(needle, haystack, tolerance) \
45 | countOfBitmapInRect(needle, haystack, MMBitmapGetBounds(haystack), tolerance)
46 |
47 | /* Returns the number of occurences of |needle| in |haystack| inside
48 | * of |rect|. */
49 | size_t countOfBitmapInRect(MMBitmapRef needle, MMBitmapRef haystack,
50 | MMRect rect, float tolerance);
51 |
52 | #endif /* BITMAP_H */
53 |
--------------------------------------------------------------------------------
/src/bmp_io.c:
--------------------------------------------------------------------------------
1 | #include "bmp_io.h"
2 | #include "os.h"
3 | #include "endian.h"
4 | #include /* fopen() */
5 | #include /* memcpy() */
6 |
7 | #if defined(_MSC_VER)
8 | #include "ms_stdbool.h"
9 | #include "ms_stdint.h"
10 | #else
11 | #include
12 | #include
13 | #endif
14 |
15 | #pragma pack(push, 1) /* The following structs should be continguous, so we can
16 | * copy them in one read. */
17 | /*
18 | * Standard, initial BMP Header
19 | */
20 | struct BITMAP_FILE_HEADER {
21 | uint16_t magic; /* First two byes of the file; should be 0x4D42. */
22 | uint32_t fileSize; /* Size of the BMP file in bytes (unreliable). */
23 | uint32_t reserved; /* Application-specific. */
24 | uint32_t imageOffset; /* Offset to bitmap data. */
25 | };
26 |
27 | #define BMP_MAGIC 0x4D42 /* The starting key that marks the file as a BMP. */
28 |
29 | enum _BMP_COMPRESSION {
30 | kBMP_RGB = 0, /* No compression. */
31 | kBMP_RLE8 = 1, /* Can only be used with 8-bit bitmaps. */
32 | kBMP_RLE4 = 2, /* Can only be used with 4-bit bitmaps. */
33 | kBMP_BITFIELDS = 3, /* Can only be used with 16/32-bit bitmaps. */
34 | kBMP_JPEG = 4, /* Bitmap contains a JPEG image. */
35 | kBMP_PNG = 5 /* Bitmap contains a PNG image. */
36 | };
37 |
38 | typedef uint32_t BMP_COMPRESSION;
39 |
40 | /*
41 | * Windows 3 Header
42 | */
43 | struct BITMAP_INFO_HEADER {
44 | uint32_t headerSize; /* The size of this header (40 bytes). */
45 | int32_t width; /* The bitmap width in pixels. */
46 | int32_t height; /* The bitmap height in pixels. */
47 | /* (A negative value denotes that the image
48 | * is flipped.) */
49 | uint16_t colorPlanes; /* The number of color planes; must be 1. */
50 | uint16_t bitsPerPixel; /* The color depth of the image (1, 4, 8, 16,
51 | * 24, or 32). */
52 | BMP_COMPRESSION compression; /* The compression method being used. */
53 | uint32_t imageSize; /* Size of the bitmap in bytes (unreliable).*/
54 | int32_t xRes; /* The horizontal resolution (unreliable). */
55 | int32_t yRes; /* The vertical resolution (unreliable). */
56 | uint32_t colorsUsed; /* The number of colors in the color table,
57 | * or 0 to default to 2^n. */
58 | uint32_t colorsImportant; /* Colors important for displaying bitmap,
59 | * or 0 when every color is equally important;
60 | * ignored. */
61 | };
62 |
63 | /*
64 | * OS/2 v1 Header
65 | */
66 | struct BITMAP_CORE_HEADER {
67 | uint32_t headerSize; /* The size of this header (12 bytes). */
68 | uint16_t width; /* The bitmap width in pixels. */
69 | uint16_t height; /* The bitmap height in pixels. */
70 | uint16_t colorPlanes; /* The number of color planes; must be 1. */
71 | uint16_t bitsPerPixel; /* Color depth of the image (1, 4, 8, or 24). */
72 | };
73 |
74 | #pragma pack(pop) /* Let the compiler do what it wants now. */
75 |
76 | /* BMP files are always saved in little endian format (x86), so we need to
77 | * convert them if we're not on a little endian machine (e.g., ARM & ppc). */
78 |
79 | #if __BYTE_ORDER == __BIG_ENDIAN
80 |
81 | /* Converts bitmap file header from to and from little endian, if and only if
82 | * host is big endian. */
83 | static void convertBitmapFileHeader(struct BITMAP_FILE_HEADER *header)
84 | {
85 | header->magic = swapLittleAndHost16(header->magic);
86 | swapLittleAndHost32(header->fileSize);
87 | swapLittleAndHost32(header->reserved);
88 | swapLittleAndHost32(header->imageOffset);
89 | }
90 |
91 | /* Converts bitmap info header from to and from little endian, if and only if
92 | * host is big endian. */
93 | static void convertBitmapInfoHeader(struct BITMAP_INFO_HEADER *header)
94 | {
95 | header->headerSize = swapLittleAndHost32(header->headerSize);
96 | header->width = swapLittleAndHost32(header->width);
97 | header->height = swapLittleAndHost32(header->height);
98 | header->colorPlanes = swapLittleAndHost16(header->colorPlanes);
99 | header->bitsPerPixel = swapLittleAndHost16(header->bitsPerPixel);
100 | header->compression = swapLittleAndHost32(header->compression);
101 | header->imageSize = swapLittleAndHost32(header->imageSize);
102 | header->xRes = swapLittleAndHost32(header->xRes);
103 | header->yRes = swapLittleAndHost32(header->yRes);
104 | header->colorsUsed = swapLittleAndHost32(header->colorsUsed);
105 | header->colorsImportant = swapLittleAndHost32(header->colorsImportant);
106 | }
107 |
108 | #elif __BYTE_ORDER == __LITTLE_ENDIAN
109 | /* No conversion necessary if we are already little endian. */
110 | #define convertBitmapFileHeader(header)
111 | #define convertBitmapInfoHeader(header)
112 | #endif
113 |
114 | /* Returns newly alloc'd image data from bitmap file. The current position of
115 | * the file must be at the start of the image before calling this. */
116 | static uint8_t *readImageData(FILE *fp, size_t width, size_t height,
117 | uint8_t bytesPerPixel, size_t bytewidth);
118 |
119 | /* Copys image buffer from |bitmap| to |dest| in BGR format. */
120 | static void copyBGRDataFromMMBitmap(MMBitmapRef bitmap, uint8_t *dest);
121 |
122 | const char *MMBMPReadErrorString(MMIOError error)
123 | {
124 | switch (error) {
125 | case kBMPAccessError:
126 | return "Could not open file";
127 | case kBMPInvalidKeyError:
128 | return "Not a BMP file";
129 | case kBMPUnsupportedHeaderError:
130 | return "Unsupported BMP header";
131 | case kBMPInvalidColorPanesError:
132 | return "Invalid number of color panes in BMP file";
133 | case kBMPUnsupportedColorDepthError:
134 | return "Unsupported color depth in BMP file";
135 | case kBMPUnsupportedCompressionError:
136 | return "Unsupported file compression in BMP file";
137 | case kBMPInvalidPixelDataError:
138 | return "Could not read BMP pixel data";
139 | default:
140 | return NULL;
141 | }
142 | }
143 |
144 | MMBitmapRef newMMBitmapFromBMP(const char *path, MMBMPReadError *err)
145 | {
146 | FILE *fp;
147 | struct BITMAP_FILE_HEADER fileHeader = {0}; /* Initialize elements to 0. */
148 | struct BITMAP_INFO_HEADER dibHeader = {0};
149 | uint32_t headerSize = 0;
150 | uint8_t bytesPerPixel;
151 | size_t bytewidth;
152 | uint8_t *imageBuf;
153 |
154 | if ((fp = fopen(path, "rb")) == NULL) {
155 | if (err != NULL) *err = kBMPAccessError;
156 | return NULL;
157 | }
158 |
159 | /* Initialize error code to generic value. */
160 | if (err != NULL) *err = kBMPGenericError;
161 |
162 | if (fread(&fileHeader, sizeof(fileHeader), 1, fp) == 0) goto bail;
163 |
164 | /* Convert from little-endian if it's not already. */
165 | convertBitmapFileHeader(&fileHeader);
166 |
167 | /* First two bytes should always be 0x4D42. */
168 | if (fileHeader.magic != BMP_MAGIC) {
169 | if (err != NULL) *err = kBMPInvalidKeyError;
170 | goto bail;
171 | }
172 |
173 | /* Get header size. */
174 | if (fread(&headerSize, sizeof(headerSize), 1, fp) == 0) goto bail;
175 | headerSize = swapLittleAndHost32(headerSize);
176 |
177 | /* Back up before reading header. */
178 | if (fseek(fp, -(long)sizeof(headerSize), SEEK_CUR) < 0) goto bail;
179 |
180 | if (headerSize == 12) { /* OS/2 v1 header */
181 | struct BITMAP_CORE_HEADER coreHeader = {0};
182 | if (fread(&coreHeader, sizeof(coreHeader), 1, fp) == 0) goto bail;
183 |
184 | dibHeader.width = coreHeader.width;
185 | dibHeader.height = coreHeader.height;
186 | dibHeader.colorPlanes = coreHeader.colorPlanes;
187 | dibHeader.bitsPerPixel = coreHeader.bitsPerPixel;
188 | } else if (headerSize == 40 || headerSize == 108 || headerSize == 124) {
189 | /* Windows v3/v4/v5 header */
190 | /* Read only the common part (v3) and skip over the rest. */
191 | if (fread(&dibHeader, sizeof(dibHeader), 1, fp) == 0) goto bail;
192 | } else {
193 | if (err != NULL) *err = kBMPUnsupportedHeaderError;
194 | goto bail;
195 | }
196 |
197 | convertBitmapInfoHeader(&dibHeader);
198 |
199 | if (dibHeader.colorPlanes != 1) {
200 | if (err != NULL) *err = kBMPInvalidColorPanesError;
201 | goto bail;
202 | }
203 |
204 | /* Currently only 24-bit and 32-bit are supported. */
205 | if (dibHeader.bitsPerPixel != 24 && dibHeader.bitsPerPixel != 32) {
206 | if (err != NULL) *err = kBMPUnsupportedColorDepthError;
207 | goto bail;
208 | }
209 |
210 | if (dibHeader.compression != kBMP_RGB) {
211 | if (err != NULL) *err = kBMPUnsupportedCompressionError;
212 | goto bail;
213 | }
214 |
215 | /* This can happen because we don't fully parse Windows v4/v5 headers. */
216 | if (ftell(fp) != (long)fileHeader.imageOffset) {
217 | fseek(fp, fileHeader.imageOffset, SEEK_SET);
218 | }
219 |
220 | /* Get bytes per row, including padding. */
221 | bytesPerPixel = dibHeader.bitsPerPixel / 8;
222 | bytewidth = ADD_PADDING(dibHeader.width * bytesPerPixel);
223 |
224 | imageBuf = readImageData(fp, dibHeader.width, abs(dibHeader.height),
225 | bytesPerPixel, bytewidth);
226 | fclose(fp);
227 |
228 | if (imageBuf == NULL) {
229 | if (err != NULL) *err = kBMPInvalidPixelDataError;
230 | return NULL;
231 | }
232 |
233 | /* A negative height indicates that the image is flipped.
234 | *
235 | * We store our bitmaps as "flipped" according to the BMP format; i.e., (0, 0)
236 | * is the top left, not bottom left. So we only need to flip the bitmap if
237 | * the height is NOT negative. */
238 | if (dibHeader.height < 0) {
239 | dibHeader.height = -dibHeader.height;
240 | } else {
241 | flipBitmapData(imageBuf, dibHeader.width, dibHeader.height, bytewidth);
242 | }
243 |
244 | return createMMBitmap(imageBuf, dibHeader.width, dibHeader.height,
245 | bytewidth, (uint8_t)dibHeader.bitsPerPixel,
246 | bytesPerPixel);
247 |
248 | bail:
249 | fclose(fp);
250 | return NULL;
251 | }
252 |
253 | uint8_t *createBitmapData(MMBitmapRef bitmap, size_t *len)
254 | {
255 | /* BMP files are always aligned to 4 bytes. */
256 | const size_t bytewidth = ((bitmap->width * bitmap->bytesPerPixel) + 3) & ~3;
257 |
258 | const size_t imageSize = bytewidth * bitmap->height;
259 | struct BITMAP_FILE_HEADER *fileHeader;
260 | struct BITMAP_INFO_HEADER *dibHeader;
261 |
262 | /* Should always be 54. */
263 | const size_t imageOffset = sizeof(*fileHeader) + sizeof(*dibHeader);
264 | uint8_t *data;
265 | const size_t dataLen = imageOffset + imageSize;
266 |
267 | data = calloc(1, dataLen);
268 | if (data == NULL) return NULL;
269 |
270 | /* Save top header. */
271 | fileHeader = (struct BITMAP_FILE_HEADER *)data;
272 | fileHeader->magic = BMP_MAGIC;
273 | fileHeader->fileSize = (uint32_t)(sizeof(*dibHeader) + imageSize);
274 | fileHeader->imageOffset = (uint32_t)imageOffset;
275 |
276 | /* BMP files are always stored as little-endian, so we need to convert back
277 | * if necessary. */
278 | convertBitmapFileHeader(fileHeader);
279 |
280 | /* Copy Windows v3 header. */
281 | dibHeader = (struct BITMAP_INFO_HEADER *)(data + sizeof(*fileHeader));
282 | dibHeader->headerSize = sizeof(*dibHeader); /* Should always be 40. */
283 | dibHeader->width = (int32_t)bitmap->width;
284 | dibHeader->height = -(int32_t)bitmap->height; /* Our bitmaps are "flipped". */
285 | dibHeader->colorPlanes = 1;
286 | dibHeader->bitsPerPixel = bitmap->bitsPerPixel;
287 | dibHeader->compression = kBMP_RGB; /* Don't save with compression. */
288 | dibHeader->imageSize = (uint32_t)imageSize;
289 |
290 | convertBitmapInfoHeader(dibHeader);
291 |
292 | /* Lastly, copy the pixel data. */
293 | copyBGRDataFromMMBitmap(bitmap, data + imageOffset);
294 |
295 | if (len != NULL) *len = dataLen;
296 | return data;
297 | }
298 |
299 | int saveMMBitmapAsBMP(MMBitmapRef bitmap, const char *path)
300 | {
301 | FILE *fp;
302 | size_t dataLen;
303 | uint8_t *data;
304 |
305 | if ((fp = fopen(path, "wb")) == NULL) return -1;
306 |
307 | if ((data = createBitmapData(bitmap, &dataLen)) == NULL) {
308 | fclose(fp);
309 | return -1;
310 | }
311 |
312 | if (fwrite(data, dataLen, 1, fp) == 0) {
313 | free(data);
314 | fclose(fp);
315 | return -1;
316 | }
317 |
318 | free(data);
319 | fclose(fp);
320 | return 0;
321 | }
322 |
323 | static uint8_t *readImageData(FILE *fp, size_t width, size_t height,
324 | uint8_t bytesPerPixel, size_t bytewidth)
325 | {
326 | size_t imageSize = bytewidth * height;
327 | uint8_t *imageBuf = calloc(1, imageSize);
328 |
329 | if (MMRGB_IS_BGR && (bytewidth % 4) == 0) { /* No conversion needed. */
330 | if (fread(imageBuf, imageSize, 1, fp) == 0) {
331 | free(imageBuf);
332 | return NULL;
333 | }
334 | } else { /* Convert from BGR with 4-byte alignment. */
335 | uint8_t *row = malloc(bytewidth);
336 | size_t y;
337 | const size_t bmp_bytewidth = (width * bytesPerPixel + 3) & ~3;
338 |
339 | if (row == NULL) return NULL;
340 | assert(bmp_bytewidth <= bytewidth);
341 |
342 | /* Read image data row by row. */
343 | for (y = 0; y < height; ++y) {
344 | const size_t rowOffset = y * bytewidth;
345 | size_t x;
346 | uint8_t *rowptr = row;
347 | if (fread(row, bmp_bytewidth, 1, fp) == 0) {
348 | free(imageBuf);
349 | free(row);
350 | return NULL;
351 | }
352 |
353 | for (x = 0; x < width; ++x) {
354 | const size_t colOffset = x * bytesPerPixel;
355 | MMRGBColor *color = (MMRGBColor *)(imageBuf +
356 | rowOffset + colOffset);
357 |
358 | /* BMP files are stored in BGR format. */
359 | color->blue = rowptr[0];
360 | color->green = rowptr[1];
361 | color->red = rowptr[2];
362 | rowptr += bytesPerPixel;
363 | }
364 | }
365 |
366 | free(row);
367 | }
368 |
369 | return imageBuf;
370 | }
371 |
372 | static void copyBGRDataFromMMBitmap(MMBitmapRef bitmap, uint8_t *dest)
373 | {
374 | if (MMRGB_IS_BGR && (bitmap->bytewidth % 4) == 0) { /* No conversion needed. */
375 | memcpy(dest, bitmap->imageBuffer, bitmap->bytewidth * bitmap->height);
376 | } else { /* Convert to RGB with other-than-4-byte alignment. */
377 | const size_t bytewidth = (bitmap->width * bitmap->bytesPerPixel + 3) & ~3;
378 | size_t y;
379 |
380 | /* Copy image data row by row. */
381 | for (y = 0; y < bitmap->height; ++y) {
382 | uint8_t *rowptr = dest + (y * bytewidth);
383 | size_t x;
384 | for (x = 0; x < bitmap->width; ++x) {
385 | MMRGBColor *color = MMRGBColorRefAtPoint(bitmap, x, y);
386 |
387 | /* BMP files are stored in BGR format. */
388 | rowptr[0] = color->blue;
389 | rowptr[1] = color->green;
390 | rowptr[2] = color->red;
391 |
392 | rowptr += bitmap->bytesPerPixel;
393 | }
394 | }
395 | }
396 | }
397 |
398 | /* Perform an in-place swap from Quadrant 1 to Quadrant III format (upside-down
399 | * PostScript/GL to right side up QD/CG raster format) We do this in-place,
400 | * which requires more copying, but will touch only half the pages.
401 | *
402 | * This is blatantly copied from Apple's glGrab example code. */
403 | void flipBitmapData(void *data, size_t width, size_t height, size_t bytewidth)
404 | {
405 | size_t top, bottom;
406 | void *topP;
407 | void *bottomP;
408 | void *tempbuf;
409 |
410 | if (height <= 1) return; /* No flipping necessary if height is <= 1. */
411 |
412 | top = 0;
413 | bottom = height - 1;
414 | tempbuf = malloc(bytewidth);
415 | if (tempbuf == NULL) return;
416 |
417 | while (top < bottom) {
418 | topP = (void *)((top * bytewidth) + (intptr_t)data);
419 | bottomP = (void *)((bottom * bytewidth) + (intptr_t)data);
420 |
421 | /* Save and swap scanlines.
422 | * Does a simple in-place exchange with a temp buffer. */
423 | memcpy(tempbuf, topP, bytewidth);
424 | memcpy(topP, bottomP, bytewidth);
425 | memcpy(bottomP, tempbuf, bytewidth);
426 |
427 | ++top;
428 | --bottom;
429 | }
430 | free(tempbuf);
431 | }
432 |
--------------------------------------------------------------------------------
/src/bmp_io.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef BMP_IO_H
3 | #define BMP_IO_H
4 |
5 | #include "MMBitmap.h"
6 | #include "io.h"
7 |
8 | #ifdef __cplusplus
9 | extern "C"
10 | {
11 | #endif
12 |
13 | enum _BMPReadError {
14 | kBMPGenericError = 0,
15 | kBMPAccessError,
16 | kBMPInvalidKeyError,
17 | kBMPUnsupportedHeaderError,
18 | kBMPInvalidColorPanesError,
19 | kBMPUnsupportedColorDepthError,
20 | kBMPUnsupportedCompressionError,
21 | kBMPInvalidPixelDataError
22 | };
23 |
24 | typedef MMIOError MMBMPReadError;
25 |
26 | /* Returns description of given MMBMPReadError.
27 | * Returned string is constant and hence should not be freed. */
28 | const char *MMBMPReadErrorString(MMIOError error);
29 |
30 | /* Attempts to read bitmap file at path; returns new MMBitmap on success, or
31 | * NULL on error. If |error| is non-NULL, it will be set to the error code
32 | * on return.
33 | *
34 | * Currently supports:
35 | * - Uncompressed Windows v3/v4/v5 24-bit or 32-bit BMP.
36 | * - OS/2 v1 or v2 24-bit BMP.
37 | * - Does NOT yet support: 1-bit, 4-bit, 8-bit, 16-bit, compressed bitmaps,
38 | * or PNGs/JPEGs disguised as BMPs (and returns NULL if those are given).
39 | *
40 | * Responsibility for destroy()'ing returned MMBitmap is left up to caller. */
41 | MMBitmapRef newMMBitmapFromBMP(const char *path, MMBMPReadError *error);
42 |
43 | /* Returns a buffer containing the raw BMP file data in Windows v3 BMP format,
44 | * ready to be saved to a file. If |len| is not NULL, it will be set to the
45 | * number of bytes allocated in the returned buffer.
46 | *
47 | * Responsibility for free()'ing data is left up to the caller. */
48 | uint8_t *createBitmapData(MMBitmapRef bitmap, size_t *len);
49 |
50 | /* Saves bitmap to file in Windows v3 BMP format.
51 | * Returns 0 on success, -1 on error. */
52 | int saveMMBitmapAsBMP(MMBitmapRef bitmap, const char *path);
53 |
54 | /* Swaps bitmap from Quadrant 1 to Quadran III format, or vice versa
55 | * (upside-down Cartesian/PostScript/GL <-> right side up QD/CG raster format).
56 | */
57 | void flipBitmapData(void *data, size_t width, size_t height, size_t bytewidth);
58 |
59 | #ifdef __cplusplus
60 | }
61 | #endif
62 |
63 | #endif /* BMP_IO_H */
64 |
--------------------------------------------------------------------------------
/src/color_find.c:
--------------------------------------------------------------------------------
1 | #include "color_find.h"
2 | #include "screen.h"
3 | #include
4 |
5 | /* Abstracted, general function to avoid repeated code. */
6 | static int findColorInRectAt(MMBitmapRef image, MMRGBHex color, MMPoint *point,
7 | MMRect rect, float tolerance, MMPoint startPoint)
8 | {
9 | MMPoint scan = startPoint;
10 | if (!MMBitmapRectInBounds(image, rect)) return -1;
11 |
12 | for (; scan.y < rect.size.height; ++scan.y) {
13 | for (; scan.x < rect.size.width; ++scan.x) {
14 | MMRGBHex found = MMRGBHexAtPoint(image, scan.x, scan.y);
15 | if (MMRGBHexSimilarToColor(color, found, tolerance)) {
16 | if (point != NULL) *point = scan;
17 | return 0;
18 | }
19 | }
20 | scan.x = rect.origin.x;
21 | }
22 |
23 | return -1;
24 | }
25 |
26 | int findColorInRect(MMBitmapRef image, MMRGBHex color,
27 | MMPoint *point, MMRect rect, float tolerance)
28 | {
29 | return findColorInRectAt(image, color, point, rect, tolerance, rect.origin);
30 | }
31 |
32 | MMPointArrayRef findAllColorInRect(MMBitmapRef image, MMRGBHex color,
33 | MMRect rect, float tolerance)
34 | {
35 | MMPointArrayRef pointArray = createMMPointArray(0);
36 | MMPoint point = MMPointZero;
37 |
38 | while (findColorInRectAt(image, color, &point, rect, tolerance, point) == 0) {
39 | MMPointArrayAppendPoint(pointArray, point);
40 | ITER_NEXT_POINT(point, rect.size.width, rect.origin.x);
41 | }
42 |
43 | return pointArray;
44 | }
45 |
46 | size_t countOfColorsInRect(MMBitmapRef image, MMRGBHex color, MMRect rect,
47 | float tolerance)
48 | {
49 | size_t count = 0;
50 | MMPoint point = MMPointZero;
51 |
52 | while (findColorInRectAt(image, color, &point, rect, tolerance, point) == 0) {
53 | ITER_NEXT_POINT(point, rect.size.width, rect.origin.x);
54 | ++count;
55 | }
56 |
57 | return count;
58 | }
59 |
--------------------------------------------------------------------------------
/src/color_find.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef COLOR_FIND_H
3 | #define COLOR_FIND_H
4 |
5 | #include "MMBitmap.h"
6 | #include "MMPointArray.h"
7 |
8 | /* Convenience wrapper around findColorInRect(), where |rect| is the bounds of
9 | * the image. */
10 | #define findColorInImage(image, color, pointPtr, tolerance) \
11 | findColorInRect(image, color, pointPtr, MMBitmapGetBounds(image), tolerance)
12 |
13 | /* Attempt to find a pixel with the given color in |image| inside |rect|.
14 | * Returns 0 on success, non-zero on failure. If the color was found and
15 | * |point| is not NULL, it will be initialized to the (x, y) coordinates the
16 | * RGB color.
17 | *
18 | * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the
19 | * colors need to match, with 0 being exact and 1 being any. */
20 | int findColorInRect(MMBitmapRef image, MMRGBHex color, MMPoint *point,
21 | MMRect rect, float tolerance);
22 |
23 | /* Convenience wrapper around findAllRGBInRect(), where |rect| is the bounds of
24 | * the image. */
25 | #define findAllColorInImage(image, color, tolerance) \
26 | findAllColorInRect(image, color, MMBitmapGetBounds(image), tolerance)
27 |
28 | /* Returns MMPointArray of all pixels of given color in |image| inside of
29 | * |rect|. Note that an array is returned regardless of whether the color was
30 | * found; check array->count to see if it actually was.
31 | *
32 | * Responsibility for freeing the MMPointArray with destroyMMPointArray() is
33 | * given to the caller.
34 | *
35 | * |tolerance| should be in the range 0.0f - 1.0f, denoting how closely the
36 | * colors need to match, with 0 being exact and 1 being any. */
37 | MMPointArrayRef findAllColorInRect(MMBitmapRef image, MMRGBHex color,
38 | MMRect rect, float tolerance);
39 |
40 | /* Convenience wrapper around countOfColorsInRect, where |rect| is the bounds
41 | * of the image. */
42 | #define countOfColorsInImage(image, color, tolerance) \
43 | countOfColorsInRect(image, color, MMBitmapGetBounds(image), tolerance)
44 |
45 | /* Returns the count of the given color in |rect| inside of |image|. */
46 | size_t countOfColorsInRect(MMBitmapRef image, MMRGBHex color, MMRect rect,
47 | float tolerance);
48 |
49 | #endif /* COLOR_FIND_H */
50 |
--------------------------------------------------------------------------------
/src/deadbeef_rand.c:
--------------------------------------------------------------------------------
1 | #include "deadbeef_rand.h"
2 | #include
3 |
4 | static uint32_t deadbeef_seed;
5 | static uint32_t deadbeef_beef = 0xdeadbeef;
6 |
7 | uint32_t deadbeef_rand(void)
8 | {
9 | deadbeef_seed = (deadbeef_seed << 7) ^ ((deadbeef_seed >> 25) + deadbeef_beef);
10 | deadbeef_beef = (deadbeef_beef << 7) ^ ((deadbeef_beef >> 25) + 0xdeadbeef);
11 | return deadbeef_seed;
12 | }
13 |
14 | void deadbeef_srand(uint32_t x)
15 | {
16 | deadbeef_seed = x;
17 | deadbeef_beef = 0xdeadbeef;
18 | }
19 |
20 | /* Taken directly from the documentation:
21 | * http://inglorion.net/software/cstuff/deadbeef_rand/ */
22 | uint32_t deadbeef_generate_seed(void)
23 | {
24 | uint32_t t = (uint32_t)time(NULL);
25 | uint32_t c = (uint32_t)clock();
26 | return (t << 24) ^ (c << 11) ^ t ^ (size_t) &c;
27 | }
28 |
--------------------------------------------------------------------------------
/src/deadbeef_rand.h:
--------------------------------------------------------------------------------
1 | #ifndef DEADBEEF_RAND_H
2 | #define DEADBEEF_RAND_H
3 |
4 | #include
5 |
6 | #define DEADBEEF_MAX UINT32_MAX
7 |
8 | /* Dead Beef Random Number Generator
9 | * From: http://inglorion.net/software/deadbeef_rand
10 | * A fast, portable psuedo-random number generator by BJ Amsterdam Zuidoost.
11 | * Stated in license terms: "Feel free to use the code in your own software." */
12 |
13 | /* Generates a random number between 0 and DEADBEEF_MAX. */
14 | uint32_t deadbeef_rand(void);
15 |
16 | /* Seeds with the given integer. */
17 | void deadbeef_srand(uint32_t x);
18 |
19 | /* Generates seed from the current time. */
20 | uint32_t deadbeef_generate_seed(void);
21 |
22 | /* Seeds with the above function. */
23 | #define deadbeef_srand_time() deadbeef_srand(deadbeef_generate_seed())
24 |
25 | /* Returns random double in the range [a, b).
26 | * Taken directly from the rand() man page. */
27 | #define DEADBEEF_UNIFORM(a, b) \
28 | ((a) + (deadbeef_rand() / (((double)DEADBEEF_MAX / (b - a) + 1))))
29 |
30 | /* Returns random integer in the range [a, b).
31 | * Also taken from the rand() man page. */
32 | #define DEADBEEF_RANDRANGE(a, b) \
33 | (uint32_t)DEADBEEF_UNIFORM(a, b)
34 |
35 | #endif /* DEADBEEF_RAND_H */
36 |
--------------------------------------------------------------------------------
/src/endian.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef ENDIAN_H
3 | #define ENDIAN_H
4 |
5 | #include "os.h"
6 |
7 | /*
8 | * (Mostly) cross-platform endian definitions and bit swapping macros.
9 | * Unfortunately, there is no standard C header for this, so we just
10 | * include the most common ones and fallback to our own custom macros.
11 | */
12 |
13 | #if defined(__linux__) /* Linux */
14 | #include
15 | #include
16 | #elif (defined(__FreeBSD__) && __FreeBSD_version >= 470000) || \
17 | defined(__OpenBSD__) || defined(__NetBSD__) /* (Free|Open|Net)BSD */
18 | #include
19 | #define __BIG_ENDIAN BIG_ENDIAN
20 | #define __LITTLE_ENDIAN LITTLE_ENDIAN
21 | #define __BYTE_ORDER BYTE_ORDER
22 | #elif defined(IS_MACOSX) || (defined(BSD) && (BSD >= 199103)) /* Other BSD */
23 | #include
24 | #define __BIG_ENDIAN BIG_ENDIAN
25 | #define __LITTLE_ENDIAN LITTLE_ENDIAN
26 | #define __BYTE_ORDER BYTE_ORDER
27 | #elif defined(IS_WINDOWS) /* Windows is assumed to be little endian only. */
28 | #define __BIG_ENDIAN 4321
29 | #define __LITTLE_ENDIAN 1234
30 | #define __BYTE_ORDER __LITTLE_ENDIAN
31 | #endif
32 |
33 | /* Fallback to custom constants. */
34 | #if !defined(__BIG_ENDIAN)
35 | #define __BIG_ENDIAN 4321
36 | #endif
37 |
38 | #if !defined(__LITTLE_ENDIAN)
39 | #define __LITTLE_ENDIAN 1234
40 | #endif
41 |
42 | /* Prefer compiler flag settings if given. */
43 | #if defined(MM_BIG_ENDIAN)
44 | #undef __BYTE_ORDER /* Avoid redefined macro compiler warning. */
45 | #define __BYTE_ORDER __BIG_ENDIAN
46 | #elif defined(MM_LITTLE_ENDIAN)
47 | #undef __BYTE_ORDER /* Avoid redefined macro compiler warning. */
48 | #define __BYTE_ORDER __LITTLE_ENDIAN
49 | #endif
50 |
51 | /* Define default endian-ness. */
52 | #ifndef __LITTLE_ENDIAN
53 | #define __LITTLE_ENDIAN 1234
54 | #endif /* __LITTLE_ENDIAN */
55 |
56 | #ifndef __BIG_ENDIAN
57 | #define __BIG_ENDIAN 4321
58 | #endif /* __BIG_ENDIAN */
59 |
60 | #ifndef __BYTE_ORDER
61 | #warning "Byte order not defined on your system; assuming little endian"
62 | #define __BYTE_ORDER __LITTLE_ENDIAN
63 | #endif /* __BYTE_ORDER */
64 |
65 | #if __BYTE_ORDER != __BIG_ENDIAN && __BYTE_ORDER != __LITTLE_ENDIAN
66 | #error "__BYTE_ORDER set to unknown byte order"
67 | #endif
68 |
69 | #if defined(IS_MACOSX)
70 | #include
71 |
72 | /* OS X system functions. */
73 | #define bitswap16(i) OSSwapInt16(i)
74 | #define bitswap32(i) OSSwapInt32(i)
75 | #define swapLittleAndHost32(i) OSSwapLittleToHostInt32(i)
76 | #define swapLittleAndHost16(i) OSSwapLittleToHostInt16(i)
77 | #else
78 | #ifndef bitswap16
79 | #if defined(bswap16)
80 | #define bitswap16(i) bswap16(i) /* FreeBSD system function */
81 | #elif defined(bswap_16)
82 | #define bitswap16(i) bswap_16(i) /* Linux system function */
83 | #else /* Default macro */
84 | #define bitswap16(i) (((uint16_t)(i) & 0xFF00) >> 8) | \
85 | (((uint16_t)(i) & 0x00FF) << 8)
86 | #endif
87 | #endif /* bitswap16 */
88 |
89 | #ifndef bitswap32
90 | #if defined(bswap32)
91 | #define bitswap32(i) bswap32(i) /* FreeBSD system function. */
92 | #elif defined(bswap_32)
93 | #define bitswap32(i) bswap_32(i) /* Linux system function. */
94 | #else /* Default macro */
95 | #define bitswap32(i) (((uint32_t)(i) & 0xFF000000) >> 24) | \
96 | ((uint32_t)((i) & 0x00FF0000) >> 8) | \
97 | ((uint32_t)((i) & 0x0000FF00) << 8) | \
98 | ((uint32_t)((i) & 0x000000FF) << 24)
99 | #endif
100 | #endif /* bitswap32 */
101 | #endif
102 |
103 | #if __BYTE_ORDER == __BIG_ENDIAN
104 | /* Little endian to/from host byte order (big endian). */
105 | #ifndef swapLittleAndHost16
106 | #define swapLittleAndHost16(i) bitswap16(i)
107 | #endif /* swapLittleAndHost16 */
108 |
109 | #ifndef swapLittleAndHost32
110 | #define swapLittleAndHost32(i) bitswap32(i)
111 | #endif /* swapLittleAndHost32 */
112 | #elif __BYTE_ORDER == __LITTLE_ENDIAN
113 | /* We are already little endian, so no conversion is needed. */
114 | #ifndef swapLittleAndHost16
115 | #define swapLittleAndHost16(i) i
116 | #endif /* swapLittleAndHost16 */
117 |
118 | #ifndef swapLittleAndHost32
119 | #define swapLittleAndHost32(i) i
120 | #endif /* swapLittleAndHost32 */
121 | #endif
122 |
123 | #endif /* ENDIAN_H */
124 |
--------------------------------------------------------------------------------
/src/inline_keywords.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | /* A complicated, portable model for declaring inline functions in
4 | * header files. */
5 | #if !defined(H_INLINE)
6 | #if defined(__GNUC__)
7 | #define H_INLINE static __inline__ __attribute__((always_inline))
8 | #elif defined(__MWERKS__) || defined(__cplusplus)
9 | #define H_INLINE static inline
10 | #elif defined(_MSC_VER)
11 | #define H_INLINE static __inline
12 | #elif TARGET_OS_WIN32
13 | #define H_INLINE static __inline__
14 | #endif
15 | #endif /* H_INLINE */
16 |
--------------------------------------------------------------------------------
/src/io.c:
--------------------------------------------------------------------------------
1 | #include "io.h"
2 | #include "os.h"
3 | #include "bmp_io.h"
4 | #include "png_io.h"
5 | #include /* For fputs() */
6 | #include /* For strcmp() */
7 | #include /* For tolower() */
8 |
9 | const char *getExtension(const char *fname, size_t len)
10 | {
11 | if (fname == NULL || len <= 0) return NULL;
12 |
13 | while (--len > 0 && fname[len] != '.' && fname[len] != '\0')
14 | ;
15 |
16 | return fname + len + 1;
17 | }
18 |
19 | MMImageType imageTypeFromExtension(const char *extension)
20 | {
21 | char ext[4];
22 | const size_t maxlen = sizeof(ext) / sizeof(ext[0]);
23 | size_t i;
24 |
25 | for (i = 0; extension[i] != '\0'; ++i) {
26 | if (i >= maxlen) return kInvalidImageType;
27 | ext[i] = tolower(extension[i]);
28 | }
29 | ext[i] = '\0';
30 |
31 | if (strcmp(ext, "png") == 0) {
32 | return kPNGImageType;
33 | } else if (strcmp(ext, "bmp") == 0) {
34 | return kBMPImageType;
35 | } else {
36 | return kInvalidImageType;
37 | }
38 | }
39 |
40 | MMBitmapRef newMMBitmapFromFile(const char *path,
41 | MMImageType type,
42 | MMIOError *err)
43 | {
44 | switch (type) {
45 | case kBMPImageType:
46 | return newMMBitmapFromBMP(path, err);
47 | case kPNGImageType:
48 | return newMMBitmapFromPNG(path, err);
49 | default:
50 | if (err != NULL) *err = kMMIOUnsupportedTypeError;
51 | return NULL;
52 | }
53 | }
54 |
55 | int saveMMBitmapToFile(MMBitmapRef bitmap,
56 | const char *path,
57 | MMImageType type)
58 | {
59 | switch (type) {
60 | case kBMPImageType:
61 | return saveMMBitmapAsBMP(bitmap, path);
62 | case kPNGImageType:
63 | return saveMMBitmapAsPNG(bitmap, path);
64 | default:
65 | return -1;
66 | }
67 | }
68 |
69 | const char *MMIOErrorString(MMImageType type, MMIOError error)
70 | {
71 | switch (type) {
72 | case kBMPImageType:
73 | return MMBMPReadErrorString(error);
74 | case kPNGImageType:
75 | return MMPNGReadErrorString(error);
76 | default:
77 | return "Unsupported image type";
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/io.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef IO_H
3 | #define IO_H
4 |
5 | #include "MMBitmap.h"
6 | #include
7 | #include
8 |
9 | #ifdef __cplusplus
10 | extern "C"
11 | {
12 | #endif
13 |
14 | enum _MMImageType {
15 | kInvalidImageType = 0,
16 | kPNGImageType,
17 | kBMPImageType /* Currently only PNG and BMP are supported. */
18 | };
19 |
20 | typedef uint16_t MMImageType;
21 |
22 | enum _MMIOError {
23 | kMMIOUnsupportedTypeError = 0
24 | };
25 |
26 | typedef uint16_t MMIOError;
27 |
28 | const char *getExtension(const char *fname, size_t len);
29 |
30 | /* Returns best guess at the MMImageType based on a file extension, or
31 | * |kInvalidImageType| if no matching type was found. */
32 | MMImageType imageTypeFromExtension(const char *ext);
33 |
34 | /* Attempts to parse the file of the given type at the given path.
35 | * |filepath| is an ASCII string describing the absolute POSIX path.
36 | * Returns new bitmap (to be destroy()'d by caller) on success, NULL on error.
37 | * If |error| is non-NULL, it will be set to the error code on return.
38 | */
39 | MMBitmapRef newMMBitmapFromFile(const char *path, MMImageType type, MMIOError *err);
40 |
41 | /* Saves |bitmap| to a file of the given type at the given path.
42 | * |filepath| is an ASCII string describing the absolute POSIX path.
43 | * Returns 0 on success, -1 on error. */
44 | int saveMMBitmapToFile(MMBitmapRef bitmap, const char *path, MMImageType type);
45 |
46 | /* Returns description of given error code.
47 | * Returned string is constant and hence should not be freed. */
48 | const char *MMIOErrorString(MMImageType type, MMIOError error);
49 |
50 | #ifdef __cplusplus
51 | }
52 | #endif
53 |
54 |
55 | #endif /* IO_H */
56 |
--------------------------------------------------------------------------------
/src/keycode.c:
--------------------------------------------------------------------------------
1 | #include "keycode.h"
2 |
3 | #if defined(IS_MACOSX)
4 |
5 | #include
6 | #include /* For kVK_ constants, and TIS functions. */
7 |
8 | /* Returns string representation of key, if it is printable.
9 | * Ownership follows the Create Rule; that is, it is the caller's
10 | * responsibility to release the returned object. */
11 | CFStringRef createStringForKey(CGKeyCode keyCode);
12 |
13 | #elif defined(USE_X11)
14 |
15 | /*
16 | * Structs to store key mappings not handled by XStringToKeysym() on some
17 | * Linux systems.
18 | */
19 |
20 | struct XSpecialCharacterMapping {
21 | char name;
22 | MMKeyCode code;
23 | };
24 |
25 | struct XSpecialCharacterMapping XSpecialCharacterTable[] = {
26 | {'~', XK_asciitilde},
27 | {'_', XK_underscore},
28 | {'[', XK_bracketleft},
29 | {']', XK_bracketright},
30 | {'!', XK_exclam},
31 | {'\'', XK_quotedbl},
32 | {'#', XK_numbersign},
33 | {'$', XK_dollar},
34 | {'%', XK_percent},
35 | {'&', XK_ampersand},
36 | {'\'', XK_quoteright},
37 | {'*', XK_asterisk},
38 | {'+', XK_plus},
39 | {',', XK_comma},
40 | {'-', XK_minus},
41 | {'.', XK_period},
42 | {'?', XK_question},
43 | {'<', XK_less},
44 | {'>', XK_greater},
45 | {'=', XK_equal},
46 | {'@', XK_at},
47 | {':', XK_colon},
48 | {';', XK_semicolon},
49 | {'\\', XK_backslash},
50 | {'`', XK_grave},
51 | {'{', XK_braceleft},
52 | {'}', XK_braceright},
53 | {'|', XK_bar},
54 | {'^', XK_asciicircum},
55 | {'(', XK_parenleft},
56 | {')', XK_parenright},
57 | {' ', XK_space},
58 | {'/', XK_slash},
59 | {'\t', XK_Tab},
60 | {'\n', XK_Return}
61 | };
62 |
63 | #endif
64 |
65 | MMKeyCode keyCodeForChar(const char c)
66 | {
67 | #if defined(IS_MACOSX)
68 | /* OS X does not appear to have a built-in function for this, so instead we
69 | * have to write our own. */
70 | static CFMutableDictionaryRef charToCodeDict = NULL;
71 | size_t code;
72 | UniChar character = c;
73 | CFStringRef charStr = NULL;
74 |
75 | /* Generate table of keycodes and characters. */
76 | if (charToCodeDict == NULL) {
77 | size_t i;
78 | charToCodeDict = CFDictionaryCreateMutable(kCFAllocatorDefault,
79 | 128,
80 | &kCFCopyStringDictionaryKeyCallBacks,
81 | NULL);
82 | if (charToCodeDict == NULL) return UINT16_MAX;
83 |
84 | /* Loop through every keycode (0 - 127) to find its current mapping. */
85 | for (i = 0; i < 128; ++i) {
86 | CFStringRef string = createStringForKey((CGKeyCode)i);
87 | if (string != NULL) {
88 | CFDictionaryAddValue(charToCodeDict, string, (const void *)i);
89 | CFRelease(string);
90 | }
91 | }
92 | }
93 |
94 | charStr = CFStringCreateWithCharacters(kCFAllocatorDefault, &character, 1);
95 |
96 | /* Our values may be NULL (0), so we need to use this function. */
97 | if (!CFDictionaryGetValueIfPresent(charToCodeDict, charStr,
98 | (const void **)&code)) {
99 | code = UINT16_MAX; /* Error */
100 | }
101 |
102 | CFRelease(charStr);
103 | return (MMKeyCode)code;
104 | #elif defined(IS_WINDOWS)
105 | return VkKeyScan(c);
106 | #elif defined(USE_X11)
107 | MMKeyCode code;
108 |
109 | char buf[2];
110 | buf[0] = c;
111 | buf[1] = '\0';
112 |
113 | code = XStringToKeysym(buf);
114 | if (code == NoSymbol) {
115 | /* Some special keys are apparently not handled properly by
116 | * XStringToKeysym() on some systems, so search for them instead in our
117 | * mapping table. */
118 | size_t i;
119 | const size_t specialCharacterCount =
120 | sizeof(XSpecialCharacterTable) / sizeof(XSpecialCharacterTable[0]);
121 | for (i = 0; i < specialCharacterCount; ++i) {
122 | if (c == XSpecialCharacterTable[i].name) {
123 | code = XSpecialCharacterTable[i].code;
124 | break;
125 | }
126 | }
127 | }
128 |
129 | return code;
130 | #endif
131 | }
132 |
133 | #if defined(IS_MACOSX)
134 |
135 | CFStringRef createStringForKey(CGKeyCode keyCode)
136 | {
137 | TISInputSourceRef currentKeyboard = TISCopyCurrentASCIICapableKeyboardInputSource();
138 | CFDataRef layoutData =
139 | TISGetInputSourceProperty(currentKeyboard,
140 | kTISPropertyUnicodeKeyLayoutData);
141 | const UCKeyboardLayout *keyboardLayout =
142 | (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
143 |
144 | UInt32 keysDown = 0;
145 | UniChar chars[4];
146 | UniCharCount realLength;
147 |
148 | UCKeyTranslate(keyboardLayout,
149 | keyCode,
150 | kUCKeyActionDisplay,
151 | 0,
152 | LMGetKbdType(),
153 | kUCKeyTranslateNoDeadKeysBit,
154 | &keysDown,
155 | sizeof(chars) / sizeof(chars[0]),
156 | &realLength,
157 | chars);
158 | CFRelease(currentKeyboard);
159 |
160 | return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1);
161 | }
162 |
163 | #endif
164 |
--------------------------------------------------------------------------------
/src/keycode.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef KEYCODE_H
3 | #define KEYCODE_H
4 |
5 | #include "os.h"
6 |
7 | #ifdef __cplusplus
8 | extern "C"
9 | {
10 | #endif
11 |
12 | #if defined(IS_MACOSX)
13 |
14 | #include /* Really only need */
15 | #include
16 | #import
17 |
18 | enum _MMKeyCode {
19 | K_NOT_A_KEY = 9999,
20 | K_BACKSPACE = kVK_Delete,
21 | K_DELETE = kVK_ForwardDelete,
22 | K_RETURN = kVK_Return,
23 | K_TAB = kVK_Tab,
24 | K_ESCAPE = kVK_Escape,
25 | K_UP = kVK_UpArrow,
26 | K_DOWN = kVK_DownArrow,
27 | K_RIGHT = kVK_RightArrow,
28 | K_LEFT = kVK_LeftArrow,
29 | K_HOME = kVK_Home,
30 | K_END = kVK_End,
31 | K_PAGEUP = kVK_PageUp,
32 | K_PAGEDOWN = kVK_PageDown,
33 | K_F1 = kVK_F1,
34 | K_F2 = kVK_F2,
35 | K_F3 = kVK_F3,
36 | K_F4 = kVK_F4,
37 | K_F5 = kVK_F5,
38 | K_F6 = kVK_F6,
39 | K_F7 = kVK_F7,
40 | K_F8 = kVK_F8,
41 | K_F9 = kVK_F9,
42 | K_F10 = kVK_F10,
43 | K_F11 = kVK_F11,
44 | K_F12 = kVK_F12,
45 | K_F13 = kVK_F13,
46 | K_F14 = kVK_F14,
47 | K_F15 = kVK_F15,
48 | K_F16 = kVK_F16,
49 | K_F17 = kVK_F17,
50 | K_F18 = kVK_F18,
51 | K_F19 = kVK_F19,
52 | K_F20 = kVK_F20,
53 | K_F21 = K_NOT_A_KEY,
54 | K_F22 = K_NOT_A_KEY,
55 | K_F23 = K_NOT_A_KEY,
56 | K_F24 = K_NOT_A_KEY,
57 | K_META = kVK_Command,
58 | K_ALT = kVK_Option,
59 | K_RIGHT_ALT = kVK_Option,
60 | K_CONTROL = kVK_Control,
61 | K_LEFT_CONTROL = kVK_Control,
62 | K_RIGHT_CONTROL = kVK_RightControl,
63 | K_SHIFT = kVK_Shift,
64 | K_RIGHTSHIFT = kVK_RightShift,
65 | K_CAPSLOCK = kVK_CapsLock,
66 | K_SPACE = kVK_Space,
67 | K_INSERT = K_NOT_A_KEY,
68 | K_PRINTSCREEN = K_NOT_A_KEY,
69 | K_MENU = K_NOT_A_KEY,
70 |
71 | K_NUMPAD_LOCK = K_NOT_A_KEY,
72 | K_NUMPAD_0 = kVK_ANSI_Keypad0,
73 | K_NUMPAD_1 = kVK_ANSI_Keypad1,
74 | K_NUMPAD_2 = kVK_ANSI_Keypad2,
75 | K_NUMPAD_3 = kVK_ANSI_Keypad3,
76 | K_NUMPAD_4 = kVK_ANSI_Keypad4,
77 | K_NUMPAD_5 = kVK_ANSI_Keypad5,
78 | K_NUMPAD_6 = kVK_ANSI_Keypad6,
79 | K_NUMPAD_7 = kVK_ANSI_Keypad7,
80 | K_NUMPAD_8 = kVK_ANSI_Keypad8,
81 | K_NUMPAD_9 = kVK_ANSI_Keypad9,
82 | K_NUMPAD_PLUS = kVK_ANSI_KeypadPlus,
83 | K_NUMPAD_MINUS = kVK_ANSI_KeypadMinus,
84 | K_NUMPAD_MULTIPLY = kVK_ANSI_KeypadMultiply,
85 | K_NUMPAD_DIVIDE = kVK_ANSI_KeypadDivide,
86 | K_NUMPAD_DECIMAL = kVK_ANSI_KeypadDecimal,
87 |
88 | K_AUDIO_VOLUME_MUTE = 1007,
89 | K_AUDIO_VOLUME_DOWN = 1001,
90 | K_AUDIO_VOLUME_UP = 1000,
91 | K_AUDIO_PLAY = 1016,
92 | K_AUDIO_STOP = K_NOT_A_KEY,
93 | K_AUDIO_PAUSE = 1016,
94 | K_AUDIO_PREV = 1018,
95 | K_AUDIO_NEXT = 1017,
96 | K_AUDIO_REWIND = K_NOT_A_KEY,
97 | K_AUDIO_FORWARD = K_NOT_A_KEY,
98 | K_AUDIO_REPEAT = K_NOT_A_KEY,
99 | K_AUDIO_RANDOM = K_NOT_A_KEY,
100 |
101 | K_LIGHTS_MON_UP = 1002,
102 | K_LIGHTS_MON_DOWN = 1003,
103 | K_LIGHTS_KBD_TOGGLE = 1023,
104 | K_LIGHTS_KBD_UP = 1021,
105 | K_LIGHTS_KBD_DOWN = 1022
106 | };
107 |
108 | typedef CGKeyCode MMKeyCode;
109 |
110 | #elif defined(USE_X11)
111 |
112 | #include
113 | #include
114 |
115 | enum _MMKeyCode {
116 | K_NOT_A_KEY = 9999,
117 | K_BACKSPACE = XK_BackSpace,
118 | K_DELETE = XK_Delete,
119 | K_RETURN = XK_Return,
120 | K_TAB = XK_Tab,
121 | K_ESCAPE = XK_Escape,
122 | K_UP = XK_Up,
123 | K_DOWN = XK_Down,
124 | K_RIGHT = XK_Right,
125 | K_LEFT = XK_Left,
126 | K_HOME = XK_Home,
127 | K_END = XK_End,
128 | K_PAGEUP = XK_Page_Up,
129 | K_PAGEDOWN = XK_Page_Down,
130 | K_F1 = XK_F1,
131 | K_F2 = XK_F2,
132 | K_F3 = XK_F3,
133 | K_F4 = XK_F4,
134 | K_F5 = XK_F5,
135 | K_F6 = XK_F6,
136 | K_F7 = XK_F7,
137 | K_F8 = XK_F8,
138 | K_F9 = XK_F9,
139 | K_F10 = XK_F10,
140 | K_F11 = XK_F11,
141 | K_F12 = XK_F12,
142 | K_F13 = XK_F13,
143 | K_F14 = XK_F14,
144 | K_F15 = XK_F15,
145 | K_F16 = XK_F16,
146 | K_F17 = XK_F17,
147 | K_F18 = XK_F18,
148 | K_F19 = XK_F19,
149 | K_F20 = XK_F20,
150 | K_F21 = XK_F21,
151 | K_F22 = XK_F22,
152 | K_F23 = XK_F23,
153 | K_F24 = XK_F24,
154 | K_META = XK_Super_L,
155 | K_ALT = XK_Alt_L,
156 | K_RIGHT_ALT = XK_Alt_R,
157 | K_CONTROL = XK_Control_L,
158 | K_LEFT_CONTROL = XK_Control_L,
159 | K_RIGHT_CONTROL = XK_Control_R,
160 | K_SHIFT = XK_Shift_L,
161 | K_RIGHTSHIFT = XK_Shift_R,
162 | K_CAPSLOCK = XK_Shift_Lock,
163 | K_SPACE = XK_space,
164 | K_INSERT = XK_Insert,
165 | K_PRINTSCREEN = XK_Print,
166 | K_MENU = K_NOT_A_KEY,
167 |
168 | K_NUMPAD_LOCK = K_NOT_A_KEY,
169 | K_NUMPAD_0 = K_NOT_A_KEY,
170 | K_NUMPAD_1 = K_NOT_A_KEY,
171 | K_NUMPAD_2 = K_NOT_A_KEY,
172 | K_NUMPAD_3 = K_NOT_A_KEY,
173 | K_NUMPAD_4 = K_NOT_A_KEY,
174 | K_NUMPAD_5 = K_NOT_A_KEY,
175 | K_NUMPAD_6 = K_NOT_A_KEY,
176 | K_NUMPAD_7 = K_NOT_A_KEY,
177 | K_NUMPAD_8 = K_NOT_A_KEY,
178 | K_NUMPAD_9 = K_NOT_A_KEY,
179 | K_NUMPAD_PLUS = K_NOT_A_KEY,
180 | K_NUMPAD_MINUS = K_NOT_A_KEY,
181 | K_NUMPAD_MULTIPLY = K_NOT_A_KEY,
182 | K_NUMPAD_DIVIDE = K_NOT_A_KEY,
183 | K_NUMPAD_DECIMAL = K_NOT_A_KEY,
184 |
185 | K_AUDIO_VOLUME_MUTE = XF86XK_AudioMute,
186 | K_AUDIO_VOLUME_DOWN = XF86XK_AudioLowerVolume,
187 | K_AUDIO_VOLUME_UP = XF86XK_AudioRaiseVolume,
188 | K_AUDIO_PLAY = XF86XK_AudioPlay,
189 | K_AUDIO_STOP = XF86XK_AudioStop,
190 | K_AUDIO_PAUSE = XF86XK_AudioPause,
191 | K_AUDIO_PREV = XF86XK_AudioPrev,
192 | K_AUDIO_NEXT = XF86XK_AudioNext,
193 | K_AUDIO_REWIND = XF86XK_AudioRewind,
194 | K_AUDIO_FORWARD = XF86XK_AudioForward,
195 | K_AUDIO_REPEAT = XF86XK_AudioRepeat,
196 | K_AUDIO_RANDOM = XF86XK_AudioRandomPlay,
197 |
198 | K_LIGHTS_MON_UP = XF86XK_MonBrightnessUp,
199 | K_LIGHTS_MON_DOWN = XF86XK_MonBrightnessDown,
200 | K_LIGHTS_KBD_TOGGLE = XF86XK_KbdLightOnOff,
201 | K_LIGHTS_KBD_UP = XF86XK_KbdBrightnessUp,
202 | K_LIGHTS_KBD_DOWN = XF86XK_KbdBrightnessDown
203 | };
204 |
205 | typedef KeySym MMKeyCode;
206 |
207 | #elif defined(IS_WINDOWS)
208 |
209 | enum _MMKeyCode {
210 | K_NOT_A_KEY = 9999,
211 | K_BACKSPACE = VK_BACK,
212 | K_DELETE = VK_DELETE,
213 | K_RETURN = VK_RETURN,
214 | K_TAB = VK_TAB,
215 | K_ESCAPE = VK_ESCAPE,
216 | K_UP = VK_UP,
217 | K_DOWN = VK_DOWN,
218 | K_RIGHT = VK_RIGHT,
219 | K_LEFT = VK_LEFT,
220 | K_HOME = VK_HOME,
221 | K_END = VK_END,
222 | K_PAGEUP = VK_PRIOR,
223 | K_PAGEDOWN = VK_NEXT,
224 | K_F1 = VK_F1,
225 | K_F2 = VK_F2,
226 | K_F3 = VK_F3,
227 | K_F4 = VK_F4,
228 | K_F5 = VK_F5,
229 | K_F6 = VK_F6,
230 | K_F7 = VK_F7,
231 | K_F8 = VK_F8,
232 | K_F9 = VK_F9,
233 | K_F10 = VK_F10,
234 | K_F11 = VK_F11,
235 | K_F12 = VK_F12,
236 | K_F13 = VK_F13,
237 | K_F14 = VK_F14,
238 | K_F15 = VK_F15,
239 | K_F16 = VK_F16,
240 | K_F17 = VK_F17,
241 | K_F18 = VK_F18,
242 | K_F19 = VK_F19,
243 | K_F20 = VK_F20,
244 | K_F21 = VK_F21,
245 | K_F22 = VK_F22,
246 | K_F23 = VK_F23,
247 | K_F24 = VK_F24,
248 | K_META = VK_LWIN,
249 | K_CONTROL = VK_CONTROL,
250 | K_LEFT_CONTROL = VK_LCONTROL,
251 | K_RIGHT_CONTROL = VK_RCONTROL,
252 | K_SHIFT = VK_SHIFT,
253 | K_RIGHTSHIFT = VK_RSHIFT,
254 | K_ALT = VK_MENU,
255 | K_RIGHT_ALT = VK_MENU,
256 | K_CAPSLOCK = VK_CAPITAL,
257 | K_SPACE = VK_SPACE,
258 | K_PRINTSCREEN = VK_SNAPSHOT,
259 | K_INSERT = VK_INSERT,
260 | K_MENU = VK_APPS,
261 |
262 | K_NUMPAD_LOCK = VK_NUMLOCK,
263 | K_NUMPAD_0 = VK_NUMPAD0,
264 | K_NUMPAD_1 = VK_NUMPAD1,
265 | K_NUMPAD_2 = VK_NUMPAD2,
266 | K_NUMPAD_3 = VK_NUMPAD3,
267 | K_NUMPAD_4 = VK_NUMPAD4,
268 | K_NUMPAD_5 = VK_NUMPAD5,
269 | K_NUMPAD_6 = VK_NUMPAD6,
270 | K_NUMPAD_7 = VK_NUMPAD7,
271 | K_NUMPAD_8 = VK_NUMPAD8,
272 | K_NUMPAD_9 = VK_NUMPAD9,
273 | K_NUMPAD_PLUS = VK_ADD,
274 | K_NUMPAD_MINUS = VK_SUBTRACT,
275 | K_NUMPAD_MULTIPLY = VK_MULTIPLY,
276 | K_NUMPAD_DIVIDE = VK_DIVIDE,
277 | K_NUMPAD_DECIMAL = VK_DECIMAL,
278 |
279 | K_AUDIO_VOLUME_MUTE = VK_VOLUME_MUTE,
280 | K_AUDIO_VOLUME_DOWN = VK_VOLUME_DOWN,
281 | K_AUDIO_VOLUME_UP = VK_VOLUME_UP,
282 | K_AUDIO_PLAY = VK_MEDIA_PLAY_PAUSE,
283 | K_AUDIO_STOP = VK_MEDIA_STOP,
284 | K_AUDIO_PAUSE = VK_MEDIA_PLAY_PAUSE,
285 | K_AUDIO_PREV = VK_MEDIA_PREV_TRACK,
286 | K_AUDIO_NEXT = VK_MEDIA_NEXT_TRACK,
287 | K_AUDIO_REWIND = K_NOT_A_KEY,
288 | K_AUDIO_FORWARD = K_NOT_A_KEY,
289 | K_AUDIO_REPEAT = K_NOT_A_KEY,
290 | K_AUDIO_RANDOM = K_NOT_A_KEY,
291 |
292 | K_LIGHTS_MON_UP = K_NOT_A_KEY,
293 | K_LIGHTS_MON_DOWN = K_NOT_A_KEY,
294 | K_LIGHTS_KBD_TOGGLE = K_NOT_A_KEY,
295 | K_LIGHTS_KBD_UP = K_NOT_A_KEY,
296 | K_LIGHTS_KBD_DOWN = K_NOT_A_KEY
297 | };
298 |
299 | typedef int MMKeyCode;
300 |
301 | #endif
302 |
303 | /* Returns the keyCode corresponding to the current keyboard layout for the
304 | * given ASCII character. */
305 | MMKeyCode keyCodeForChar(const char c);
306 |
307 | #endif /* KEYCODE_H */
308 |
309 | #ifdef __cplusplus
310 | }
311 | #endif
312 |
--------------------------------------------------------------------------------
/src/keypress.c:
--------------------------------------------------------------------------------
1 | #include "keypress.h"
2 | #include "deadbeef_rand.h"
3 | #include "microsleep.h"
4 |
5 | #include /* For isupper() */
6 |
7 | #if defined(IS_MACOSX)
8 | #include
9 | #import
10 | #import
11 | #elif defined(USE_X11)
12 | #include
13 | #include "xdisplay.h"
14 | #endif
15 |
16 | /* Convenience wrappers around ugly APIs. */
17 | #if defined(IS_WINDOWS)
18 | #define WIN32_KEY_EVENT_WAIT(key, flags) \
19 | (win32KeyEvent(key, flags))
20 | #elif defined(USE_X11)
21 | #define X_KEY_EVENT(display, key, is_press) \
22 | (XTestFakeKeyEvent(display, \
23 | XKeysymToKeycode(display, key), \
24 | is_press, CurrentTime), \
25 | XSync(display, false))
26 | #define X_KEY_EVENT_WAIT(display, key, is_press) \
27 | (X_KEY_EVENT(display, key, is_press))
28 | #endif
29 |
30 | #if defined(IS_MACOSX)
31 | static io_connect_t _getAuxiliaryKeyDriver(void)
32 | {
33 | static mach_port_t sEventDrvrRef = 0;
34 | mach_port_t masterPort, service, iter;
35 | kern_return_t kr;
36 |
37 | if (!sEventDrvrRef) {
38 | kr = IOMasterPort( bootstrap_port, &masterPort );
39 | assert(KERN_SUCCESS == kr);
40 | kr = IOServiceGetMatchingServices(masterPort, IOServiceMatching( kIOHIDSystemClass), &iter );
41 | assert(KERN_SUCCESS == kr);
42 | service = IOIteratorNext( iter );
43 | assert(service);
44 | kr = IOServiceOpen(service, mach_task_self(), kIOHIDParamConnectType, &sEventDrvrRef );
45 | assert(KERN_SUCCESS == kr);
46 | IOObjectRelease(service);
47 | IOObjectRelease(iter);
48 | }
49 | return sEventDrvrRef;
50 | }
51 | #endif
52 |
53 | #if defined(IS_WINDOWS)
54 | void win32KeyEvent(int key, MMKeyFlags flags)
55 | {
56 | int scan = MapVirtualKey(key & 0xff, MAPVK_VK_TO_VSC);
57 |
58 | /* Set the scan code for extended keys */
59 | switch (key)
60 | {
61 | case VK_RCONTROL:
62 | case VK_SNAPSHOT: /* Print Screen */
63 | case VK_RMENU: /* Right Alt / Alt Gr */
64 | case VK_PAUSE: /* Pause / Break */
65 | case VK_HOME:
66 | case VK_UP:
67 | case VK_PRIOR: /* Page up */
68 | case VK_LEFT:
69 | case VK_RIGHT:
70 | case VK_END:
71 | case VK_DOWN:
72 | case VK_NEXT: /* 'Page Down' */
73 | case VK_INSERT:
74 | case VK_DELETE:
75 | case VK_LWIN:
76 | case VK_RWIN:
77 | case VK_APPS: /* Application */
78 | case VK_VOLUME_MUTE:
79 | case VK_VOLUME_DOWN:
80 | case VK_VOLUME_UP:
81 | case VK_MEDIA_NEXT_TRACK:
82 | case VK_MEDIA_PREV_TRACK:
83 | case VK_MEDIA_STOP:
84 | case VK_MEDIA_PLAY_PAUSE:
85 | case VK_BROWSER_BACK:
86 | case VK_BROWSER_FORWARD:
87 | case VK_BROWSER_REFRESH:
88 | case VK_BROWSER_STOP:
89 | case VK_BROWSER_SEARCH:
90 | case VK_BROWSER_FAVORITES:
91 | case VK_BROWSER_HOME:
92 | case VK_LAUNCH_MAIL:
93 | {
94 | flags |= KEYEVENTF_EXTENDEDKEY;
95 | break;
96 | }
97 | }
98 |
99 | /* Set the scan code for keyup */
100 | if ( flags & KEYEVENTF_KEYUP ) {
101 | scan |= 0x80;
102 | }
103 |
104 | flags |= KEYEVENTF_SCANCODE;
105 |
106 | INPUT keyboardInput;
107 | keyboardInput.type = INPUT_KEYBOARD;
108 | keyboardInput.ki.wVk = 0;
109 | keyboardInput.ki.wScan = scan;
110 | keyboardInput.ki.dwFlags = flags;
111 | keyboardInput.ki.time = 0;
112 | keyboardInput.ki.dwExtraInfo = 0;
113 | SendInput(1, &keyboardInput, sizeof(keyboardInput));
114 | }
115 | #endif
116 |
117 | void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags)
118 | {
119 | #if defined(IS_MACOSX)
120 | /* The media keys all have 1000 added to them to help us detect them. */
121 | if (code >= 1000) {
122 | code = code - 1000; /* Get the real keycode. */
123 | NXEventData event;
124 | kern_return_t kr;
125 | IOGPoint loc = { 0, 0 };
126 | UInt32 evtInfo = code << 16 | (down?NX_KEYDOWN:NX_KEYUP) << 8;
127 | bzero(&event, sizeof(NXEventData));
128 | event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
129 | event.compound.misc.L[0] = evtInfo;
130 | kr = IOHIDPostEvent( _getAuxiliaryKeyDriver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
131 | assert( KERN_SUCCESS == kr );
132 | } else {
133 | CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL,
134 | (CGKeyCode)code, down);
135 | assert(keyEvent != NULL);
136 |
137 | CGEventSetType(keyEvent, down ? kCGEventKeyDown : kCGEventKeyUp);
138 | CGEventSetFlags(keyEvent, flags);
139 | CGEventPost(kCGSessionEventTap, keyEvent);
140 | CFRelease(keyEvent);
141 | }
142 | #elif defined(IS_WINDOWS)
143 | const DWORD dwFlags = down ? 0 : KEYEVENTF_KEYUP;
144 |
145 | if (down) {
146 | /* Parse modifier keys. */
147 | if (flags & MOD_META) WIN32_KEY_EVENT_WAIT(K_META, dwFlags);
148 | if (flags & MOD_ALT) WIN32_KEY_EVENT_WAIT(K_ALT, dwFlags);
149 | if (flags & MOD_CONTROL) WIN32_KEY_EVENT_WAIT(K_CONTROL, dwFlags);
150 | if (flags & MOD_SHIFT) WIN32_KEY_EVENT_WAIT(K_SHIFT, dwFlags);
151 |
152 | WIN32_KEY_EVENT_WAIT(code, dwFlags);
153 | } else {
154 | /* Reverse order for key up */
155 | WIN32_KEY_EVENT_WAIT(code, dwFlags);
156 |
157 | /* Parse modifier keys. */
158 | if (flags & MOD_META) win32KeyEvent(K_META, dwFlags);
159 | if (flags & MOD_ALT) win32KeyEvent(K_ALT, dwFlags);
160 | if (flags & MOD_CONTROL) win32KeyEvent(K_CONTROL, dwFlags);
161 | if (flags & MOD_SHIFT) win32KeyEvent(K_SHIFT, dwFlags);
162 | }
163 | #elif defined(USE_X11)
164 | Display *display = XGetMainDisplay();
165 | const Bool is_press = down ? True : False; /* Just to be safe. */
166 |
167 | if (down) {
168 | /* Parse modifier keys. */
169 | if (flags & MOD_META) X_KEY_EVENT_WAIT(display, K_META, is_press);
170 | if (flags & MOD_ALT) X_KEY_EVENT_WAIT(display, K_ALT, is_press);
171 | if (flags & MOD_CONTROL) X_KEY_EVENT_WAIT(display, K_CONTROL, is_press);
172 | if (flags & MOD_SHIFT) X_KEY_EVENT_WAIT(display, K_SHIFT, is_press);
173 |
174 | X_KEY_EVENT_WAIT(display, code, is_press);
175 | } else {
176 | /* Reverse order for key up */
177 | X_KEY_EVENT_WAIT(display, code, is_press);
178 |
179 | /* Parse modifier keys. */
180 | if (flags & MOD_META) X_KEY_EVENT(display, K_META, is_press);
181 | if (flags & MOD_ALT) X_KEY_EVENT(display, K_ALT, is_press);
182 | if (flags & MOD_CONTROL) X_KEY_EVENT(display, K_CONTROL, is_press);
183 | if (flags & MOD_SHIFT) X_KEY_EVENT(display, K_SHIFT, is_press);
184 | }
185 | #endif
186 | }
187 |
188 | void tapKeyCode(MMKeyCode code, MMKeyFlags flags)
189 | {
190 | toggleKeyCode(code, true, flags);
191 | toggleKeyCode(code, false, flags);
192 | }
193 |
194 | void toggleKey(char c, const bool down, MMKeyFlags flags)
195 | {
196 | MMKeyCode keyCode = keyCodeForChar(c);
197 |
198 | //Prevent unused variable warning for Mac and Linux.
199 | #if defined(IS_WINDOWS)
200 | int modifiers;
201 | #endif
202 |
203 | if (isupper(c) && !(flags & MOD_SHIFT)) {
204 | flags |= MOD_SHIFT; /* Not sure if this is safe for all layouts. */
205 | }
206 |
207 | #if defined(IS_WINDOWS)
208 | modifiers = keyCode >> 8; // Pull out modifers.
209 | if ((modifiers & 1) != 0) flags |= MOD_SHIFT; // Uptdate flags from keycode modifiers.
210 | if ((modifiers & 2) != 0) flags |= MOD_CONTROL;
211 | if ((modifiers & 4) != 0) flags |= MOD_ALT;
212 | keyCode = keyCode & 0xff; // Mask out modifiers.
213 | #endif
214 | toggleKeyCode(keyCode, down, flags);
215 | }
216 |
217 | void tapKey(char c, MMKeyFlags flags)
218 | {
219 | toggleKey(c, true, flags);
220 | toggleKey(c, false, flags);
221 | }
222 |
223 | #if defined(IS_MACOSX)
224 | void toggleUnicode(UniChar ch, const bool down)
225 | {
226 | /* This function relies on the convenient
227 | * CGEventKeyboardSetUnicodeString(), which allows us to not have to
228 | * convert characters to a keycode, but does not support adding modifier
229 | * flags. It is therefore only used in typeStringDelayed()
230 | * -- if you need modifier keys, use the above functions instead. */
231 | CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL, 0, down);
232 | if (keyEvent == NULL) {
233 | fputs("Could not create keyboard event.\n", stderr);
234 | return;
235 | }
236 |
237 | if (ch > 0xFFFF) {
238 | // encode to utf-16 if necessary
239 | UniChar surrogates[2] = {
240 | 0xD800 + ((ch - 0x10000) >> 10),
241 | 0xDC00 + (ch & 0x3FF)
242 | };
243 |
244 | CGEventKeyboardSetUnicodeString(keyEvent, 2, (UniChar*) &surrogates);
245 | } else {
246 | CGEventKeyboardSetUnicodeString(keyEvent, 1, (UniChar*) &ch);
247 | }
248 |
249 | CGEventPost(kCGSessionEventTap, keyEvent);
250 | CFRelease(keyEvent);
251 | }
252 | #elif defined(USE_X11)
253 | #define toggleUniKey(c, down) toggleKey(c, down, MOD_NONE)
254 | #endif
255 |
256 | void unicodeTap(const unsigned value)
257 | {
258 | #if defined(USE_X11)
259 | char ch = (char)value;
260 |
261 | toggleUniKey(ch, true);
262 | toggleUniKey(ch, false);
263 | #elif defined(IS_MACOSX)
264 | UniChar ch = (UniChar)value; // Convert to unsigned char
265 |
266 | toggleUnicode(ch, true);
267 | toggleUnicode(ch, false);
268 | #elif defined(IS_WINDOWS)
269 | INPUT ip;
270 |
271 | // Set up a generic keyboard event.
272 | ip.type = INPUT_KEYBOARD;
273 | ip.ki.wVk = 0; // Virtual-key code
274 | ip.ki.wScan = value; // Hardware scan code for key
275 | ip.ki.time = 0; // System will provide its own time stamp.
276 | ip.ki.dwExtraInfo = 0; // No extra info. Use the GetMessageExtraInfo function to obtain this information if needed.
277 | ip.ki.dwFlags = KEYEVENTF_UNICODE; // KEYEVENTF_KEYUP for key release.
278 |
279 | SendInput(1, &ip, sizeof(INPUT));
280 | #endif
281 | }
282 |
283 | void typeStringDelayed(const char *str, const unsigned cpm)
284 | {
285 | unsigned long n;
286 | unsigned short c;
287 | unsigned short c1;
288 | unsigned short c2;
289 | unsigned short c3;
290 |
291 | /* Characters per second */
292 | const double cps = (double)cpm / 60.0;
293 |
294 | /* Average milli-seconds per character */
295 | const double mspc = (cps == 0.0) ? 0.0 : 1000.0 / cps;
296 |
297 | while (*str != '\0') {
298 | c = *str++;
299 |
300 | // warning, the following utf8 decoder
301 | // doesn't perform validation
302 | if (c <= 0x7F) {
303 | // 0xxxxxxx one byte
304 | n = c;
305 | } else if ((c & 0xE0) == 0xC0) {
306 | // 110xxxxx two bytes
307 | c1 = (*str++) & 0x3F;
308 | n = ((c & 0x1F) << 6) | c1;
309 | } else if ((c & 0xF0) == 0xE0) {
310 | // 1110xxxx three bytes
311 | c1 = (*str++) & 0x3F;
312 | c2 = (*str++) & 0x3F;
313 | n = ((c & 0x0F) << 12) | (c1 << 6) | c2;
314 | } else if ((c & 0xF8) == 0xF0) {
315 | // 11110xxx four bytes
316 | c1 = (*str++) & 0x3F;
317 | c2 = (*str++) & 0x3F;
318 | c3 = (*str++) & 0x3F;
319 | n = ((c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
320 | }
321 |
322 | unicodeTap(n);
323 |
324 | if (mspc > 0) {
325 | microsleep(mspc);
326 | }
327 | }
328 | }
329 |
--------------------------------------------------------------------------------
/src/keypress.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef KEYPRESS_H
3 | #define KEYPRESS_H
4 |
5 | #include "os.h"
6 | #include "keycode.h"
7 |
8 | #if defined(_MSC_VER)
9 | #include "ms_stdbool.h"
10 | #else
11 | #include
12 | #endif
13 | #ifdef __cplusplus
14 | extern "C"
15 | {
16 | #endif
17 | #if defined(IS_MACOSX)
18 |
19 | typedef enum {
20 | MOD_NONE = 0,
21 | MOD_META = kCGEventFlagMaskCommand,
22 | MOD_ALT = kCGEventFlagMaskAlternate,
23 | MOD_CONTROL = kCGEventFlagMaskControl,
24 | MOD_SHIFT = kCGEventFlagMaskShift
25 | } MMKeyFlags;
26 |
27 | #elif defined(USE_X11)
28 |
29 | enum _MMKeyFlags {
30 | MOD_NONE = 0,
31 | MOD_META = Mod4Mask,
32 | MOD_ALT = Mod1Mask,
33 | MOD_CONTROL = ControlMask,
34 | MOD_SHIFT = ShiftMask
35 | };
36 |
37 | typedef unsigned int MMKeyFlags;
38 |
39 | #elif defined(IS_WINDOWS)
40 |
41 | enum _MMKeyFlags {
42 | MOD_NONE = 0,
43 | /* These are already defined by the Win32 API */
44 | /* MOD_ALT = 0,
45 | MOD_CONTROL = 0,
46 | MOD_SHIFT = 0, */
47 | MOD_META = MOD_WIN
48 | };
49 |
50 | typedef unsigned int MMKeyFlags;
51 |
52 | #endif
53 |
54 | #if defined(IS_WINDOWS)
55 | /* Send win32 key event for given key. */
56 | void win32KeyEvent(int key, MMKeyFlags flags);
57 | #endif
58 |
59 | /* Toggles the given key down or up. */
60 | void toggleKeyCode(MMKeyCode code, const bool down, MMKeyFlags flags);
61 |
62 | /* Toggles the key down and then up. */
63 | void tapKeyCode(MMKeyCode code, MMKeyFlags flags);
64 |
65 | /* Toggles the key corresponding to the given UTF character up or down. */
66 | void toggleKey(char c, const bool down, MMKeyFlags flags);
67 | void tapKey(char c, MMKeyFlags flags);
68 |
69 | /* Sends a Unicode character without modifiers. */
70 | void unicodeTap(const unsigned value);
71 |
72 | /* Macro to convert WPM to CPM integers.
73 | * (the average English word length is 5.1 characters.) */
74 | #define WPM_TO_CPM(WPM) (unsigned)(5.1 * WPM)
75 |
76 | /* Sends a UTF-8 string without modifiers and with partially random delays between each letter.
77 | * Note that deadbeef_srand() must be called before this function if you actually want
78 | * randomness. */
79 | void typeStringDelayed(const char *str, const unsigned cpm);
80 |
81 | #ifdef __cplusplus
82 | }
83 | #endif
84 |
85 | #endif /* KEYPRESS_H */
86 |
--------------------------------------------------------------------------------
/src/microsleep.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef MICROSLEEP_H
3 | #define MICROSLEEP_H
4 |
5 | #include "os.h"
6 | #include "inline_keywords.h"
7 |
8 | #if !defined(IS_WINDOWS)
9 | /* Make sure nanosleep gets defined even when using C89. */
10 | #if !defined(__USE_POSIX199309) || !__USE_POSIX199309
11 | #define __USE_POSIX199309 1
12 | #endif
13 |
14 | #include /* For nanosleep() */
15 | #endif
16 |
17 | /*
18 | * A more widely supported alternative to usleep(), based on Sleep() in Windows
19 | * and nanosleep() everywhere else.
20 | *
21 | * Pauses execution for the given amount of milliseconds.
22 | */
23 | H_INLINE void microsleep(double milliseconds)
24 | {
25 | #if defined(IS_WINDOWS)
26 | Sleep((DWORD)milliseconds); /* (Unfortunately truncated to a 32-bit integer.) */
27 | #else
28 | /* Technically, nanosleep() is not an ANSI function, but it is the most
29 | * supported precise sleeping function I can find.
30 | *
31 | * If it is really necessary, it may be possible to emulate this with some
32 | * hack using select() in the future if we really have to. */
33 | struct timespec sleepytime;
34 | sleepytime.tv_sec = milliseconds / 1000;
35 | sleepytime.tv_nsec = (milliseconds - (sleepytime.tv_sec * 1000)) * 1000000;
36 | nanosleep(&sleepytime, NULL);
37 | #endif
38 | }
39 |
40 | #endif /* MICROSLEEP_H */
41 |
--------------------------------------------------------------------------------
/src/mouse.c:
--------------------------------------------------------------------------------
1 | #include "mouse.h"
2 | #include "screen.h"
3 | #include "deadbeef_rand.h"
4 | #include "microsleep.h"
5 |
6 | #include /* For floor() */
7 |
8 | #if defined(IS_MACOSX)
9 | #include
10 | #elif defined(USE_X11)
11 | #include
12 | #include
13 | #include
14 | #include "xdisplay.h"
15 | #endif
16 |
17 | #if !defined(M_SQRT2)
18 | #define M_SQRT2 1.4142135623730950488016887 /* Fix for MSVC. */
19 | #endif
20 |
21 | /* Some convenience macros for converting our enums to the system API types. */
22 | #if defined(IS_MACOSX)
23 |
24 | #define MMMouseToCGEventType(down, button) \
25 | (down ? MMMouseDownToCGEventType(button) : MMMouseUpToCGEventType(button))
26 |
27 | #define MMMouseDownToCGEventType(button) \
28 | ((button) == (LEFT_BUTTON) ? kCGEventLeftMouseDown \
29 | : ((button) == RIGHT_BUTTON ? kCGEventRightMouseDown \
30 | : kCGEventOtherMouseDown))
31 |
32 | #define MMMouseUpToCGEventType(button) \
33 | ((button) == LEFT_BUTTON ? kCGEventLeftMouseUp \
34 | : ((button) == RIGHT_BUTTON ? kCGEventRightMouseUp \
35 | : kCGEventOtherMouseUp))
36 |
37 | #define MMMouseDragToCGEventType(button) \
38 | ((button) == LEFT_BUTTON ? kCGEventLeftMouseDragged \
39 | : ((button) == RIGHT_BUTTON ? kCGEventRightMouseDragged \
40 | : kCGEventOtherMouseDragged))
41 |
42 | #elif defined(IS_WINDOWS)
43 |
44 | // The width of the virtual screen, in pixels.
45 | static int vscreenWidth = -1; // not initialized
46 |
47 | // The height of the virtual screen, in pixels.
48 | static int vscreenHeight = -1; // not initialized
49 |
50 | // The coordinates for the left side of the virtual screen.
51 | static int vscreenMinX = 0;
52 |
53 | // The coordinates for the top of the virtual screen.
54 | static int vscreenMinY = 0;
55 |
56 | #define MMMouseToMEventF(down, button) \
57 | (down ? MMMouseDownToMEventF(button) : MMMouseUpToMEventF(button))
58 |
59 | #define MMMouseUpToMEventF(button) \
60 | ((button) == LEFT_BUTTON ? MOUSEEVENTF_LEFTUP \
61 | : ((button) == RIGHT_BUTTON ? MOUSEEVENTF_RIGHTUP \
62 | : MOUSEEVENTF_MIDDLEUP))
63 |
64 | #define MMMouseDownToMEventF(button) \
65 | ((button) == LEFT_BUTTON ? MOUSEEVENTF_LEFTDOWN \
66 | : ((button) == RIGHT_BUTTON ? MOUSEEVENTF_RIGHTDOWN \
67 | : MOUSEEVENTF_MIDDLEDOWN))
68 |
69 | #endif
70 |
71 | #if defined(IS_MACOSX)
72 | /**
73 | * Calculate the delta for a mouse move and add them to the event.
74 | * @param event The mouse move event (by ref).
75 | * @param point The new mouse x and y.
76 | */
77 | void calculateDeltas(CGEventRef *event, MMSignedPoint point)
78 | {
79 | /**
80 | * The next few lines are a workaround for games not detecting mouse moves.
81 | * See this issue for more information:
82 | * https://github.com/octalmage/robotjs/issues/159
83 | */
84 | CGEventRef get = CGEventCreate(NULL);
85 | CGPoint mouse = CGEventGetLocation(get);
86 |
87 | // Calculate the deltas.
88 | int64_t deltaX = point.x - mouse.x;
89 | int64_t deltaY = point.y - mouse.y;
90 |
91 | CGEventSetIntegerValueField(*event, kCGMouseEventDeltaX, deltaX);
92 | CGEventSetIntegerValueField(*event, kCGMouseEventDeltaY, deltaY);
93 |
94 | CFRelease(get);
95 | }
96 | #endif
97 |
98 | void updateScreenMetrics()
99 | {
100 | #if defined(IS_WINDOWS)
101 | vscreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
102 | vscreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
103 | vscreenMinX = GetSystemMetrics(SM_XVIRTUALSCREEN);
104 | vscreenMinY = GetSystemMetrics(SM_YVIRTUALSCREEN);
105 | #endif
106 | }
107 | /**
108 | * Move the mouse to a specific point.
109 | * @param point The coordinates to move the mouse to (x, y).
110 | */
111 | void moveMouse(MMSignedPoint point)
112 | {
113 | #if defined(IS_MACOSX)
114 | CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved,
115 | CGPointFromMMSignedPoint(point),
116 | kCGMouseButtonLeft);
117 |
118 | calculateDeltas(&move, point);
119 |
120 | CGEventPost(kCGSessionEventTap, move);
121 | CFRelease(move);
122 | #elif defined(USE_X11)
123 | Display *display = XGetMainDisplay();
124 | XWarpPointer(display, None, DefaultRootWindow(display),
125 | 0, 0, 0, 0, point.x, point.y);
126 | XSync(display, false);
127 | #elif defined(IS_WINDOWS)
128 |
129 | if(vscreenWidth<0 || vscreenHeight<0)
130 | updateScreenMetrics();
131 |
132 | //Mouse motion is now done using SendInput with MOUSEINPUT. We use Absolute mouse positioning
133 | #define MOUSE_COORD_TO_ABS(coord, width_or_height) ((65536 * (coord) / width_or_height) + ((coord) < 0 ? -1 : 1))
134 |
135 | size_t x = MOUSE_COORD_TO_ABS(point.x-vscreenMinX, vscreenWidth);
136 | size_t y = MOUSE_COORD_TO_ABS(point.y-vscreenMinY, vscreenHeight);
137 |
138 | INPUT mouseInput = {0};
139 | mouseInput.type = INPUT_MOUSE;
140 | mouseInput.mi.dx = x;
141 | mouseInput.mi.dy = y;
142 | mouseInput.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_VIRTUALDESK;
143 | mouseInput.mi.time = 0; //System will provide the timestamp
144 |
145 | SendInput(1, &mouseInput, sizeof(mouseInput));
146 | #endif
147 | }
148 |
149 | void dragMouse(MMSignedPoint point, const MMMouseButton button)
150 | {
151 | #if defined(IS_MACOSX)
152 | const CGEventType dragType = MMMouseDragToCGEventType(button);
153 | CGEventRef drag = CGEventCreateMouseEvent(NULL, dragType,
154 | CGPointFromMMSignedPoint(point),
155 | (CGMouseButton)button);
156 | calculateDeltas(&drag, point);
157 |
158 | CGEventPost(kCGSessionEventTap, drag);
159 | CFRelease(drag);
160 | #else
161 | moveMouse(point);
162 | #endif
163 | }
164 |
165 | MMPoint getMousePos()
166 | {
167 | #if defined(IS_MACOSX)
168 | CGEventRef event = CGEventCreate(NULL);
169 | CGPoint point = CGEventGetLocation(event);
170 | CFRelease(event);
171 |
172 | return MMPointFromCGPoint(point);
173 | #elif defined(USE_X11)
174 | int x, y; /* This is all we care about. Seriously. */
175 | Window garb1, garb2; /* Why you can't specify NULL as a parameter */
176 | int garb_x, garb_y; /* is beyond me. */
177 | unsigned int more_garbage;
178 |
179 | Display *display = XGetMainDisplay();
180 | XQueryPointer(display, XDefaultRootWindow(display), &garb1, &garb2,
181 | &x, &y, &garb_x, &garb_y, &more_garbage);
182 |
183 | return MMPointMake(x, y);
184 | #elif defined(IS_WINDOWS)
185 | POINT point;
186 | GetCursorPos(&point);
187 |
188 | return MMPointFromPOINT(point);
189 | #endif
190 | }
191 |
192 | /**
193 | * Press down a button, or release it.
194 | * @param down True for down, false for up.
195 | * @param button The button to press down or release.
196 | */
197 | void toggleMouse(bool down, MMMouseButton button)
198 | {
199 | #if defined(IS_MACOSX)
200 | const CGPoint currentPos = CGPointFromMMPoint(getMousePos());
201 | const CGEventType mouseType = MMMouseToCGEventType(down, button);
202 | CGEventRef event = CGEventCreateMouseEvent(NULL,
203 | mouseType,
204 | currentPos,
205 | (CGMouseButton)button);
206 | CGEventPost(kCGSessionEventTap, event);
207 | CFRelease(event);
208 | #elif defined(USE_X11)
209 | Display *display = XGetMainDisplay();
210 | XTestFakeButtonEvent(display, button, down ? True : False, CurrentTime);
211 | XSync(display, false);
212 | #elif defined(IS_WINDOWS)
213 | INPUT mouseInput;
214 | mouseInput.type = INPUT_MOUSE;
215 | mouseInput.mi.dx = 0;
216 | mouseInput.mi.dy = 0;
217 | mouseInput.mi.dwFlags = MMMouseToMEventF(down, button);
218 | mouseInput.mi.time = 0; //System will provide the timestamp
219 | mouseInput.mi.dwExtraInfo = 0;
220 | mouseInput.mi.mouseData = 0;
221 | SendInput(1, &mouseInput, sizeof(mouseInput));
222 | #endif
223 | }
224 |
225 | void clickMouse(MMMouseButton button)
226 | {
227 | toggleMouse(true, button);
228 | toggleMouse(false, button);
229 | }
230 |
231 | /**
232 | * Special function for sending double clicks, needed for Mac OS X.
233 | * @param button Button to click.
234 | */
235 | void doubleClick(MMMouseButton button)
236 | {
237 |
238 | #if defined(IS_MACOSX)
239 |
240 | /* Double click for Mac. */
241 | const CGPoint currentPos = CGPointFromMMPoint(getMousePos());
242 | const CGEventType mouseTypeDown = MMMouseToCGEventType(true, button);
243 | const CGEventType mouseTypeUP = MMMouseToCGEventType(false, button);
244 |
245 | CGEventRef event = CGEventCreateMouseEvent(NULL, mouseTypeDown, currentPos, kCGMouseButtonLeft);
246 |
247 | /* Set event to double click. */
248 | CGEventSetIntegerValueField(event, kCGMouseEventClickState, 2);
249 |
250 | CGEventPost(kCGHIDEventTap, event);
251 |
252 | CGEventSetType(event, mouseTypeUP);
253 | CGEventPost(kCGHIDEventTap, event);
254 |
255 | CFRelease(event);
256 |
257 | #else
258 |
259 | /* Double click for everything else. */
260 | clickMouse(button);
261 | microsleep(200);
262 | clickMouse(button);
263 |
264 | #endif
265 | }
266 |
267 | void scrollMouse(int x, int y)
268 | {
269 | #if defined(IS_WINDOWS)
270 | // Fix for #97 https://github.com/octalmage/robotjs/issues/97,
271 | // C89 needs variables declared on top of functions (mouseScrollInput)
272 | INPUT mouseScrollInputs[2];
273 | #endif
274 |
275 | /* Direction should only be considered based on the scrollDirection. This
276 | * Should not interfere. */
277 |
278 | /* Set up the OS specific solution */
279 | #if defined(__APPLE__)
280 |
281 | CGEventRef event;
282 |
283 | event = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 2, y, x);
284 | CGEventPost(kCGHIDEventTap, event);
285 |
286 | CFRelease(event);
287 |
288 | #elif defined(USE_X11)
289 |
290 | /*
291 | X11 Mouse Button Numbering
292 | 1 = left button
293 | 2 = middle button (pressing the scroll wheel)
294 | 3 = right button
295 | 4 = turn scroll wheel up
296 | 5 = turn scroll wheel down
297 | 6 = push scroll wheel left
298 | 7 = push scroll wheel right
299 | 8 = 4th button (aka browser backward button)
300 | 9 = 5th button (aka browser forward button)
301 | */
302 | int ydir = 4; // Button 4 is up, 5 is down.
303 | int xdir = 6; // Button 6 is left, 7 is right.
304 | Display *display = XGetMainDisplay();
305 |
306 | if (y < 0){
307 | ydir = 5;
308 | }
309 | if (x < 0){
310 | xdir = 7;
311 | }
312 |
313 | int xi;
314 | int yi;
315 | for (xi = 0; xi < abs(x); xi++) {
316 | XTestFakeButtonEvent(display, xdir, 1, CurrentTime);
317 | XTestFakeButtonEvent(display, xdir, 0, CurrentTime);
318 | }
319 | for (yi = 0; yi < abs(y); yi++) {
320 | XTestFakeButtonEvent(display, ydir, 1, CurrentTime);
321 | XTestFakeButtonEvent(display, ydir, 0, CurrentTime);
322 | }
323 |
324 | XSync(display, false);
325 |
326 | #elif defined(IS_WINDOWS)
327 |
328 | // Must send y first, otherwise we get stuck when scrolling on y axis
329 | mouseScrollInputs[0].type = INPUT_MOUSE;
330 | mouseScrollInputs[0].mi.dx = 0;
331 | mouseScrollInputs[0].mi.dy = 0;
332 | mouseScrollInputs[0].mi.dwFlags = MOUSEEVENTF_WHEEL;
333 | mouseScrollInputs[0].mi.time = 0;
334 | mouseScrollInputs[0].mi.dwExtraInfo = 0;
335 | mouseScrollInputs[0].mi.mouseData = y;
336 |
337 | mouseScrollInputs[1].type = INPUT_MOUSE;
338 | mouseScrollInputs[1].mi.dx = 0;
339 | mouseScrollInputs[1].mi.dy = 0;
340 | mouseScrollInputs[1].mi.dwFlags = MOUSEEVENTF_HWHEEL;
341 | mouseScrollInputs[1].mi.time = 0;
342 | mouseScrollInputs[1].mi.dwExtraInfo = 0;
343 | // Flip x to match other platforms.
344 | mouseScrollInputs[1].mi.mouseData = -x;
345 |
346 | SendInput(2, mouseScrollInputs, sizeof(INPUT));
347 | #endif
348 | }
349 |
350 | /*
351 | * A crude, fast hypot() approximation to get around the fact that hypot() is
352 | * not a standard ANSI C function.
353 | *
354 | * It is not particularly accurate but that does not matter for our use case.
355 | *
356 | * Taken from this StackOverflow answer:
357 | * http://stackoverflow.com/questions/3506404/fast-hypotenuse-algorithm-for-embedded-processor#3507882
358 | *
359 | */
360 | static double crude_hypot(double x, double y)
361 | {
362 | double big = fabs(x); /* max(|x|, |y|) */
363 | double small = fabs(y); /* min(|x|, |y|) */
364 |
365 | if (big > small) {
366 | double temp = big;
367 | big = small;
368 | small = temp;
369 | }
370 |
371 | return ((M_SQRT2 - 1.0) * small) + big;
372 | }
373 |
374 | bool smoothlyMoveMouse(MMPoint endPoint,double speed)
375 | {
376 | MMPoint pos = getMousePos();
377 | MMSize screenSize = getMainDisplaySize();
378 | double velo_x = 0.0, velo_y = 0.0;
379 | double distance;
380 |
381 | while ((distance = crude_hypot((double)pos.x - endPoint.x,
382 | (double)pos.y - endPoint.y)) > 1.0) {
383 | double gravity = DEADBEEF_UNIFORM(5.0, 500.0);
384 | double veloDistance;
385 | velo_x += (gravity * ((double)endPoint.x - pos.x)) / distance;
386 | velo_y += (gravity * ((double)endPoint.y - pos.y)) / distance;
387 |
388 | /* Normalize velocity to get a unit vector of length 1. */
389 | veloDistance = crude_hypot(velo_x, velo_y);
390 | velo_x /= veloDistance;
391 | velo_y /= veloDistance;
392 |
393 | pos.x += floor(velo_x + 0.5);
394 | pos.y += floor(velo_y + 0.5);
395 |
396 | /* Make sure we are in the screen boundaries!
397 | * (Strange things will happen if we are not.) */
398 | if (pos.x >= screenSize.width || pos.y >= screenSize.height) {
399 | return false;
400 | }
401 |
402 | moveMouse(MMSignedPointMake((int32_t)pos.x, (int32_t)pos.y));
403 |
404 | /* Wait 1 - (speed) milliseconds. */
405 | microsleep(DEADBEEF_UNIFORM(0.7, speed));
406 | }
407 |
408 | return true;
409 | }
410 |
--------------------------------------------------------------------------------
/src/mouse.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef MOUSE_H
3 | #define MOUSE_H
4 |
5 | #include "os.h"
6 | #include "types.h"
7 |
8 | #if defined(_MSC_VER)
9 | #include "ms_stdbool.h"
10 | #else
11 | #include
12 | #endif
13 | #ifdef __cplusplus
14 | extern "C"
15 | {
16 | #endif
17 | #if defined(IS_MACOSX)
18 |
19 | #include
20 |
21 | typedef enum {
22 | LEFT_BUTTON = kCGMouseButtonLeft,
23 | RIGHT_BUTTON = kCGMouseButtonRight,
24 | CENTER_BUTTON = kCGMouseButtonCenter
25 | } MMMouseButton;
26 |
27 | #elif defined(USE_X11)
28 |
29 | enum _MMMouseButton {
30 | LEFT_BUTTON = 1,
31 | CENTER_BUTTON = 2,
32 | RIGHT_BUTTON = 3
33 | };
34 | typedef unsigned int MMMouseButton;
35 |
36 | #elif defined(IS_WINDOWS)
37 |
38 | enum _MMMouseButton {
39 | LEFT_BUTTON = 1,
40 | CENTER_BUTTON = 2,
41 | RIGHT_BUTTON = 3
42 | };
43 | typedef unsigned int MMMouseButton;
44 |
45 | #else
46 | #error "No mouse button constants set for platform"
47 | #endif
48 |
49 | #define MMMouseButtonIsValid(button) \
50 | (button == LEFT_BUTTON || button == RIGHT_BUTTON || \
51 | button == CENTER_BUTTON)
52 |
53 | enum __MMMouseWheelDirection
54 | {
55 | DIRECTION_DOWN = -1,
56 | DIRECTION_UP = 1
57 | };
58 | typedef int MMMouseWheelDirection;
59 |
60 | /* Updates information about current virtual screen size and coordinates
61 | * in Windows
62 | * It is up to the caller to ensure that this called before mouse moving
63 | */
64 | void updateScreenMetrics();
65 |
66 | /* Immediately moves the mouse to the given point on-screen.
67 | * It is up to the caller to ensure that this point is within the
68 | * screen boundaries. */
69 | void moveMouse(MMSignedPoint point);
70 |
71 | /* Like moveMouse, moves the mouse to the given point on-screen, but marks
72 | * the event as the mouse being dragged on platforms where it is supported.
73 | * It is up to the caller to ensure that this point is within the screen
74 | * boundaries. */
75 | void dragMouse(MMSignedPoint point, const MMMouseButton button);
76 |
77 | /* Smoothly moves the mouse from the current position to the given point.
78 | * deadbeef_srand() should be called before using this function.
79 | *
80 | * Returns false if unsuccessful (i.e. a point was hit that is outside of the
81 | * screen boundaries), or true if successful. */
82 | bool smoothlyMoveMouse(MMPoint point,double speed);
83 |
84 | /* Returns the coordinates of the mouse on the current screen. */
85 | MMPoint getMousePos(void);
86 |
87 | /* Holds down or releases the mouse with the given button in the current
88 | * position. */
89 | void toggleMouse(bool down, MMMouseButton button);
90 |
91 | /* Clicks the mouse with the given button in the current position. */
92 | void clickMouse(MMMouseButton button);
93 |
94 | /* Double clicks the mouse with the given button. */
95 | void doubleClick(MMMouseButton button);
96 |
97 | /* Scrolls the mouse in the stated direction.
98 | * TODO: Add a smoothly scroll mouse next. */
99 | void scrollMouse(int x, int y);
100 |
101 | #endif /* MOUSE_H */
102 |
103 | #ifdef __cplusplus
104 | }
105 | #endif
106 |
--------------------------------------------------------------------------------
/src/ms_stdbool.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #if !defined(MS_STDBOOL_H) && \
3 | (!defined(__bool_true_false_are_defined) || __bool_true_false_are_defined)
4 | #define MS_STDBOOL_H
5 |
6 | #ifndef _MSC_VER
7 | #error "Use this header only with Microsoft Visual C++ compilers!"
8 | #endif /* _MSC_VER */
9 |
10 | #define __bool_true_false_are_defined 1
11 |
12 | #ifndef __cplusplus
13 |
14 | #if defined(true) || defined(false) || defined(bool)
15 | #error "Boolean type already defined"
16 | #endif
17 |
18 | enum {
19 | false = 0,
20 | true = 1
21 | };
22 |
23 | typedef unsigned char bool;
24 |
25 | #endif /* !__cplusplus */
26 |
27 | #endif /* MS_STDBOOL_H */
28 |
--------------------------------------------------------------------------------
/src/ms_stdint.h:
--------------------------------------------------------------------------------
1 | /* ISO C9x compliant stdint.h for Microsoft Visual Studio
2 | * Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
3 | *
4 | * Copyright (c) 2006-2008 Alexander Chemeris
5 | *
6 | * Redistribution and use in source and binary forms, with or without
7 | * modification, are permitted provided that the following conditions are met:
8 | *
9 | * 1. Redistributions of source code must retain the above copyright notice,
10 | * this list of conditions and the following disclaimer.
11 | *
12 | * 2. Redistributions in binary form must reproduce the above copyright
13 | * notice, this list of conditions and the following disclaimer in the
14 | * documentation and/or other materials provided with the distribution.
15 | *
16 | * 3. The name of the author may be used to endorse or promote products
17 | * derived from this software without specific prior written permission.
18 | *
19 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
20 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 | * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
22 | * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 | * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 | * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 | */
30 |
31 | #ifndef _MSC_VER
32 | #error "Use this header only with Microsoft Visual C++ compilers!"
33 | #endif /* _MSC_VER */
34 |
35 | #ifndef MSC_STDINT_H
36 | #define MSC_STDINT_H
37 |
38 | #if _MSC_VER > 1000
39 | #pragma once
40 | #endif
41 |
42 | #include
43 |
44 | /* For Visual Studio 6 in C++ mode and for many Visual Studio versions when
45 | * compiling for ARM we should wrap include with 'extern "C++" {}'
46 | * or compiler give many errors like this: */
47 | #if defined(__cplusplus)
48 | extern "C" {
49 | #endif /* __cplusplus */
50 | #include
51 | #if defined(__cplusplus)
52 | }
53 | #endif /* __cplusplus */
54 |
55 | /* Define _W64 macros to mark types changing their size, like intptr_t. */
56 | #ifndef _W64
57 | #if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
58 | #define _W64 __w64
59 | #else
60 | #define _W64
61 | #endif
62 | #endif
63 |
64 |
65 | /* 7.18.1 Integer types */
66 |
67 | /* 7.18.1.1 Exact-width integer types */
68 |
69 | /* Visual Studio 6 and Embedded Visual C++ 4 doesn't
70 | * realize that, e.g. char has the same size as __int8
71 | * so we give up on __intX for them. */
72 | #if _MSC_VER < 1300
73 | typedef signed char int8_t;
74 | typedef signed short int16_t;
75 | typedef signed int int32_t;
76 | typedef unsigned char uint8_t;
77 | typedef unsigned short uint16_t;
78 | typedef unsigned int uint32_t;
79 | #else
80 | typedef signed __int8 int8_t;
81 | typedef signed __int16 int16_t;
82 | typedef signed __int32 int32_t;
83 | typedef unsigned __int8 uint8_t;
84 | typedef unsigned __int16 uint16_t;
85 | typedef unsigned __int32 uint32_t;
86 | #endif
87 | typedef signed __int64 int64_t;
88 | typedef unsigned __int64 uint64_t;
89 |
90 | /* 7.18.1.2 Minimum-width integer types */
91 | typedef int8_t int_least8_t;
92 | typedef int16_t int_least16_t;
93 | typedef int32_t int_least32_t;
94 | typedef int64_t int_least64_t;
95 | typedef uint8_t uint_least8_t;
96 | typedef uint16_t uint_least16_t;
97 | typedef uint32_t uint_least32_t;
98 | typedef uint64_t uint_least64_t;
99 |
100 | /* 7.18.1.3 Fastest minimum-width integer types */
101 | typedef int8_t int_fast8_t;
102 | typedef int16_t int_fast16_t;
103 | typedef int32_t int_fast32_t;
104 | typedef int64_t int_fast64_t;
105 | typedef uint8_t uint_fast8_t;
106 | typedef uint16_t uint_fast16_t;
107 | typedef uint32_t uint_fast32_t;
108 | typedef uint64_t uint_fast64_t;
109 |
110 | /* 7.18.1.4 Integer types capable of holding object pointers */
111 | #if defined(_WIN64)
112 | typedef signed __int64 intptr_t;
113 | typedef unsigned __int64 uintptr_t;
114 | #else
115 | typedef _W64 signed int intptr_t;
116 | typedef _W64 unsigned int uintptr_t;
117 | #endif /* _WIN64 ] */
118 |
119 | /* 7.18.1.5 Greatest-width integer types */
120 | typedef int64_t intmax_t;
121 | typedef uint64_t uintmax_t;
122 |
123 | /* 7.18.2 Limits of specified-width integer types */
124 |
125 | /* See footnote 220 at page 257 and footnote 221 at page 259 */
126 | #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS)
127 |
128 | /* 7.18.2.1 Limits of exact-width integer types */
129 | #define INT8_MIN ((int8_t)_I8_MIN)
130 | #define INT8_MAX _I8_MAX
131 | #define INT16_MIN ((int16_t)_I16_MIN)
132 | #define INT16_MAX _I16_MAX
133 | #define INT32_MIN ((int32_t)_I32_MIN)
134 | #define INT32_MAX _I32_MAX
135 | #define INT64_MIN ((int64_t)_I64_MIN)
136 | #define INT64_MAX _I64_MAX
137 | #define UINT8_MAX _UI8_MAX
138 | #define UINT16_MAX _UI16_MAX
139 | #define UINT32_MAX _UI32_MAX
140 | #define UINT64_MAX _UI64_MAX
141 |
142 | /* 7.18.2.2 Limits of minimum-width integer types */
143 | #define INT_LEAST8_MIN INT8_MIN
144 | #define INT_LEAST8_MAX INT8_MAX
145 | #define INT_LEAST16_MIN INT16_MIN
146 | #define INT_LEAST16_MAX INT16_MAX
147 | #define INT_LEAST32_MIN INT32_MIN
148 | #define INT_LEAST32_MAX INT32_MAX
149 | #define INT_LEAST64_MIN INT64_MIN
150 | #define INT_LEAST64_MAX INT64_MAX
151 | #define UINT_LEAST8_MAX UINT8_MAX
152 | #define UINT_LEAST16_MAX UINT16_MAX
153 | #define UINT_LEAST32_MAX UINT32_MAX
154 | #define UINT_LEAST64_MAX UINT64_MAX
155 |
156 | /* 7.18.2.4 Limits of integer types capable of holding object pointers */
157 | #if defined(_WIN64)
158 | #define INTPTR_MIN INT64_MIN
159 | #define INTPTR_MAX INT64_MAX
160 | #define UINTPTR_MAX UINT64_MAX
161 | #else
162 | #define INTPTR_MIN INT32_MIN
163 | #define INTPTR_MAX INT32_MAX
164 | #define UINTPTR_MAX UINT32_MAX
165 | #endif
166 |
167 | /* 7.18.3 Limits of other integer types */
168 |
169 | #if defined(_WIN64)
170 | #define PTRDIFF_MIN _I64_MIN
171 | #define PTRDIFF_MAX _I64_MAX
172 | #else
173 | #define PTRDIFF_MIN _I32_MIN
174 | #define PTRDIFF_MAX _I32_MAX
175 | #endif /* _WIN64 */
176 |
177 | #define SIG_ATOMIC_MIN INT_MIN
178 | #define SIG_ATOMIC_MAX INT_MAX
179 |
180 | #ifndef SIZE_MAX
181 | #if defined(_WIN64)
182 | #define SIZE_MAX _UI64_MAX
183 | #else
184 | #define SIZE_MAX _UI32_MAX
185 | #endif
186 | #endif
187 |
188 | /* WCHAR_MIN and WCHAR_MAX are also defined in */
189 | #ifndef WCHAR_MIN
190 | #define WCHAR_MIN 0
191 | #endif /* WCHAR_MIN */
192 |
193 | #ifndef WCHAR_MAX
194 | #define WCHAR_MAX _UI16_MAX
195 | #endif /* WCHAR_MAX */
196 |
197 | #define WINT_MIN 0
198 | #define WINT_MAX _UI16_MAX
199 | #endif /* __STDC_LIMIT_MACROS */
200 |
201 |
202 | /* 7.18.4 Limits of other integer types */
203 |
204 | #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) /* See footnote 224 at page 260 */
205 |
206 | /* 7.18.4.1 Macros for minimum-width integer constants */
207 |
208 | #define INT8_C(val) val##i8
209 | #define INT16_C(val) val##i16
210 | #define INT32_C(val) val##i32
211 | #define INT64_C(val) val##i64
212 |
213 | #define UINT8_C(val) val##ui8
214 | #define UINT16_C(val) val##ui16
215 | #define UINT32_C(val) val##ui32
216 | #define UINT64_C(val) val##ui64
217 |
218 | /* 7.18.4.2 Macros for greatest-width integer constants */
219 | #define INTMAX_C INT64_C
220 | #define UINTMAX_C UINT64_C
221 |
222 | #endif /* __STDC_CONSTANT_MACROS */
223 |
224 | #endif /* MSC_STDINT_H */
225 |
--------------------------------------------------------------------------------
/src/os.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef OS_H
3 | #define OS_H
4 |
5 | /* Python versions under 2.5 don't support this macro, but it's not
6 | * terribly difficult to replicate: */
7 | #ifndef PyModule_AddIntMacro
8 | #define PyModule_AddIntMacro(module, macro) \
9 | PyModule_AddIntConstant(module, #macro, macro)
10 | #endif /* PyModule_AddIntMacro */
11 |
12 | #if !defined(IS_MACOSX) && defined(__APPLE__) && defined(__MACH__)
13 | #define IS_MACOSX
14 | #endif /* IS_MACOSX */
15 |
16 | #if !defined(IS_WINDOWS) && (defined(WIN32) || defined(_WIN32) || \
17 | defined(__WIN32__) || defined(__WINDOWS__))
18 | #define IS_WINDOWS
19 | #endif /* IS_WINDOWS */
20 |
21 | #if !defined(USE_X11) && !defined(NUSE_X11) && !defined(IS_MACOSX) && !defined(IS_WINDOWS)
22 | #define USE_X11
23 | #endif /* USE_X11 */
24 |
25 | #if defined(IS_WINDOWS)
26 | #define STRICT /* Require use of exact types. */
27 | #define WIN32_LEAN_AND_MEAN 1 /* Speed up compilation. */
28 | #include
29 | #elif !defined(IS_MACOSX) && !defined(USE_X11)
30 | #error "Sorry, this platform isn't supported yet!"
31 | #endif
32 |
33 | /* Interval to align by for large buffers (e.g. bitmaps). */
34 | /* Must be a power of 2. */
35 | #ifndef BYTE_ALIGN
36 | #define BYTE_ALIGN 4 /* Bytes to align pixel buffers to. */
37 | /* #include */
38 | /* #define BYTE_ALIGN (sizeof(size_t)) */
39 | #endif /* BYTE_ALIGN */
40 |
41 | #if BYTE_ALIGN == 0
42 | /* No alignment needed. */
43 | #define ADD_PADDING(width) (width)
44 | #else
45 | /* Aligns given width to padding. */
46 | #define ADD_PADDING(width) (BYTE_ALIGN + (((width) - 1) & ~(BYTE_ALIGN - 1)))
47 | #endif
48 |
49 | #endif /* OS_H */
50 |
--------------------------------------------------------------------------------
/src/pasteboard.c:
--------------------------------------------------------------------------------
1 | #include "pasteboard.h"
2 | #include "os.h"
3 |
4 | #if defined(IS_MACOSX)
5 | #include "png_io.h"
6 | #include
7 | #elif defined(IS_WINDOWS)
8 | #include "bmp_io.h"
9 | #endif
10 |
11 | MMPasteError copyMMBitmapToPasteboard(MMBitmapRef bitmap)
12 | {
13 | #if defined(IS_MACOSX)
14 | PasteboardRef clipboard;
15 |
16 | size_t len;
17 | uint8_t *pngbuf;
18 | CFDataRef data;
19 | OSStatus err;
20 |
21 | if (PasteboardCreate(kPasteboardClipboard, &clipboard) != noErr) {
22 | return kMMPasteOpenError;
23 | }
24 |
25 | if (PasteboardClear(clipboard) != noErr) {
26 | CFRelease(clipboard);
27 | return kMMPasteClearError;
28 | }
29 |
30 | pngbuf = createPNGData(bitmap, &len);
31 | if (pngbuf == NULL) {
32 | CFRelease(clipboard);
33 | return kMMPasteDataError;
34 | }
35 |
36 | data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, pngbuf, len,
37 | kCFAllocatorNull);
38 | if (data == NULL) {
39 | CFRelease(clipboard);
40 | free(pngbuf);
41 | return kMMPasteDataError;
42 | }
43 |
44 | err = PasteboardPutItemFlavor(clipboard, bitmap, kUTTypePNG, data, 0);
45 | CFRelease(data);
46 | CFRelease(clipboard);
47 | free(pngbuf);
48 | return (err == noErr) ? kMMPasteNoError : kMMPastePasteError;
49 | #elif defined(IS_WINDOWS)
50 | MMPasteError ret = kMMPasteNoError;
51 | uint8_t *bmpData;
52 | size_t len;
53 | HGLOBAL handle;
54 |
55 | if (!OpenClipboard(NULL)) return kMMPasteOpenError;
56 | if (!EmptyClipboard()) return kMMPasteClearError;
57 |
58 | bmpData = createBitmapData(bitmap, &len);
59 | if (bmpData == NULL) return kMMPasteDataError;
60 |
61 | /* CF_DIB does not include the BITMAPFILEHEADER struct (and displays a
62 | * cryptic error if it is included). */
63 | len -= sizeof(BITMAPFILEHEADER);
64 |
65 | /* SetClipboardData() needs a "handle", not just a buffer, so we have to
66 | * allocate one with GlobalAlloc(). */
67 | if ((handle = GlobalAlloc(GMEM_MOVEABLE, len)) == NULL) {
68 | CloseClipboard();
69 | free(bmpData);
70 | return kMMPasteDataError;
71 | }
72 |
73 | memcpy(GlobalLock(handle), bmpData + sizeof(BITMAPFILEHEADER), len);
74 | GlobalUnlock(handle);
75 | free(bmpData);
76 |
77 | if (SetClipboardData(CF_DIB, handle) == NULL) {
78 | ret = kMMPastePasteError;
79 | }
80 |
81 | CloseClipboard();
82 | GlobalFree(handle);
83 | return ret;
84 | #elif defined(USE_X11)
85 | /* TODO (X11's clipboard is _weird_.) */
86 | return kMMPasteUnsupportedError;
87 | #endif
88 | }
89 |
90 | const char *MMPasteErrorString(MMPasteError err)
91 | {
92 | switch (err) {
93 | case kMMPasteOpenError:
94 | return "Could not open pasteboard";
95 | case kMMPasteClearError:
96 | return "Could not clear pasteboard";
97 | case kMMPasteDataError:
98 | return "Could not create image data from bitmap";
99 | case kMMPastePasteError:
100 | return "Could not paste data";
101 | case kMMPasteUnsupportedError:
102 | return "Unsupported platform";
103 | default:
104 | return NULL;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/pasteboard.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef PASTEBOARD_H
3 | #define PASTEBOARD_H
4 |
5 | #include "MMBitmap.h"
6 | #include "io.h"
7 |
8 | enum _MMBitmapPasteError {
9 | kMMPasteNoError = 0,
10 | kMMPasteGenericError,
11 | kMMPasteOpenError,
12 | kMMPasteClearError,
13 | kMMPasteDataError,
14 | kMMPastePasteError,
15 | kMMPasteUnsupportedError
16 | };
17 |
18 | typedef MMIOError MMPasteError;
19 |
20 | /* Copies |bitmap| to the pasteboard as a PNG.
21 | * Returns 0 on success, non-zero on error. */
22 | MMPasteError copyMMBitmapToPasteboard(MMBitmapRef bitmap);
23 |
24 | /* Returns description of given MMPasteError.
25 | * Returned string is constant and hence should not be freed. */
26 | const char *MMPasteErrorString(MMPasteError error);
27 |
28 | #endif /* PASTEBOARD_H */
29 |
--------------------------------------------------------------------------------
/src/png_io.c:
--------------------------------------------------------------------------------
1 | #include "png_io.h"
2 | #include "os.h"
3 | #include
4 | #include /* fopen() */
5 | #include /* malloc/realloc */
6 | #include
7 |
8 | #if defined(_MSC_VER)
9 | #include "ms_stdint.h"
10 | #include "ms_stdbool.h"
11 | #else
12 | #include
13 | #include
14 | #endif
15 |
16 | const char *MMPNGReadErrorString(MMIOError error)
17 | {
18 | switch (error) {
19 | case kPNGAccessError:
20 | return "Could not open file";
21 | case kPNGReadError:
22 | return "Could not read file";
23 | case kPNGInvalidHeaderError:
24 | return "Not a PNG file";
25 | default:
26 | return NULL;
27 | }
28 | }
29 |
30 | MMBitmapRef newMMBitmapFromPNG(const char *path, MMPNGReadError *err)
31 | {
32 | FILE *fp;
33 | uint8_t header[8];
34 | png_struct *png_ptr = NULL;
35 | png_info *info_ptr = NULL;
36 | png_byte bit_depth, color_type;
37 | uint8_t *row, *bitmapData;
38 | uint8_t bytesPerPixel;
39 | png_uint_32 width, height, y;
40 | uint32_t bytewidth;
41 |
42 | if ((fp = fopen(path, "rb")) == NULL) {
43 | if (err != NULL) *err = kPNGAccessError;
44 | return NULL;
45 | }
46 |
47 | /* Initialize error code to generic value. */
48 | if (err != NULL) *err = kPNGGenericError;
49 |
50 | /* Validate the PNG. */
51 | if (fread(header, 1, sizeof header, fp) == 0) {
52 | if (err != NULL) *err = kPNGReadError;
53 | goto bail;
54 | } else if (png_sig_cmp(header, 0, sizeof(header)) != 0) {
55 | if (err != NULL) *err = kPNGInvalidHeaderError;
56 | goto bail;
57 | }
58 |
59 | png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
60 | if (png_ptr == NULL) goto bail;
61 |
62 | info_ptr = png_create_info_struct(png_ptr);
63 | if (info_ptr == NULL) goto bail;
64 |
65 | /* Set up error handling. */
66 | if (setjmp(png_jmpbuf(png_ptr))) {
67 | goto bail;
68 | }
69 |
70 | png_init_io(png_ptr, fp);
71 |
72 | /* Skip past the header. */
73 | png_set_sig_bytes(png_ptr, sizeof header);
74 |
75 | png_read_info(png_ptr, info_ptr);
76 |
77 | /* Convert different image types to common type to be read. */
78 | bit_depth = png_get_bit_depth(png_ptr, info_ptr);
79 | color_type = png_get_color_type(png_ptr, info_ptr);
80 |
81 | /* Convert color palettes to RGB. */
82 | if (color_type == PNG_COLOR_TYPE_PALETTE) {
83 | png_set_palette_to_rgb(png_ptr);
84 | }
85 |
86 | /* Convert PNG to bit depth of 8. */
87 | if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
88 | png_set_expand_gray_1_2_4_to_8(png_ptr);
89 | } else if (bit_depth == 16) {
90 | png_set_strip_16(png_ptr);
91 | }
92 |
93 | /* Convert transparency chunk to alpha channel. */
94 | if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
95 | png_set_tRNS_to_alpha(png_ptr);
96 | }
97 |
98 | /* Convert gray images to RGB. */
99 | if (color_type == PNG_COLOR_TYPE_GRAY ||
100 | color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
101 | png_set_gray_to_rgb(png_ptr);
102 | }
103 |
104 | /* Ignore alpha for now. */
105 | if (color_type & PNG_COLOR_MASK_ALPHA) {
106 | png_set_strip_alpha(png_ptr);
107 | }
108 |
109 | /* Get image attributes. */
110 | width = png_get_image_width(png_ptr, info_ptr);
111 | height = png_get_image_height(png_ptr, info_ptr);
112 | bytesPerPixel = 3; /* All images decompress to this size. */
113 | bytewidth = ADD_PADDING(width * bytesPerPixel); /* Align width. */
114 |
115 | /* Decompress the PNG row by row. */
116 | bitmapData = calloc(1, bytewidth * height);
117 | row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
118 | if (bitmapData == NULL || row == NULL) goto bail;
119 | for (y = 0; y < height; ++y) {
120 | png_uint_32 x;
121 | const uint32_t rowOffset = y * bytewidth;
122 | uint8_t *rowptr = row;
123 | png_read_row(png_ptr, (png_byte *)row, NULL);
124 |
125 | for (x = 0; x < width; ++x) {
126 | const uint32_t colOffset = x * bytesPerPixel;
127 | MMRGBColor *color = (MMRGBColor *)(bitmapData + rowOffset + colOffset);
128 | color->red = *rowptr++;
129 | color->green = *rowptr++;
130 | color->blue = *rowptr++;
131 | }
132 | }
133 | free(row);
134 |
135 | /* Finish reading. */
136 | png_read_end(png_ptr, NULL);
137 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
138 | fclose(fp);
139 |
140 | return createMMBitmap(bitmapData, width, height,
141 | bytewidth, bytesPerPixel * 8, bytesPerPixel);
142 |
143 | bail:
144 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
145 | fclose(fp);
146 | return NULL;
147 | }
148 |
149 | struct _PNGWriteInfo {
150 | png_struct *png_ptr;
151 | png_info *info_ptr;
152 | png_byte **row_pointers;
153 | size_t row_count;
154 | bool free_row_pointers;
155 | };
156 |
157 | typedef struct _PNGWriteInfo PNGWriteInfo;
158 | typedef PNGWriteInfo *PNGWriteInfoRef;
159 |
160 | /* Returns pointer to PNGWriteInfo struct containing data ready to be used with
161 | * functions such as png_write_png().
162 | *
163 | * It is the caller's responsibility to destroy() the returned structure with
164 | * destroyPNGWriteInfo(). */
165 | static PNGWriteInfoRef createPNGWriteInfo(MMBitmapRef bitmap)
166 | {
167 | PNGWriteInfoRef info = malloc(sizeof(PNGWriteInfo));
168 | png_uint_32 y;
169 |
170 | if (info == NULL) return NULL;
171 | info->png_ptr = NULL;
172 | info->info_ptr = NULL;
173 | info->row_pointers = NULL;
174 |
175 | assert(bitmap != NULL);
176 |
177 | /* Initialize the write struct. */
178 | info->png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
179 | NULL, NULL, NULL);
180 | if (info->png_ptr == NULL) goto bail;
181 |
182 | /* Set up error handling. */
183 | if (setjmp(png_jmpbuf(info->png_ptr))) {
184 | png_destroy_write_struct(&(info->png_ptr), &(info->info_ptr));
185 | goto bail;
186 | }
187 |
188 | /* Initialize the info struct. */
189 | info->info_ptr = png_create_info_struct(info->png_ptr);
190 | if (info->info_ptr == NULL) {
191 | png_destroy_write_struct(&(info->png_ptr), NULL);
192 | goto bail;
193 | }
194 |
195 | /* Set image attributes. */
196 | png_set_IHDR(info->png_ptr,
197 | info->info_ptr,
198 | (png_uint_32)bitmap->width,
199 | (png_uint_32)bitmap->height,
200 | 8,
201 | PNG_COLOR_TYPE_RGB,
202 | PNG_INTERLACE_NONE,
203 | PNG_COMPRESSION_TYPE_DEFAULT,
204 | PNG_FILTER_TYPE_DEFAULT);
205 |
206 | info->row_count = bitmap->height;
207 | info->row_pointers = png_malloc(info->png_ptr,
208 | sizeof(png_byte *) * info->row_count);
209 |
210 | if (bitmap->bytesPerPixel == 3) {
211 | /* No alpha channel; image data can be copied directly. */
212 | for (y = 0; y < info->row_count; ++y) {
213 | info->row_pointers[y] = bitmap->imageBuffer + (bitmap->bytewidth * y);
214 | }
215 | info->free_row_pointers = false;
216 |
217 | /* Convert BGR to RGB if necessary. */
218 | if (MMRGB_IS_BGR) {
219 | png_set_bgr(info->png_ptr);
220 | }
221 | } else {
222 | /* Ignore alpha channel; copy image data row by row. */
223 | const size_t bytesPerPixel = 3;
224 | const size_t bytewidth = ADD_PADDING(bitmap->width * bytesPerPixel);
225 |
226 | for (y = 0; y < info->row_count; ++y) {
227 | png_uint_32 x;
228 | png_byte *row_ptr = png_malloc(info->png_ptr, bytewidth);
229 | info->row_pointers[y] = row_ptr;
230 | for (x = 0; x < bitmap->width; ++x) {
231 | MMRGBColor *color = MMRGBColorRefAtPoint(bitmap, x, y);
232 | row_ptr[0] = color->red;
233 | row_ptr[1] = color->green;
234 | row_ptr[2] = color->blue;
235 |
236 | row_ptr += bytesPerPixel;
237 | }
238 | }
239 | info->free_row_pointers = true;
240 | }
241 |
242 | png_set_rows(info->png_ptr, info->info_ptr, info->row_pointers);
243 | return info;
244 |
245 | bail:
246 | if (info != NULL) free(info);
247 | return NULL;
248 | }
249 |
250 | /* Free memory in use by |info|. */
251 | static void destroyPNGWriteInfo(PNGWriteInfoRef info)
252 | {
253 | assert(info != NULL);
254 | if (info->row_pointers != NULL) {
255 | if (info->free_row_pointers) {
256 | size_t y;
257 | for (y = 0; y < info->row_count; ++y) {
258 | free(info->row_pointers[y]);
259 | }
260 | }
261 | png_free(info->png_ptr, info->row_pointers);
262 | }
263 |
264 | png_destroy_write_struct(&(info->png_ptr), &(info->info_ptr));
265 | free(info);
266 | }
267 |
268 | int saveMMBitmapAsPNG(MMBitmapRef bitmap, const char *path)
269 | {
270 | FILE *fp = fopen(path, "wb");
271 | PNGWriteInfoRef info;
272 | if (fp == NULL) return -1;
273 |
274 | if ((info = createPNGWriteInfo(bitmap)) == NULL) {
275 | fclose(fp);
276 | return -1;
277 | }
278 |
279 | png_init_io(info->png_ptr, fp);
280 | png_write_png(info->png_ptr, info->info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
281 | fclose(fp);
282 |
283 | destroyPNGWriteInfo(info);
284 | return 0;
285 | }
286 |
287 | /* Structure to store PNG image bytes. */
288 | struct io_data
289 | {
290 | uint8_t *buffer; /* Pointer to raw file data. */
291 | size_t size; /* Number of bytes actually written to buffer. */
292 | size_t allocedSize; /* Number of bytes allocated for buffer. */
293 | };
294 |
295 | /* Called each time libpng attempts to write data in createPNGData(). */
296 | void png_append_data(png_struct *png_ptr,
297 | png_byte *new_data,
298 | png_size_t length)
299 | {
300 | struct io_data *data = png_get_io_ptr(png_ptr);
301 | data->size += length;
302 |
303 | /* Allocate or grow buffer. */
304 | if (data->buffer == NULL) {
305 | data->allocedSize = data->size;
306 | data->buffer = png_malloc(png_ptr, data->allocedSize);
307 | assert(data->buffer != NULL);
308 | } else if (data->allocedSize < data->size) {
309 | do {
310 | /* Double size each time to avoid calls to realloc. */
311 | data->allocedSize <<= 1;
312 | } while (data->allocedSize < data->size);
313 |
314 | data->buffer = realloc(data->buffer, data->allocedSize);
315 | }
316 |
317 | /* Copy new bytes to end of buffer. */
318 | memcpy(data->buffer + data->size - length, new_data, length);
319 | }
320 |
321 | uint8_t *createPNGData(MMBitmapRef bitmap, size_t *len)
322 | {
323 | PNGWriteInfoRef info = NULL;
324 | struct io_data data = {NULL, 0, 0};
325 |
326 | assert(bitmap != NULL);
327 | assert(len != NULL);
328 |
329 | if ((info = createPNGWriteInfo(bitmap)) == NULL) return NULL;
330 |
331 | png_set_write_fn(info->png_ptr, &data, &png_append_data, NULL);
332 | png_write_png(info->png_ptr, info->info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
333 |
334 | destroyPNGWriteInfo(info);
335 |
336 | *len = data.size;
337 | return data.buffer;
338 | }
339 |
--------------------------------------------------------------------------------
/src/png_io.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef PNG_IO_H
3 | #define PNG_IO_H
4 |
5 | #include "MMBitmap.h"
6 | #include "io.h"
7 |
8 | enum _PNGReadError {
9 | kPNGGenericError = 0,
10 | kPNGReadError,
11 | kPNGAccessError,
12 | kPNGInvalidHeaderError
13 | };
14 |
15 | typedef MMIOError MMPNGReadError;
16 |
17 | /* Returns description of given MMPNGReadError.
18 | * Returned string is constant and hence should not be freed. */
19 | const char *MMPNGReadErrorString(MMIOError error);
20 |
21 | /* Attempts to read PNG file at path; returns new MMBitmap on success, or
22 | * NULL on error. If |error| is non-NULL, it will be set to the error code
23 | * on return.
24 | * Responsibility for destroy()'ing returned MMBitmap is left up to caller. */
25 | MMBitmapRef newMMBitmapFromPNG(const char *path, MMPNGReadError *error);
26 |
27 | /* Attempts to write PNG at path; returns 0 on success, -1 on error. */
28 | int saveMMBitmapAsPNG(MMBitmapRef bitmap, const char *path);
29 |
30 | /* Returns a buffer containing the raw PNG file data, ready to be saved to a
31 | * file. |len| will be set to the number of bytes allocated in the returned
32 | * buffer (it cannot be NULL).
33 | *
34 | * Responsibility for free()'ing data is left up to the caller. */
35 | uint8_t *createPNGData(MMBitmapRef bitmap, size_t *len);
36 |
37 | #endif /* PNG_IO_H */
38 |
--------------------------------------------------------------------------------
/src/rgb.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef RGB_H
3 | #define RGB_H
4 |
5 | #include /* For abs() */
6 | #include
7 | #include "inline_keywords.h" /* For H_INLINE */
8 | #include
9 |
10 |
11 | /* RGB colors in MMBitmaps are stored as BGR for convenience in converting
12 | * to/from certain formats (mainly OpenGL).
13 | *
14 | * It is best not to rely on the order (simply use rgb.{blue,green,red} to
15 | * access values), but some situations (e.g., glReadPixels) require one to
16 | * do so. In that case, check to make sure to use MMRGB_IS_BGR for future
17 | * compatibility. */
18 |
19 | /* #define MMRGB_IS_BGR (offsetof(MMRGBColor, red) > offsetof(MMRGBColor, blue)) */
20 | #define MMRGB_IS_BGR 1
21 |
22 | struct _MMRGBColor {
23 | uint8_t blue;
24 | uint8_t green;
25 | uint8_t red;
26 | };
27 |
28 | typedef struct _MMRGBColor MMRGBColor;
29 |
30 | /* MMRGBHex is a hexadecimal color value, akin to HTML's, in the form 0xRRGGBB
31 | * where RR is the red value expressed as hexadecimal, GG is the green value,
32 | * and BB is the blue value. */
33 | typedef uint32_t MMRGBHex;
34 |
35 | #define MMRGBHEX_MIN 0x000000
36 | #define MMRGBHEX_MAX 0xFFFFFF
37 |
38 | /* Converts rgb color to hexadecimal value.
39 | * |red|, |green|, and |blue| should each be of the type |uint8_t|, where the
40 | * range is 0 - 255. */
41 | #define RGB_TO_HEX(red, green, blue) (((red) << 16) | ((green) << 8) | (blue))
42 |
43 | /* Convenience wrapper for MMRGBColors. */
44 | H_INLINE MMRGBHex hexFromMMRGB(MMRGBColor rgb)
45 | {
46 | return RGB_TO_HEX(rgb.red, rgb.green, rgb.blue);
47 | }
48 |
49 | #define RED_FROM_HEX(hex) ((hex >> 16) & 0xFF)
50 | #define GREEN_FROM_HEX(hex) ((hex >> 8) & 0xFF)
51 | #define BLUE_FROM_HEX(hex) (hex & 0xFF)
52 |
53 | /* Converts hexadecimal color to MMRGBColor. */
54 | H_INLINE MMRGBColor MMRGBFromHex(MMRGBHex hex)
55 | {
56 | MMRGBColor color;
57 | color.red = RED_FROM_HEX(hex);
58 | color.green = GREEN_FROM_HEX(hex);
59 | color.blue = BLUE_FROM_HEX(hex);
60 | return color;
61 | }
62 |
63 | /* Check absolute equality of two RGB colors. */
64 | #define MMRGBColorEqualToColor(c1, c2) ((c1).red == (c2).red && \
65 | (c1).blue == (c2).blue && \
66 | (c1).green == (c2).green)
67 |
68 | /* Returns whether two colors are similar within the given range, |tolerance|.
69 | * Tolerance can be in the range 0.0f - 1.0f, where 0 denotes the exact
70 | * color and 1 denotes any color. */
71 | H_INLINE int MMRGBColorSimilarToColor(MMRGBColor c1, MMRGBColor c2,
72 | float tolerance)
73 | {
74 | /* Speedy case */
75 | if (tolerance <= 0.0f) {
76 | return MMRGBColorEqualToColor(c1, c2);
77 | } else { /* Otherwise, use a Euclidean space to determine similarity */
78 | uint8_t d1 = c1.red - c2.red;
79 | uint8_t d2 = c1.green - c2.green;
80 | uint8_t d3 = c1.blue - c2.blue;
81 | return sqrt((double)(d1 * d1) +
82 | (d2 * d2) +
83 | (d3 * d3)) <= (tolerance * 442.0f);
84 | }
85 |
86 | }
87 |
88 | /* Identical to MMRGBColorSimilarToColor, only for hex values. */
89 | H_INLINE int MMRGBHexSimilarToColor(MMRGBHex h1, MMRGBHex h2, float tolerance)
90 | {
91 | if (tolerance <= 0.0f) {
92 | return h1 == h2;
93 | } else {
94 | uint8_t d1 = RED_FROM_HEX(h1) - RED_FROM_HEX(h2);
95 | uint8_t d2 = GREEN_FROM_HEX(h1) - GREEN_FROM_HEX(h2);
96 | uint8_t d3 = BLUE_FROM_HEX(h1) - BLUE_FROM_HEX(h2);
97 | return sqrt((double)(d1 * d1) +
98 | (d2 * d2) +
99 | (d3 * d3)) <= (tolerance * 442.0f);
100 | }
101 | }
102 |
103 | #endif /* RGB_H */
104 |
--------------------------------------------------------------------------------
/src/screen.c:
--------------------------------------------------------------------------------
1 | #include "screen.h"
2 | #include "os.h"
3 |
4 | #if defined(IS_MACOSX)
5 | #include
6 | #elif defined(USE_X11)
7 | #include
8 | #include "xdisplay.h"
9 | #endif
10 |
11 | MMSize getMainDisplaySize(void)
12 | {
13 | #if defined(IS_MACOSX)
14 | CGDirectDisplayID displayID = CGMainDisplayID();
15 | return MMSizeMake(CGDisplayPixelsWide(displayID),
16 | CGDisplayPixelsHigh(displayID));
17 | #elif defined(USE_X11)
18 | Display *display = XGetMainDisplay();
19 | const int screen = DefaultScreen(display);
20 |
21 | return MMSizeMake((size_t)DisplayWidth(display, screen),
22 | (size_t)DisplayHeight(display, screen));
23 | #elif defined(IS_WINDOWS)
24 | return MMSizeMake((size_t)GetSystemMetrics(SM_CXSCREEN),
25 | (size_t)GetSystemMetrics(SM_CYSCREEN));
26 | #endif
27 | }
28 |
29 | bool pointVisibleOnMainDisplay(MMPoint point)
30 | {
31 | MMSize displaySize = getMainDisplaySize();
32 | return point.x < displaySize.width && point.y < displaySize.height;
33 | }
34 |
--------------------------------------------------------------------------------
/src/screen.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef SCREEN_H
3 | #define SCREEN_H
4 |
5 | #include "types.h"
6 |
7 | #if defined(_MSC_VER)
8 | #include "ms_stdbool.h"
9 | #else
10 | #include
11 | #endif
12 |
13 | #ifdef __cplusplus
14 | extern "C"
15 | {
16 | #endif
17 |
18 | /* Returns the size of the main display. */
19 | MMSize getMainDisplaySize(void);
20 |
21 | /* Convenience function that returns whether the given point is in the bounds
22 | * of the main screen. */
23 | bool pointVisibleOnMainDisplay(MMPoint point);
24 |
25 | #ifdef __cplusplus
26 | }
27 | #endif
28 |
29 | #endif /* SCREEN_H */
30 |
--------------------------------------------------------------------------------
/src/screengrab.c:
--------------------------------------------------------------------------------
1 | #include "screengrab.h"
2 | #include "bmp_io.h"
3 | #include "endian.h"
4 | #include /* malloc() */
5 |
6 | #if defined(IS_MACOSX)
7 | #include
8 | #include
9 | #include
10 | #elif defined(USE_X11)
11 | #include
12 | #include
13 | #include "xdisplay.h"
14 | #elif defined(IS_WINDOWS)
15 | #include
16 | #endif
17 |
18 | MMBitmapRef copyMMBitmapFromDisplayInRect(MMRect rect)
19 | {
20 | #if defined(IS_MACOSX)
21 |
22 | MMBitmapRef bitmap = NULL;
23 | uint8_t *buffer = NULL;
24 | size_t bufferSize = 0;
25 |
26 | CGDirectDisplayID displayID = CGMainDisplayID();
27 |
28 | CGImageRef image = CGDisplayCreateImageForRect(displayID,
29 | CGRectMake(rect.origin.x,
30 | rect.origin.y,
31 | rect.size.width,
32 | rect.size.height));
33 |
34 | if (!image) { return NULL; }
35 |
36 | CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(image));
37 |
38 | if (!imageData) { return NULL; }
39 |
40 | bufferSize = CFDataGetLength(imageData);
41 | buffer = malloc(bufferSize);
42 |
43 | CFDataGetBytes(imageData, CFRangeMake(0,bufferSize), buffer);
44 |
45 | bitmap = createMMBitmap(buffer,
46 | CGImageGetWidth(image),
47 | CGImageGetHeight(image),
48 | CGImageGetBytesPerRow(image),
49 | CGImageGetBitsPerPixel(image),
50 | CGImageGetBitsPerPixel(image) / 8);
51 |
52 | CFRelease(imageData);
53 |
54 | CGImageRelease(image);
55 |
56 | return bitmap;
57 |
58 | #elif defined(USE_X11)
59 | MMBitmapRef bitmap;
60 |
61 | Display *display = XOpenDisplay(NULL);
62 | XImage *image = XGetImage(display,
63 | XDefaultRootWindow(display),
64 | (int)rect.origin.x,
65 | (int)rect.origin.y,
66 | (unsigned int)rect.size.width,
67 | (unsigned int)rect.size.height,
68 | AllPlanes, ZPixmap);
69 | XCloseDisplay(display);
70 | if (image == NULL) return NULL;
71 |
72 | bitmap = createMMBitmap((uint8_t *)image->data,
73 | rect.size.width,
74 | rect.size.height,
75 | (size_t)image->bytes_per_line,
76 | (uint8_t)image->bits_per_pixel,
77 | (uint8_t)image->bits_per_pixel / 8);
78 | image->data = NULL; /* Steal ownership of bitmap data so we don't have to
79 | * copy it. */
80 | XDestroyImage(image);
81 |
82 | return bitmap;
83 | #elif defined(IS_WINDOWS)
84 | MMBitmapRef bitmap;
85 | void *data;
86 | HDC screen = NULL, screenMem = NULL;
87 | HBITMAP dib;
88 | BITMAPINFO bi;
89 |
90 | /* Initialize bitmap info. */
91 | bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
92 | bi.bmiHeader.biWidth = (long)rect.size.width;
93 | bi.bmiHeader.biHeight = -(long)rect.size.height; /* Non-cartesian, please */
94 | bi.bmiHeader.biPlanes = 1;
95 | bi.bmiHeader.biBitCount = 32;
96 | bi.bmiHeader.biCompression = BI_RGB;
97 | bi.bmiHeader.biSizeImage = (DWORD)(4 * rect.size.width * rect.size.height);
98 | bi.bmiHeader.biXPelsPerMeter = 0;
99 | bi.bmiHeader.biYPelsPerMeter = 0;
100 | bi.bmiHeader.biClrUsed = 0;
101 | bi.bmiHeader.biClrImportant = 0;
102 |
103 | screen = GetDC(NULL); /* Get entire screen */
104 | if (screen == NULL) return NULL;
105 |
106 | /* Get screen data in display device context. */
107 | dib = CreateDIBSection(screen, &bi, DIB_RGB_COLORS, &data, NULL, 0);
108 |
109 | /* Copy the data into a bitmap struct. */
110 | if ((screenMem = CreateCompatibleDC(screen)) == NULL ||
111 | SelectObject(screenMem, dib) == NULL ||
112 | !BitBlt(screenMem,
113 | (int)0,
114 | (int)0,
115 | (int)rect.size.width,
116 | (int)rect.size.height,
117 | screen,
118 | rect.origin.x,
119 | rect.origin.y,
120 | SRCCOPY)) {
121 |
122 | /* Error copying data. */
123 | ReleaseDC(NULL, screen);
124 | DeleteObject(dib);
125 | if (screenMem != NULL) DeleteDC(screenMem);
126 |
127 | return NULL;
128 | }
129 |
130 | bitmap = createMMBitmap(NULL,
131 | rect.size.width,
132 | rect.size.height,
133 | 4 * rect.size.width,
134 | (uint8_t)bi.bmiHeader.biBitCount,
135 | 4);
136 |
137 | /* Copy the data to our pixel buffer. */
138 | if (bitmap != NULL) {
139 | bitmap->imageBuffer = malloc(bitmap->bytewidth * bitmap->height);
140 | memcpy(bitmap->imageBuffer, data, bitmap->bytewidth * bitmap->height);
141 | }
142 |
143 | ReleaseDC(NULL, screen);
144 | DeleteObject(dib);
145 | DeleteDC(screenMem);
146 |
147 | return bitmap;
148 | #endif
149 | }
150 |
--------------------------------------------------------------------------------
/src/screengrab.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef SCREENGRAB_H
3 | #define SCREENGRAB_H
4 |
5 | #include "types.h"
6 | #include "MMBitmap.h"
7 |
8 | #ifdef __cplusplus
9 | extern "C"
10 | {
11 | #endif
12 |
13 | /* Returns a raw bitmap of screengrab of the display (to be destroyed()'d by
14 | * caller), or NULL on error. */
15 | MMBitmapRef copyMMBitmapFromDisplayInRect(MMRect rect);
16 |
17 | #ifdef __cplusplus
18 | }
19 | #endif
20 |
21 | #endif /* SCREENGRAB_H */
22 |
--------------------------------------------------------------------------------
/src/snprintf.h:
--------------------------------------------------------------------------------
1 | #ifndef _PORTABLE_SNPRINTF_H_
2 | #define _PORTABLE_SNPRINTF_H_
3 |
4 | #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
5 | #define PORTABLE_SNPRINTF_VERSION_MINOR 2
6 |
7 | #include "os.h"
8 | #if defined(IS_MACOSX)
9 | #define HAVE_SNPRINTF
10 | #else
11 | #define HAVE_SNPRINTF
12 | #define PREFER_PORTABLE_SNPRINTF
13 | #endif
14 |
15 | #include
16 | #include
17 |
18 | #ifdef __cplusplus
19 | extern "C"
20 | {
21 | #endif
22 |
23 | #ifdef HAVE_SNPRINTF
24 | #include
25 | #else
26 | extern int snprintf(char *, size_t, const char *, /*args*/ ...);
27 | extern int vsnprintf(char *, size_t, const char *, va_list);
28 | #endif
29 |
30 | #if defined(HAVE_SNPRINTF) && defined(PREFER_PORTABLE_SNPRINTF)
31 | extern int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
32 | extern int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
33 | #define snprintf portable_snprintf
34 | #define vsnprintf portable_vsnprintf
35 | #endif
36 |
37 | extern int asprintf (char **ptr, const char *fmt, /*args*/ ...);
38 | extern int vasprintf (char **ptr, const char *fmt, va_list ap);
39 | extern int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
40 | extern int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap);
41 |
42 | #endif
43 |
44 | #ifdef __cplusplus
45 | }
46 | #endif
--------------------------------------------------------------------------------
/src/str_io.c:
--------------------------------------------------------------------------------
1 | #include "str_io.h"
2 | #include "zlib_util.h"
3 | #include "base64.h"
4 | #include "snprintf.h" /* snprintf() */
5 | #include /* fputs() */
6 | #include /* isdigit() */
7 | #include /* atoi() */
8 | #include /* strlen() */
9 | #include
10 |
11 | #if defined(_MSC_VER)
12 | #include "ms_stdbool.h"
13 | #else
14 | #include
15 | #endif
16 |
17 | #define STR_BITS_PER_PIXEL 24
18 | #define STR_BYTES_PER_PIXEL ((STR_BITS_PER_PIXEL) / 8)
19 |
20 | #define MAX_DIMENSION_LEN 5 /* Maximum length for [width] or [height]
21 | * in string. */
22 |
23 | const char *MMBitmapStringErrorString(MMBMPStringError err)
24 | {
25 | switch (err) {
26 | case kMMBMPStringInvalidHeaderError:
27 | return "Invalid header for string";
28 | case kMMBMPStringDecodeError:
29 | return "Error decoding string";
30 | case kMMBMPStringDecompressError:
31 | return "Error decompressing string";
32 | case kMMBMPStringSizeError:
33 | return "String not of expected size";
34 | case MMMBMPStringEncodeError:
35 | return "Error encoding string";
36 | case kMMBMPStringCompressError:
37 | return "Error compressing string";
38 | default:
39 | return NULL;
40 | }
41 | }
42 |
43 | /* Parses beginning of string in the form of "[width],[height],*".
44 | *
45 | * If successful, |width| and |height| are set to the appropropriate values,
46 | * |len| is set to the length of [width] + the length of [height] + 2,
47 | * and true is returned; otherwise, false is returned.
48 | */
49 | static bool getSizeFromString(const uint8_t *buf, size_t buflen,
50 | size_t *width, size_t *height,
51 | size_t *len);
52 |
53 | MMBitmapRef createMMBitmapFromString(const uint8_t *buffer, size_t buflen,
54 | MMBMPStringError *err)
55 | {
56 | uint8_t *decoded, *decompressed;
57 | size_t width, height;
58 | size_t len, bytewidth;
59 |
60 | if (*buffer++ != 'b' || !getSizeFromString(buffer, --buflen,
61 | &width, &height, &len)) {
62 | if (err != NULL) *err = kMMBMPStringInvalidHeaderError;
63 | return NULL;
64 | }
65 | buffer += len;
66 | buflen -= len;
67 |
68 | decoded = base64decode(buffer, buflen, NULL);
69 | if (decoded == NULL) {
70 | if (err != NULL) *err = kMMBMPStringDecodeError;
71 | return NULL;
72 | }
73 |
74 | decompressed = zlib_decompress(decoded, &len);
75 | free(decoded);
76 |
77 | if (decompressed == NULL) {
78 | if (err != NULL) *err = kMMBMPStringDecompressError;
79 | return NULL;
80 | }
81 |
82 | bytewidth = width * STR_BYTES_PER_PIXEL; /* Note that bytewidth is NOT
83 | * aligned to a padding. */
84 | if (height * bytewidth != len) {
85 | if (err != NULL) *err = kMMBMPStringSizeError;
86 | return NULL;
87 | }
88 |
89 | return createMMBitmap(decompressed, width, height,
90 | bytewidth, STR_BITS_PER_PIXEL, STR_BYTES_PER_PIXEL);
91 | }
92 |
93 | /* Returns bitmap data suitable for encoding to a string; that is, 24-bit BGR
94 | * bitmap with no padding and 3 bytes per pixel.
95 | *
96 | * Caller is responsible for free()'ing returned buffer. */
97 | static uint8_t *createRawBitmapData(MMBitmapRef bitmap);
98 |
99 | uint8_t *createStringFromMMBitmap(MMBitmapRef bitmap, MMBMPStringError *err)
100 | {
101 | uint8_t *raw, *compressed;
102 | uint8_t *ret, *encoded;
103 | size_t len, retlen;
104 |
105 | assert(bitmap != NULL);
106 |
107 | raw = createRawBitmapData(bitmap);
108 | if (raw == NULL) {
109 | if (err != NULL) *err = kMMBMPStringGenericError;
110 | return NULL;
111 | }
112 |
113 | compressed = zlib_compress(raw,
114 | bitmap->width * bitmap->height *
115 | STR_BYTES_PER_PIXEL,
116 | 9, &len);
117 | free(raw);
118 | if (compressed == NULL) {
119 | if (err != NULL) *err = kMMBMPStringCompressError;
120 | return NULL;
121 | }
122 |
123 | encoded = base64encode(compressed, len - 1, &retlen);
124 | free(compressed);
125 | if (encoded == NULL) {
126 | if (err != NULL) *err = MMMBMPStringEncodeError;
127 | return NULL;
128 | }
129 |
130 | retlen += 3 + (MAX_DIMENSION_LEN * 2);
131 | ret = calloc(sizeof(char), (retlen + 1));
132 | snprintf((char *)ret, retlen, "b%lu,%lu,%s", (unsigned long)bitmap->width,
133 | (unsigned long)bitmap->height,
134 | encoded);
135 | ret[retlen] = '\0';
136 | free(encoded);
137 | return ret;
138 | }
139 |
140 | static uint32_t parseDimension(const uint8_t *buf, size_t buflen,
141 | size_t *numlen);
142 |
143 | static bool getSizeFromString(const uint8_t *buf, size_t buflen,
144 | size_t *width, size_t *height,
145 | size_t *len)
146 | {
147 | size_t numlen;
148 | assert(buf != NULL);
149 | assert(width != NULL);
150 | assert(height != NULL);
151 |
152 | if ((*width = parseDimension(buf, buflen, &numlen)) == 0) {
153 | return false;
154 | }
155 | *len = numlen + 1;
156 |
157 | if ((*height = parseDimension(buf + *len, buflen, &numlen)) == 0) {
158 | return false;
159 | }
160 | *len += numlen + 1;
161 |
162 | return true;
163 | }
164 |
165 | /* Parses one dimension from string as described in getSizeFromString().
166 | * Returns dimension on success, or 0 on error. */
167 | static uint32_t parseDimension(const uint8_t *buf, size_t buflen,
168 | size_t *numlen)
169 | {
170 | char num[MAX_DIMENSION_LEN + 1];
171 | size_t i;
172 |
173 | assert(buf != NULL);
174 | assert(len != NULL);
175 | for (i = 0; i < buflen && buf[i] != ',' && buf[i] != '\0'; ++i) {
176 | if (!isdigit(buf[i]) || i > MAX_DIMENSION_LEN) return 0;
177 | num[i] = buf[i];
178 | }
179 | num[i] = '\0';
180 | *numlen = i;
181 |
182 | return (uint32_t)atoi(num);
183 | }
184 |
185 | static uint8_t *createRawBitmapData(MMBitmapRef bitmap)
186 | {
187 | uint8_t *raw = calloc(STR_BYTES_PER_PIXEL, bitmap->width * bitmap->height);
188 | size_t y;
189 |
190 | for (y = 0; y < bitmap->height; ++y) {
191 | /* No padding is added to string bitmaps. */
192 | const size_t rowOffset = y * bitmap->width * STR_BYTES_PER_PIXEL;
193 | size_t x;
194 | for (x = 0; x < bitmap->width; ++x) {
195 | /* Copy in BGR format. */
196 | const size_t colOffset = x * STR_BYTES_PER_PIXEL;
197 | uint8_t *dest = raw + rowOffset + colOffset;
198 | MMRGBColor *srcColor = MMRGBColorRefAtPoint(bitmap, x, y);
199 | dest[0] = srcColor->blue;
200 | dest[1] = srcColor->green;
201 | dest[2] = srcColor->red;
202 | }
203 | }
204 |
205 | return raw;
206 | }
207 |
--------------------------------------------------------------------------------
/src/str_io.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef STR_IO_H
3 | #define STR_IO_H
4 |
5 | #include "MMBitmap.h"
6 | #include "io.h"
7 | #include
8 |
9 |
10 | enum _MMBMPStringError {
11 | kMMBMPStringGenericError = 0,
12 | kMMBMPStringInvalidHeaderError,
13 | kMMBMPStringDecodeError,
14 | kMMBMPStringDecompressError,
15 | kMMBMPStringSizeError, /* Size does not match header. */
16 | MMMBMPStringEncodeError,
17 | kMMBMPStringCompressError
18 | };
19 |
20 | typedef MMIOError MMBMPStringError;
21 |
22 | /* Creates a 24-bit bitmap from a compressed, printable string.
23 | *
24 | * String should be in the format: "b[width],[height],[data]",
25 | * where [width] and [height] are the image width & height, and [data]
26 | * is the raw image data run through zlib_compress() and base64_encode().
27 | *
28 | * Returns NULL on error; follows the Create Rule (that is, the caller is
29 | * responsible for destroy'()ing object).
30 | * If |error| is non-NULL, it will be set to the error code on return.
31 | */
32 | MMBitmapRef createMMBitmapFromString(const uint8_t *buffer, size_t buflen,
33 | MMBMPStringError *error);
34 |
35 | /* Inverse of createMMBitmapFromString().
36 | *
37 | * Creates string in the format: "b[width],[height],[data]", where [width] and
38 | * [height] are the image width & height, and [data] is the raw image data run
39 | * through zlib_compress() and base64_encode().
40 | *
41 | * Returns NULL on error, or new string on success (to be free'()d by caller).
42 | * If |error| is non-NULL, it will be set to the error code on return.
43 | */
44 | uint8_t *createStringFromMMBitmap(MMBitmapRef bitmap, MMBMPStringError *error);
45 |
46 | /* Returns description of given error code.
47 | * Returned string is constant and hence should not be freed. */
48 | const char *MMBitmapStringErrorString(MMBMPStringError err);
49 |
50 | #endif /* STR_IO_H */
51 |
--------------------------------------------------------------------------------
/src/types.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef TYPES_H
3 | #define TYPES_H
4 |
5 | #include "os.h"
6 | #include "inline_keywords.h" /* For H_INLINE */
7 | #include
8 | #include
9 |
10 | /* Some generic, cross-platform types. */
11 |
12 | struct _MMPoint {
13 | size_t x;
14 | size_t y;
15 | };
16 |
17 | typedef struct _MMPoint MMPoint;
18 |
19 |
20 | struct _MMSignedPoint {
21 | int32_t x;
22 | int32_t y;
23 | };
24 |
25 | typedef struct _MMSignedPoint MMSignedPoint;
26 |
27 | struct _MMSize {
28 | size_t width;
29 | size_t height;
30 | };
31 |
32 | typedef struct _MMSize MMSize;
33 |
34 | struct _MMRect {
35 | MMPoint origin;
36 | MMSize size;
37 | };
38 |
39 | typedef struct _MMRect MMRect;
40 |
41 | H_INLINE MMPoint MMPointMake(size_t x, size_t y)
42 | {
43 | MMPoint point;
44 | point.x = x;
45 | point.y = y;
46 | return point;
47 | }
48 |
49 | H_INLINE MMSignedPoint MMSignedPointMake(int32_t x, int32_t y)
50 | {
51 | MMSignedPoint point;
52 | point.x = x;
53 | point.y = y;
54 | return point;
55 | }
56 |
57 | H_INLINE MMSize MMSizeMake(size_t width, size_t height)
58 | {
59 | MMSize size;
60 | size.width = width;
61 | size.height = height;
62 | return size;
63 | }
64 |
65 | H_INLINE MMRect MMRectMake(size_t x, size_t y, size_t width, size_t height)
66 | {
67 | MMRect rect;
68 | rect.origin = MMPointMake(x, y);
69 | rect.size = MMSizeMake(width, height);
70 | return rect;
71 | }
72 |
73 | #define MMPointZero MMPointMake(0, 0)
74 |
75 | #if defined(IS_MACOSX)
76 |
77 | #define CGPointFromMMPoint(p) CGPointMake((CGFloat)(p).x, (CGFloat)(p).y)
78 | #define MMPointFromCGPoint(p) MMPointMake((size_t)(p).x, (size_t)(p).y)
79 |
80 | #define CGPointFromMMSignedPoint(p) CGPointMake((CGFloat)(p).x, (CGFloat)(p).y)
81 | #define MMSignedPointFromCGPoint(p) MMPointMake((int32_t)(p).x, (int32_t)(p).y)
82 |
83 | #elif defined(IS_WINDOWS)
84 |
85 | #define MMPointFromPOINT(p) MMPointMake((size_t)p.x, (size_t)p.y)
86 |
87 | #endif
88 |
89 | #endif /* TYPES_H */
90 |
--------------------------------------------------------------------------------
/src/xdisplay.c:
--------------------------------------------------------------------------------
1 | #include "xdisplay.h"
2 | #include /* For fputs() */
3 | #include /* For atexit() */
4 |
5 | static Display *mainDisplay = NULL;
6 | static int registered = 0;
7 | static char *displayName = ":0.0";
8 | static int hasDisplayNameChanged = 0;
9 |
10 | Display *XGetMainDisplay(void)
11 | {
12 | /* Close the display if displayName has changed */
13 | if (hasDisplayNameChanged) {
14 | XCloseMainDisplay();
15 | hasDisplayNameChanged = 0;
16 | }
17 |
18 | if (mainDisplay == NULL) {
19 | /* First try the user set displayName */
20 | mainDisplay = XOpenDisplay(displayName);
21 |
22 | /* Then try using environment variable DISPLAY */
23 | if (mainDisplay == NULL) {
24 | mainDisplay = XOpenDisplay(NULL);
25 | }
26 |
27 | if (mainDisplay == NULL) {
28 | fputs("Could not open main display\n", stderr);
29 | } else if (!registered) {
30 | atexit(&XCloseMainDisplay);
31 | registered = 1;
32 | }
33 | }
34 |
35 | return mainDisplay;
36 | }
37 |
38 | void XCloseMainDisplay(void)
39 | {
40 | if (mainDisplay != NULL) {
41 | XCloseDisplay(mainDisplay);
42 | mainDisplay = NULL;
43 | }
44 | }
45 |
46 | char *getXDisplay(void)
47 | {
48 | return displayName;
49 | }
50 |
51 | void setXDisplay(char *name)
52 | {
53 | displayName = strdup(name);
54 | hasDisplayNameChanged = 1;
55 | }
56 |
--------------------------------------------------------------------------------
/src/xdisplay.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef XDISPLAY_H
3 | #define XDISPLAY_H
4 |
5 | #include
6 |
7 | /* Returns the main display, closed either on exit or when closeMainDisplay()
8 | * is invoked. This removes a bit of the overhead of calling XOpenDisplay() &
9 | * XCloseDisplay() everytime the main display needs to be used.
10 | *
11 | * Note that this is almost certainly not thread safe. */
12 | Display *XGetMainDisplay(void);
13 |
14 | /* Closes the main display if it is open, or does nothing if not. */
15 | void XCloseMainDisplay(void);
16 |
17 | #ifdef __cplusplus
18 | extern "C"
19 | {
20 | #endif
21 |
22 | char *getXDisplay(void);
23 | void setXDisplay(char *name);
24 |
25 | #ifdef __cplusplus
26 | }
27 | #endif
28 |
29 | #endif /* XDISPLAY_H */
30 |
--------------------------------------------------------------------------------
/src/zlib_util.c:
--------------------------------------------------------------------------------
1 | #include "zlib_util.h"
2 | #include
3 | #include /* fprintf() */
4 | #include /* malloc() */
5 | #include
6 |
7 | #define ZLIB_CHUNK (16 * 1024)
8 |
9 | uint8_t *zlib_decompress(const uint8_t *buf, size_t *len)
10 | {
11 | size_t output_size = ZLIB_CHUNK;
12 | uint8_t *output = malloc(output_size);
13 | int err;
14 | z_stream zst;
15 |
16 | /* Sanity check */
17 | if (output == NULL) return NULL;
18 | assert(buf != NULL);
19 |
20 | /* Set inflate state */
21 | zst.zalloc = Z_NULL;
22 | zst.zfree = Z_NULL;
23 | zst.opaque = Z_NULL;
24 | zst.next_out = (Byte *)output;
25 | zst.next_in = (Byte *)buf;
26 | zst.avail_out = ZLIB_CHUNK;
27 |
28 | if (inflateInit(&zst) != Z_OK) goto error;
29 |
30 | /* Decompress input buffer */
31 | do {
32 | if ((err = inflate(&zst, Z_NO_FLUSH)) == Z_OK) { /* Need more memory */
33 | zst.avail_out = (uInt)output_size;
34 |
35 | /* Double size each time to avoid calls to realloc() */
36 | output_size <<= 1;
37 | output = realloc(output, output_size + 1);
38 | if (output == NULL) return NULL;
39 |
40 | zst.next_out = (Byte *)(output + zst.avail_out);
41 | } else if (err != Z_STREAM_END) { /* Error decompressing */
42 | if (zst.msg != NULL) {
43 | fprintf(stderr, "Could not decompress data: %s\n", zst.msg);
44 | }
45 | inflateEnd(&zst);
46 | goto error;
47 | }
48 | } while (err != Z_STREAM_END);
49 |
50 | if (len != NULL) *len = zst.total_out;
51 | if (inflateEnd(&zst) != Z_OK) goto error;
52 | return output; /* To be free()'d by caller */
53 |
54 | error:
55 | if (output != NULL) free(output);
56 | return NULL;
57 | }
58 |
59 | uint8_t *zlib_compress(const uint8_t *buf, const size_t buflen, int level,
60 | size_t *len)
61 | {
62 | z_stream zst;
63 | uint8_t *output = NULL;
64 |
65 | /* Sanity check */
66 | assert(buf != NULL);
67 | assert(len != NULL);
68 | assert(level <= 9 && level >= 0);
69 |
70 | zst.avail_out = (uInt)((buflen + (buflen / 10)) + 12);
71 | output = malloc(zst.avail_out);
72 | if (output == NULL) return NULL;
73 |
74 | /* Set deflate state */
75 | zst.zalloc = Z_NULL;
76 | zst.zfree = Z_NULL;
77 | zst.next_out = (Byte *)output;
78 | zst.next_in = (Byte *)buf;
79 | zst.avail_in = (uInt)buflen;
80 |
81 | if (deflateInit(&zst, level) != Z_OK) goto error;
82 |
83 | /* Compress input buffer */
84 | if (deflate(&zst, Z_FINISH) != Z_STREAM_END) {
85 | if (zst.msg != NULL) {
86 | fprintf(stderr, "Could not compress data: %s\n", zst.msg);
87 | }
88 | deflateEnd(&zst);
89 | goto error;
90 | }
91 |
92 | if (len != NULL) *len = zst.total_out;
93 | if (deflateEnd(&zst) != Z_OK) goto error;
94 | return output; /* To be free()'d by caller */
95 |
96 | error:
97 | if (output != NULL) free(output);
98 | return NULL;
99 | }
100 |
--------------------------------------------------------------------------------
/src/zlib_util.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #ifndef ZLIB_UTIL_H
3 | #define ZLIB_UTIL_H
4 |
5 | #include
6 |
7 | #if defined(_MSC_VER)
8 | #include "ms_stdint.h"
9 | #else
10 | #include
11 | #endif
12 |
13 | /* Attempts to decompress given deflated NUL-terminated buffer.
14 | *
15 | * If successful and |len| is not NULL, |len| will be set to the number of
16 | * bytes in the returned buffer.
17 | * Returns new string to be free()'d by caller, or NULL on error. */
18 | uint8_t *zlib_decompress(const uint8_t *buf, size_t *len);
19 |
20 | /* Attempt to compress given buffer.
21 | *
22 | * The compression level is passed directly to zlib: it must between 0 and 9,
23 | * where 1 gives best speed, 9 gives best compression, and 0 gives no
24 | * compression at all.
25 | *
26 | * If successful and |len| is not NULL, |len| will be set to the number of
27 | * bytes in the returned buffer.
28 | * Returns new string to be free()'d by caller, or NULL on error. */
29 | uint8_t *zlib_compress(const uint8_t *buf, const size_t buflen, int level,
30 | size_t *len);
31 |
32 | #endif /* ZLIB_UTIL_H */
33 |
--------------------------------------------------------------------------------
/test/bitmap.js:
--------------------------------------------------------------------------------
1 | var robot = require('..');
2 |
3 | describe('Bitmap', () => {
4 | var params = {
5 | 'width': 'number',
6 | 'height': 'number',
7 | 'byteWidth': 'number',
8 | 'bitsPerPixel': 'number',
9 | 'bytesPerPixel': 'number',
10 | 'image': 'object'
11 | };
12 |
13 | it('Get a bitmap and check the parameters.', function() {
14 | var img = robot.screen.capture();
15 |
16 | for (var x in params)
17 | {
18 | expect(typeof img[x]).toEqual(params[x]);
19 | }
20 | });
21 |
22 | it('Get a bitmap of a specific size.', function()
23 | {
24 | var size = 10;
25 | var img = robot.screen.capture(0, 0, size, size);
26 |
27 | // Support for higher density screens.
28 | var multi = img.width / size;
29 | var size = size * multi;
30 | expect(img.height).toEqual(size);
31 | expect(img.width).toEqual(size);
32 | });
33 |
34 | it('Get a bitmap and make sure the colorAt works as expected.', function()
35 | {
36 | var img = robot.screen.capture();
37 | var hex = img.colorAt(0, 0);
38 |
39 | // t.ok(.it(hex), "colorAt returned valid hex.");
40 | expect(hex).toMatch(/^[0-9A-F]{6}$/i);
41 |
42 | var screenSize = robot.getScreenSize();
43 | var width = screenSize.width;
44 | var height = screenSize.height;
45 |
46 | // Support for higher density screens.
47 | var multi = img.width / width;
48 | width = width * multi;
49 | height = height * multi;
50 | expect(() => img.colorAt(0, height)).toThrowError(/are outside the bitmap/);
51 | expect(() => img.colorAt(0, height-1)).not.toThrow();
52 | expect(() => img.colorAt(width, 0)).toThrowError(/are outside the bitmap/);
53 | expect(() => img.colorAt(9999999999999, 0)).toThrowError(/are outside the bitmap/);
54 | expect(() => img.colorAt(0, 9999999999999)).toThrowError(/are outside the bitmap/);
55 | });
56 | });
57 |
--------------------------------------------------------------------------------
/test/integration/keyboard.js:
--------------------------------------------------------------------------------
1 | /* jshint esversion: 6 */
2 | var robot = require('../..');
3 | var targetpractice = require('targetpractice/index.js');
4 | var os = require('os');
5 |
6 | robot.setMouseDelay(100);
7 |
8 | var target, elements;
9 |
10 | describe('Integration/Keyboard', () => {
11 | beforeEach(done => {
12 | target = targetpractice.start();
13 | target.once('elements', message => {
14 | elements = message;
15 | done();
16 | });
17 | });
18 |
19 | afterEach(() => {
20 | targetpractice.stop();
21 | target = null;
22 | });
23 |
24 | it('types', done => {
25 | const stringToType = 'hello world';
26 | // Currently Target Practice waits for the "user" to finish typing before sending the event.
27 | target.once('type', element => {
28 | expect(element.id).toEqual('input_1');
29 | expect(element.text).toEqual(stringToType);
30 | done();
31 | });
32 |
33 | const input_1 = elements.input_1;
34 | robot.moveMouse(input_1.x, input_1.y);
35 | robot.mouseClick();
36 | robot.typeString(stringToType);
37 | });
38 | });
39 |
--------------------------------------------------------------------------------
/test/integration/mouse.js:
--------------------------------------------------------------------------------
1 | /* jshint esversion: 6 */
2 | var robot = require('../..');
3 | var targetpractice = require('targetpractice/index.js');
4 | var os = require('os');
5 |
6 | robot.setMouseDelay(100);
7 |
8 | var target, elements;
9 |
10 | describe('Integration/Mouse', () => {
11 | beforeEach(done => {
12 | target = targetpractice.start();
13 | target.once('elements', message => {
14 | elements = message;
15 | done();
16 | });
17 | });
18 |
19 | afterEach(() => {
20 | targetpractice.stop();
21 | target = null;
22 | });
23 |
24 | it('clicks', done => {
25 | // Alright we got a click event, did we click the button we wanted?
26 | target.once('click', function(e)
27 | {
28 | expect(e.id).toEqual('button_1');
29 | expect(e.type).toEqual('click');
30 | done();
31 | });
32 |
33 | // For this test we want a button.
34 | var button_1 = elements.button_1;
35 | // Click it!
36 | robot.moveMouse(button_1.x, button_1.y);
37 | robot.mouseClick();
38 | });
39 |
40 | it('scrolls vertically', done => {
41 | target.once('scroll', element => {
42 | /**
43 | * TODO: This is gross! The scroll distance is different for each OS. I want
44 | * to look into this further, but at least these numbers are consistent.
45 | */
46 | var expectedScroll;
47 | switch(os.platform()) {
48 | case 'linux':
49 | expectedScroll = 180;
50 | break;
51 | case 'win32':
52 | expectedScroll = 8;
53 | break;
54 | default:
55 | expectedScroll = 10;
56 | }
57 | expect(element.id).toEqual('textarea_1');
58 | expect(element.scroll_y).toEqual(expectedScroll);
59 | done();
60 | });
61 |
62 | var textarea_1 = elements.textarea_1;
63 | robot.moveMouse(textarea_1.x, textarea_1.y);
64 | robot.mouseClick();
65 | robot.scrollMouse(0, -10);
66 | });
67 |
68 | it('scrolls horizontally', done => {
69 | target.once('scroll', element => {
70 | /**
71 | * TODO: This is gross! The scroll distance is different for each OS. I want
72 | * to look into this further, but at least these numbers are consistent.
73 | */
74 | var expectedScroll;
75 | switch(os.platform()) {
76 | case 'linux':
77 | expectedScroll = 530;
78 | break;
79 | case 'win32':
80 | expectedScroll = 8;
81 | break;
82 | default:
83 | expectedScroll = 10;
84 | }
85 | expect(element.id).toEqual('textarea_1');
86 | expect(element.scroll_x).toEqual(expectedScroll);
87 | done();
88 | });
89 |
90 | var textarea_1 = elements.textarea_1;
91 | robot.moveMouse(textarea_1.x, textarea_1.y);
92 | robot.mouseClick();
93 | robot.scrollMouse(-10, 0);
94 | });
95 | });
96 |
--------------------------------------------------------------------------------
/test/integration/screen.js:
--------------------------------------------------------------------------------
1 | /* jshint esversion: 6 */
2 | var robot = require('../..');
3 | var targetpractice = require('targetpractice/index.js');
4 | var elements, target;
5 |
6 | describe('Integration/Screen', () => {
7 | beforeEach(done => {
8 | target = targetpractice.start();
9 | target.once('elements', message => {
10 | elements = message;
11 | done();
12 | });
13 | });
14 |
15 | afterEach(() => {
16 | targetpractice.stop();
17 | target = null;
18 | });
19 |
20 | it('reads a pixel color', (done) => {
21 | const maxDelay = 1000
22 | jasmine.DEFAULT_TIMEOUT_INTERVAL = maxDelay + 1000
23 | const expected = 'c0ff33'
24 | const color_1 = elements.color_1;
25 | const sleepTime = robot.getPixelColor(color_1.x, color_1.y) === expected ? 0
26 | : maxDelay
27 |
28 | setTimeout(() => {
29 | const color = robot.getPixelColor(color_1.x, color_1.y);
30 | expect(color).toEqual(expected);
31 | done()
32 | }, sleepTime)
33 | });
34 | });
35 |
--------------------------------------------------------------------------------
/test/keyboard.js:
--------------------------------------------------------------------------------
1 | var robot = require('..');
2 | var os = require('os');
3 |
4 | // TODO: Need tests for keyToggle, typeString, typeStringDelayed, and setKeyboardDelay.
5 |
6 | describe('Keyboard', () => {
7 | it('Tap a key.', function() {
8 | expect(() => robot.keyTap('a')).not.toThrow();
9 | expect(() => robot.keyTap('a', 'control')).not.toThrow();
10 | expect(() => robot.keyTap()).toThrowError(/Invalid number/);
11 | });
12 |
13 | // This it won't fail if there's an issue, but it will help you identify an issue if ran locally.
14 | it('Tap all keys.', function()
15 | {
16 | var chars = 'abcdefghijklmnopqrstuvwxyz1234567890,./;\'[]\\'.split('');
17 |
18 | for (var x in chars)
19 | {
20 | expect(() => robot.keyTap(chars[x])).not.toThrow();
21 | }
22 | });
23 |
24 | // This it won't fail if there's an issue, but it will help you identify an issue if ran locally.
25 | it('Tap all numpad keys.', function()
26 | {
27 | var nums = '0123456789'.split('');
28 |
29 | for (var x in nums)
30 | {
31 | if (os.platform() === 'linux')
32 | {
33 | expect(() => robot.keyTap('numpad_' + nums[x])).toThrowError(/Invalid key code/);
34 | }
35 | else
36 | {
37 | expect(() => robot.keyTap('numpad_' + nums[x])).not.toThrow();
38 | }
39 | }
40 | });
41 | });
42 |
43 | test('Tap a Unicode character.', function(t)
44 | {
45 | t.plan(7);
46 | t.ok(robot.unicodeTap("r".charCodeAt(0)) === 1, 'successfully tapped "r".');
47 | t.ok(robot.unicodeTap("ά".charCodeAt(0)) === 1, 'successfully tapped "ά".');
48 | t.ok(robot.unicodeTap("ö".charCodeAt(0)) === 1, 'successfully tapped "ö".');
49 | t.ok(robot.unicodeTap("ち".charCodeAt(0)) === 1, 'successfully tapped "ち".');
50 | t.ok(robot.unicodeTap("嗨".charCodeAt(0)) === 1, 'successfully tapped "嗨".');
51 | t.ok(robot.unicodeTap("ఝ".charCodeAt(0)) === 1, 'successfully tapped "ఝ".');
52 |
53 | t.throws(function()
54 | {
55 | robot.unicodeTap();
56 | }, /Invalid character typed./, 'tap nothing.');
57 | });
58 |
59 | test('Test Key Toggle.', function(t)
60 | {
61 | t.plan(4);
62 |
63 | t.ok(robot.keyToggle("a", "down") === 1, 'Successfully pressed a.');
64 | t.ok(robot.keyToggle("a", "up") === 1, 'Successfully released a.');
65 |
66 | t.throws(function()
67 | {
68 | t.ok(robot.keyToggle("ά", "down") === 1, 'Successfully pressed ά.');
69 | t.ok(robot.keyToggle("ά", "up") === 1, 'Successfully released ά.');
70 | }, /Invalid key code specified./, 'exception tapping ά.');
71 |
72 | t.throws(function()
73 | {
74 | t.ok(robot.keyToggle("嗨", "down") === 1, 'Successfully pressed 嗨.');
75 | t.ok(robot.keyToggle("嗨", "up") === 1, 'Successfully released 嗨.');
76 | }, /Invalid key code specified./, 'exception tapping 嗨.');
77 | });
78 |
79 | test('Type Ctrl+Shift+RightArrow.', function(t)
80 | {
81 | t.plan(2);
82 |
83 | var modifiers = []
84 | modifiers.push('shift')
85 | modifiers.push('control')
86 |
87 | t.ok(robot.keyToggle("right", "down", modifiers) === 1, 'Successfully pressed Ctrl+Shift+RightArrow.');
88 | t.ok(robot.keyToggle("right", "up", modifiers) === 1, 'Successfully released Ctrl+Shift+RightArrow.');
89 | });
90 |
91 | test('Type a string.', function(t)
92 | {
93 | t.plan(2);
94 | t.ok(robot.typeString("Typed rάöち嗨ఝ 1") === 1, 'successfully typed "Typed rάöち嗨ఝ 1".');
95 |
96 | t.throws(function()
97 | {
98 | t.ok(robot.typeString() === 1, 'Successfully typed nothing.');
99 | }, /Invalid number of arguments./, 'exception tapping nothing.');
100 | });
101 |
102 | test('Type a string with delay.', function(t)
103 | {
104 | t.plan(2);
105 |
106 | // 10 characters per minute -> 3 seconds to write the whole sentence here.
107 | t.ok(robot.typeStringDelayed("Typed rάöち嗨ఝ with delay 1", 600) === 1, 'successfully typed with delay "Typed rάöち嗨ఝ with delay 1".');
108 |
109 | t.throws(function()
110 | {
111 | t.ok(robot.typeStringDelayed() === 1, 'Successfully typed nothing.');
112 | }, /Invalid number of arguments./, 'exception tapping nothing.');
113 | });
114 |
--------------------------------------------------------------------------------
/test/mouse.js:
--------------------------------------------------------------------------------
1 | var robot = require('..');
2 | var lastKnownPos, currentPos;
3 |
4 | //Increase delay to help it reliability.
5 | robot.setMouseDelay(100);
6 |
7 | describe('Mouse', () => {
8 | it('Get the initial mouse position.', function()
9 | {
10 | expect(lastKnownPos = robot.getMousePos()).toBeTruthy();
11 | expect(lastKnownPos.x !== undefined).toBeTruthy();
12 | expect(lastKnownPos.y !== undefined).toBeTruthy();
13 | });
14 |
15 | it('Move the mouse.', function()
16 | {
17 | lastKnownPos = robot.moveMouse(0, 0);
18 | expect(robot.moveMouse(100, 100) === 1).toBeTruthy();
19 | currentPos = robot.getMousePos();
20 | expect(currentPos.x === 100).toBeTruthy();
21 | expect(currentPos.y === 100).toBeTruthy();
22 |
23 | expect(function()
24 | {
25 | robot.moveMouse(0, 1, 2, 3);
26 | }).toThrowError(/Invalid number/);
27 |
28 | expect(function()
29 | {
30 | robot.moveMouse(0);
31 | }).toThrowError(/Invalid number/);
32 |
33 | expect(robot.moveMouse("0", "0") === 1).toBeTruthy();
34 |
35 | });
36 |
37 | it('Move the mouse smoothly.', function()
38 | {
39 | lastKnownPos = robot.moveMouseSmooth(0, 0);
40 | expect(robot.moveMouseSmooth(100, 100) === 1).toBeTruthy();
41 | currentPos = robot.getMousePos();
42 | expect(currentPos.x).toEqual(100);
43 | expect(currentPos.y).toEqual(100);
44 |
45 | expect(function()
46 | {
47 | robot.moveMouseSmooth(0, 1, 2, 3);
48 | }).toThrowError(/Invalid number/);
49 |
50 | expect(function()
51 | {
52 | robot.moveMouseSmooth(0);
53 | }).toThrowError(/Invalid number/);
54 |
55 | expect(robot.moveMouseSmooth("0", "0") === 1).toBeTruthy();
56 |
57 | });
58 |
59 | it('Click the mouse.', function()
60 | {
61 | expect(robot.mouseClick()).toBeTruthy();
62 | expect(robot.mouseClick("left") === 1).toBeTruthy();
63 | expect(robot.mouseClick("middle") === 1).toBeTruthy();
64 | expect(robot.mouseClick("right") === 1).toBeTruthy();
65 |
66 | expect(robot.mouseClick("left", 1)).toBeTruthy();
67 |
68 | expect(function()
69 | {
70 | robot.mouseClick("party");
71 | }).toThrowError(/Invalid mouse/);
72 |
73 | expect(function()
74 | {
75 | robot.mouseClick("0");
76 | }).toThrowError(/Invalid mouse/);
77 |
78 | expect(function()
79 | {
80 | robot.mouseClick("left", 0, "it");
81 | }).toThrowError(/Invalid number/);
82 |
83 | });
84 |
85 | it('Drag the mouse.', function()
86 | {
87 |
88 | expect(robot.dragMouse(5, 5) === 1).toBeTruthy();
89 |
90 | expect(function()
91 | {
92 | robot.dragMouse(0);
93 | }).toThrowError(/Invalid number/);
94 |
95 | expect(function()
96 | {
97 | robot.dragMouse(1, 1, "left", 5);
98 | }).toThrowError(/Invalid number/);
99 |
100 | expect(function()
101 | {
102 | robot.dragMouse(2, 2, "party");
103 | }).toThrowError(/Invalid mouse/);
104 |
105 | });
106 |
107 | it('Mouse scroll.', function()
108 | {
109 | expect(lastKnownPos = robot.getMousePos()).toBeTruthy();
110 | expect(robot.mouseClick() === 1).toBeTruthy();
111 | expect(robot.scrollMouse(0, 1 * 120) === 1).toBeTruthy();
112 | expect(robot.scrollMouse(0, 20 * 120) === 1).toBeTruthy();
113 | expect(robot.scrollMouse(0, -5 * 120) === 1).toBeTruthy();
114 | expect(robot.scrollMouse(1 * 120, 0) === 1).toBeTruthy();
115 | expect(robot.scrollMouse(20 * 120, 0) === 1).toBeTruthy();
116 | expect(robot.scrollMouse(-5 * 120, 0) === 1).toBeTruthy();
117 | expect(robot.scrollMouse(-5 * 120, -5 * 120) === 1).toBeTruthy();
118 | });
119 |
120 | it('Mouse Toggle', function()
121 | {
122 | expect(lastKnownPos = robot.getMousePos()).toBeTruthy();
123 | expect(robot.mouseToggle('up', 'right') === 1).toBeTruthy();
124 | });
125 | });
126 |
--------------------------------------------------------------------------------
/test/screen.js:
--------------------------------------------------------------------------------
1 | var robot = require('..');
2 | var pixelColor, screenSize;
3 |
4 | describe('Screen', () => {
5 | it('Get pixel color.', function()
6 | {
7 | expect(pixelColor = robot.getPixelColor(5, 5)).toBeTruthy();
8 | expect(pixelColor !== undefined).toBeTruthy();
9 | expect(pixelColor.length === 6).toBeTruthy();
10 | expect(/^[0-9A-F]{6}$/i.test(pixelColor)).toBeTruthy();
11 |
12 | expect(function()
13 | {
14 | robot.getPixelColor(9999999999999, 9999999999999);
15 | }).toThrowError(/outside the main screen/);
16 |
17 | expect(function()
18 | {
19 | robot.getPixelColor(-1, -1);
20 | }).toThrowError(/outside the main screen/);
21 |
22 | expect(function()
23 | {
24 | robot.getPixelColor(0);
25 | }).toThrowError(/Invalid number/);
26 |
27 | expect(function()
28 | {
29 | robot.getPixelColor(1, 2, 3);
30 | }).toThrowError(/Invalid number/);
31 | });
32 |
33 | it('Get screen size.', function()
34 | {
35 | expect(screenSize = robot.getScreenSize()).toBeTruthy();
36 | expect(screenSize.width !== undefined).toBeTruthy();
37 | expect(screenSize.height !== undefined).toBeTruthy();
38 | });
39 | });
40 |
--------------------------------------------------------------------------------