├── docs ├── kanji.gif ├── qt6fast.png ├── kanjiNewUI.gif ├── snaaaaaaake.gif ├── usePenAsMouse.png ├── followScreenOnBigCards.png └── dontUseSoftwareRendering.png ├── AnkiDraw ├── manifest.json ├── PerfectFreehand.js ├── Caligrapher.js └── __init__.py ├── .gitmodules ├── .gitignore ├── README.md ├── index.html └── LICENSE /docs/kanji.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/kanji.gif -------------------------------------------------------------------------------- /docs/qt6fast.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/qt6fast.png -------------------------------------------------------------------------------- /docs/kanjiNewUI.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/kanjiNewUI.gif -------------------------------------------------------------------------------- /docs/snaaaaaaake.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/snaaaaaaake.gif -------------------------------------------------------------------------------- /docs/usePenAsMouse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/usePenAsMouse.png -------------------------------------------------------------------------------- /docs/followScreenOnBigCards.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/followScreenOnBigCards.png -------------------------------------------------------------------------------- /docs/dontUseSoftwareRendering.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rytisgit/Anki-StylusDraw/HEAD/docs/dontUseSoftwareRendering.png -------------------------------------------------------------------------------- /AnkiDraw/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "package": "AnkiDraw - Draw and write using mouse and stylus with pressure support", 3 | "name": "AnkiDraw - Draw and write using mouse and stylus with pressure support" 4 | } 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "caligrapher"] 2 | path = caligrapher 3 | url = https://github.com/Rytisgit/Calligrapher.git 4 | branch = prepare_for_integration 5 | [submodule "perfectFreehand"] 6 | path = perfectFreehand 7 | url = https://github.com/Rytisgit/perfect-freehand.git 8 | branch = compiled_js_for_import 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | /.vscode/* 106 | .DS_Store 107 | AnkiDraw.zip 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Anki-StylusDraw 2 | Initially based on the Anki-TouchScreen addon, updated ui and added pressure pen/stylus capabilities, perfect freehand(line smoothing) and calligrapher functionality. 3 | 4 | Website to test the drawing functionality: https://rytisgit.github.io/Anki-StylusDraw/ 5 | 6 | 7 | Draw Demonstration 8 |
9 | 10 | # Changes 11 | * Added background color selection 12 | * Added follow screen mode(menu option) and small canvas mode(alt + b) to increase drawing speed on very big cards 13 | * Added toolbar location configuration and other small fixes. 14 | * Fixed "resize not defined" error. Thanks huandney. 15 | * Updated UI, add option to convert dots, hide cursor and ui while drawing. Thanks rin-w 16 | * Added Perfect Freehand mode(https://github.com/steveruizok/perfect-freehand) 17 | * Added Calligrapher mode(https://github.com/atomanyih/Calligrapher) 18 | * Added pressure sensitivity 19 | * Increased drawing speed 20 | * Added , for showing/hiding, . for clearing, alt + c for calligrapher mode and alt + x for perfect freehand mode 21 | * Added standalone website to test drawing 22 | * Work around a Windows Pen bug which makes 2 primary pointers appear when drawing in Anki 23 | 24 | ## Hardware 25 | Tested to work with a Huion H1161, Windows Pen enabled. 26 | ### For best experience: 27 | * #### don't use software rendering(enable hardware acceleration) 28 | * #### turn on use pen as a mouse with Windows Pen 29 | * #### if drawing is slow on big cards turn on follow mode or small canvas 30 | https://docs.ankiweb.net/platform/windows/display-issues.html 31 | #### Run `echo auto > %APPDATA%\Anki2\gldriver6` in cmd for Qt6 32 | Switch away from Software in Qt6 33 | 34 | 35 |
Qt5 rendering change Switch away from Software in Qt5 Check use pen as mouse in Windows pen settings
36 | Turn On Follow when scrolling or small canvas if drawing is slow on very big cards 37 | 38 | # Old Description 39 | 40 | Implements same drawing/writing mechanism as in AnkiDroid. Your writing is NOT intended to remain on the cards after review - same as in AnkiDroid. 41 | 42 | Use the menu `View` → `TouchScreen` to activate/change settings. 43 | 44 | Use Ctrl + R to toggle the touchscreen. 45 | 46 | Use icons which will show up in the top right corner of the review screen to temporarily hide/clean the board. 47 | Enjoy! 48 | 49 | Warning: the version for Anki 2.0 has limited functionality, and may sometimes not work as expected; since the release of Anki 2.1, the old version is not supported. 50 | 51 | 52 | #### Changelog: 53 | - 0.2.6 - make "undo" action available under Alt + Z 54 | - 0.2.4 - add support for enhanced image occlusion, add a fix for "a double click bug" by LaucianK 55 | - 0.2.3 - bug fix release, improvements to undo button, styling and performance 56 | - 0.2.1 - minor fix for the buttons/canvas positioning 57 | - 0.2 - added "undo" option, improved the support of long cards plus other minor improvements 58 | 59 | #### Disclaimer 60 | Important parts of Javascript code were inspired by creativejs tutorial. I recommend you check out the resource if you are interested in learning JS. 61 | 62 | This add-on works well with Anki Night Mode. 63 | 64 | #### For developers 65 | You are more than welcome to contribute! While I may not be able to support every user of this addon, I will do my best to help any developer willing to open PR implementing new features or fixing bugs. 66 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 |
14 |
15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 83 | 84 | -------------------------------------------------------------------------------- /AnkiDraw/PerfectFreehand.js: -------------------------------------------------------------------------------- 1 | /* ------------------------------ PerfectFreehand ------------------------------*/ 2 | /* ------------------------------ GetStroke.js ------------------------------*/ 3 | /** 4 | * ## getStroke 5 | * @description Get an array of points describing a polygon that surrounds the input points. 6 | * @param points An array of points (as `[x, y, pressure]` or `{x, y, pressure}`). Pressure is optional in both cases. 7 | * @param options (optional) An object with options. 8 | * @param options.size The base size (diameter) of the stroke. 9 | * @param options.thinning The effect of pressure on the stroke's size. 10 | * @param options.smoothing How much to soften the stroke's edges. 11 | * @param options.easing An easing function to apply to each point's pressure. 12 | * @param options.simulatePressure Whether to simulate pressure based on velocity. 13 | * @param options.start Cap, taper and easing for the start of the line. 14 | * @param options.end Cap, taper and easing for the end of the line. 15 | * @param options.last Whether to handle the points as a completed stroke. 16 | */ 17 | function getStroke(points, options) { 18 | if (options === void 0) { options = {}; } 19 | return getStrokeOutlinePoints(getStrokePoints(points, options), options); 20 | } 21 | //# sourceMappingURL=getStroke.js.map 22 | var __spreadArray = function (to, from, pack) { 23 | if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { 24 | if (ar || !(i in from)) { 25 | if (!ar) ar = Array.prototype.slice.call(from, 0, i); 26 | ar[i] = from[i]; 27 | } 28 | } 29 | return to.concat(ar || Array.prototype.slice.call(from)); 30 | }; 31 | var min = Math.min, PI = Math.PI; 32 | // This is the rate of change for simulated pressure. It could be an option. 33 | var RATE_OF_PRESSURE_CHANGE = 0.275; 34 | // Browser strokes seem to be off if PI is regular, a tiny offset seems to fix it 35 | var FIXED_PI = PI + 0.0001; 36 | /** 37 | * ## getStrokeOutlinePoints 38 | * @description Get an array of points (as `[x, y]`) representing the outline of a stroke. 39 | * @param points An array of StrokePoints as returned from `getStrokePoints`. 40 | * @param options (optional) An object with options. 41 | * @param options.size The base size (diameter) of the stroke. 42 | * @param options.thinning The effect of pressure on the stroke's size. 43 | * @param options.smoothing How much to soften the stroke's edges. 44 | * @param options.easing An easing function to apply to each point's pressure. 45 | * @param options.simulatePressure Whether to simulate pressure based on velocity. 46 | * @param options.start Cap, taper and easing for the start of the line. 47 | * @param options.end Cap, taper and easing for the end of the line. 48 | * @param options.last Whether to handle the points as a completed stroke. 49 | */ 50 | function getStrokeOutlinePoints(points, options) { 51 | if (options === void 0) { options = {}; } 52 | var _a = options.size, size = _a === void 0 ? 16 : _a, _b = options.smoothing, smoothing = _b === void 0 ? 0.5 : _b, _c = options.thinning, thinning = _c === void 0 ? 0.5 : _c, _d = options.simulatePressure, simulatePressure = _d === void 0 ? true : _d, _e = options.easing, easing = _e === void 0 ? function (t) { return t; } : _e, _f = options.start, start = _f === void 0 ? {} : _f, _g = options.end, end = _g === void 0 ? {} : _g, _h = options.last, isComplete = _h === void 0 ? false : _h; 53 | var _j = start.cap, capStart = _j === void 0 ? true : _j, _k = start.taper, taperStart = _k === void 0 ? 0 : _k, _l = start.easing, taperStartEase = _l === void 0 ? function (t) { return t * (2 - t); } : _l; 54 | var _m = end.cap, capEnd = _m === void 0 ? true : _m, _o = end.taper, taperEnd = _o === void 0 ? 0 : _o, _p = end.easing, taperEndEase = _p === void 0 ? function (t) { return --t * t * t + 1; } : _p; 55 | // We can't do anything with an empty array or a stroke with negative size. 56 | if (points.length === 0 || size <= 0) { 57 | return []; 58 | } 59 | // The total length of the line 60 | var totalLength = points[points.length - 1].runningLength; 61 | // The minimum allowed distance between points (squared) 62 | var minDistance = Math.pow(size * smoothing, 2); 63 | // Our collected left and right points 64 | var leftPts = []; 65 | var rightPts = []; 66 | // Previous pressure (start with average of first five pressures, 67 | // in order to prevent fat starts for every line. Drawn lines 68 | // almost always start slow! 69 | var prevPressure = points.slice(0, 10).reduce(function (acc, curr) { 70 | var pressure = curr.pressure; 71 | if (simulatePressure) { 72 | // Speed of change - how fast should the the pressure changing? 73 | var sp = min(1, curr.distance / size); 74 | // Rate of change - how much of a change is there? 75 | var rp = min(1, 1 - sp); 76 | // Accelerate the pressure 77 | pressure = min(1, acc + (rp - acc) * (sp * RATE_OF_PRESSURE_CHANGE)); 78 | } 79 | return (acc + pressure) / 2; 80 | }, points[0].pressure); 81 | // The current radius 82 | var radius = getStrokeRadius(size, thinning, points[points.length - 1].pressure, easing); 83 | // The radius of the first saved point 84 | var firstRadius = undefined; 85 | // Previous vector 86 | var prevVector = points[0].vector; 87 | // Previous left and right points 88 | var pl = points[0].point; 89 | var pr = pl; 90 | // Temporary left and right points 91 | var tl = pl; 92 | var tr = pr; 93 | // let short = true 94 | /* 95 | Find the outline's left and right points 96 | 97 | Iterating through the points and populate the rightPts and leftPts arrays, 98 | skipping the first and last pointsm, which will get caps later on. 99 | */ 100 | for (var i = 0; i < points.length; i++) { 101 | var pressure = points[i].pressure; 102 | var _q = points[i], point = _q.point, vector = _q.vector, distance = _q.distance, runningLength = _q.runningLength; 103 | // Removes noise from the end of the line 104 | if (i < points.length - 1 && totalLength - runningLength < 3) { 105 | continue; 106 | } 107 | /* 108 | Calculate the radius 109 | 110 | If not thinning, the current point's radius will be half the size; or 111 | otherwise, the size will be based on the current (real or simulated) 112 | pressure. 113 | */ 114 | if (thinning) { 115 | if (simulatePressure) { 116 | // If we're simulating pressure, then do so based on the distance 117 | // between the current point and the previous point, and the size 118 | // of the stroke. Otherwise, use the input pressure. 119 | var sp = min(1, distance / size); 120 | var rp = min(1, 1 - sp); 121 | pressure = min(1, prevPressure + (rp - prevPressure) * (sp * RATE_OF_PRESSURE_CHANGE)); 122 | } 123 | radius = getStrokeRadius(size, thinning, pressure, easing); 124 | } 125 | else { 126 | radius = size / 2; 127 | } 128 | if (firstRadius === undefined) { 129 | firstRadius = radius; 130 | } 131 | /* 132 | Apply tapering 133 | 134 | If the current length is within the taper distance at either the 135 | start or the end, calculate the taper strengths. Apply the smaller 136 | of the two taper strengths to the radius. 137 | */ 138 | var ts = runningLength < taperStart 139 | ? taperStartEase(runningLength / taperStart) 140 | : 1; 141 | var te = totalLength - runningLength < taperEnd 142 | ? taperEndEase((totalLength - runningLength) / taperEnd) 143 | : 1; 144 | radius = Math.max(0.01, radius * Math.min(ts, te)); 145 | /* Add points to left and right */ 146 | // Handle the last point 147 | if (i === points.length - 1) { 148 | var offset_1 = mul(per(vector), radius); 149 | leftPts.push(sub(point, offset_1)); 150 | rightPts.push(add(point, offset_1)); 151 | continue; 152 | } 153 | var nextVector = points[i + 1].vector; 154 | var nextDpr = dpr(vector, nextVector); 155 | /* 156 | Handle sharp corners 157 | 158 | Find the difference (dot product) between the current and next vector. 159 | If the next vector is at more than a right angle to the current vector, 160 | draw a cap at the current point. 161 | */ 162 | if (nextDpr < 0) { 163 | // It's a sharp corner. Draw a rounded cap and move on to the next point 164 | // Considering saving these and drawing them later? So that we can avoid 165 | // crossing future points. 166 | var offset_2 = mul(per(prevVector), radius); 167 | for (var step = 1 / 13, t = 0; t <= 1; t += step) { 168 | tl = rotAround(sub(point, offset_2), point, FIXED_PI * t); 169 | leftPts.push(tl); 170 | tr = rotAround(add(point, offset_2), point, FIXED_PI * -t); 171 | rightPts.push(tr); 172 | } 173 | pl = tl; 174 | pr = tr; 175 | continue; 176 | } 177 | /* 178 | Add regular points 179 | 180 | Project points to either side of the current point, using the 181 | calculated size as a distance. If a point's distance to the 182 | previous point on that side greater than the minimum distance 183 | (or if the corner is kinda sharp), add the points to the side's 184 | points array. 185 | */ 186 | var offset = mul(per(lrp(nextVector, vector, nextDpr)), radius); 187 | tl = sub(point, offset); 188 | if (i <= 1 || dist2(pl, tl) > minDistance) { 189 | leftPts.push(tl); 190 | pl = tl; 191 | } 192 | tr = add(point, offset); 193 | if (i <= 1 || dist2(pr, tr) > minDistance) { 194 | rightPts.push(tr); 195 | pr = tr; 196 | } 197 | // Set variables for next iteration 198 | prevPressure = pressure; 199 | prevVector = vector; 200 | } 201 | /* 202 | Drawing caps 203 | 204 | Now that we have our points on either side of the line, we need to 205 | draw caps at the start and end. Tapered lines don't have caps, but 206 | may have dots for very short lines. 207 | */ 208 | var firstPoint = points[0].point.slice(0, 2); 209 | var lastPoint = points.length > 1 210 | ? points[points.length - 1].point.slice(0, 2) 211 | : add(points[0].point, [1, 1]); 212 | var startCap = []; 213 | var endCap = []; 214 | /* 215 | Draw a dot for very short or completed strokes 216 | 217 | If the line is too short to gather left or right points and if the line is 218 | not tapered on either side, draw a dot. If the line is tapered, then only 219 | draw a dot if the line is both very short and complete. If we draw a dot, 220 | we can just return those points. 221 | */ 222 | if (convertDotStrokes == true && points.length === 1) { 223 | if (!(taperStart || taperEnd) || isComplete) { 224 | var start_1 = prj(firstPoint, uni(per(sub(firstPoint, lastPoint))), -(firstRadius || radius)); 225 | var dotPts = []; 226 | for (var step = 1 / 13, t = step; t <= 1; t += step) { 227 | dotPts.push(rotAround(start_1, firstPoint, FIXED_PI * 2 * t)); 228 | } 229 | return dotPts; 230 | } 231 | } 232 | else { 233 | /* 234 | Draw a start cap 235 | 236 | Unless the line has a tapered start, or unless the line has a tapered end 237 | and the line is very short, draw a start cap around the first point. Use 238 | the distance between the second left and right point for the cap's radius. 239 | Finally remove the first left and right points. :psyduck: 240 | */ 241 | if (taperStart || (taperEnd && points.length === 1)) { 242 | // The start point is tapered, noop 243 | } 244 | else if (capStart) { 245 | // Draw the round cap - add thirteen points rotating the right point around the start point to the left point 246 | for (var step = 1 / 13, t = step; t <= 1; t += step) { 247 | var pt = rotAround(rightPts[0], firstPoint, FIXED_PI * t); 248 | startCap.push(pt); 249 | } 250 | } 251 | else { 252 | // Draw the flat cap - add a point to the left and right of the start point 253 | var cornersVector = sub(leftPts[0], rightPts[0]); 254 | var offsetA = mul(cornersVector, 0.5); 255 | var offsetB = mul(cornersVector, 0.51); 256 | startCap.push(sub(firstPoint, offsetA), sub(firstPoint, offsetB), add(firstPoint, offsetB), add(firstPoint, offsetA)); 257 | } 258 | /* 259 | Draw an end cap 260 | 261 | If the line does not have a tapered end, and unless the line has a tapered 262 | start and the line is very short, draw a cap around the last point. Finally, 263 | remove the last left and right points. Otherwise, add the last point. Note 264 | that This cap is a full-turn-and-a-half: this prevents incorrect caps on 265 | sharp end turns. 266 | */ 267 | var direction = per(neg(points[points.length - 1].vector)); 268 | if (taperEnd || (taperStart && points.length === 1)) { 269 | // Tapered end - push the last point to the line 270 | endCap.push(lastPoint); 271 | } 272 | else if (capEnd) { 273 | // Draw the round end cap 274 | var start_2 = prj(lastPoint, direction, radius); 275 | for (var step = 1 / 29, t = step; t < 1; t += step) { 276 | endCap.push(rotAround(start_2, lastPoint, FIXED_PI * 3 * t)); 277 | } 278 | } 279 | else { 280 | // Draw the flat end cap 281 | endCap.push(add(lastPoint, mul(direction, radius)), add(lastPoint, mul(direction, radius * 0.99)), sub(lastPoint, mul(direction, radius * 0.99)), sub(lastPoint, mul(direction, radius))); 282 | } 283 | } 284 | /* 285 | Return the points in the correct winding order: begin on the left side, then 286 | continue around the end cap, then come back along the right side, and finally 287 | complete the start cap. 288 | */ 289 | return leftPts.concat(endCap, rightPts.reverse(), startCap); 290 | } 291 | 292 | function getStrokePoints(points, options) { 293 | var _a; 294 | if (options === void 0) { options = {}; } 295 | var _b = options.streamline, streamline = _b === void 0 ? 0.5 : _b, _c = options.size, size = _c === void 0 ? 16 : _c, _d = options.last, isComplete = _d === void 0 ? false : _d; 296 | // If we don't have any points, return an empty array. 297 | if (points.length === 0) 298 | return []; 299 | // Find the interpolation level between points. 300 | var t = 0.15 + (1 - streamline) * 0.85; 301 | // Whatever the input is, make sure that the points are in number[][]. 302 | var pts = Array.isArray(points[0]) 303 | ? points 304 | : points.map(function (_a) { 305 | var x = _a.x, y = _a.y, _b = _a.pressure, pressure = _b === void 0 ? 0.5 : _b; 306 | return [x, y, pressure]; 307 | }); 308 | // Add extra points between the two, to help avoid "dash" lines 309 | // for strokes with tapered start and ends. Don't mutate the 310 | // input array! 311 | if (pts.length === 2) { 312 | var last = pts[1]; 313 | pts = pts.slice(0, -1); 314 | for (var i = 1; i < 5; i++) { 315 | pts.push(lrp(pts[0], last, i / 4)); 316 | } 317 | } 318 | // If there's only one point, add another point at a 1pt offset. 319 | // Don't mutate the input array! 320 | if (pts.length === 1) { 321 | pts = __spreadArray(__spreadArray([], pts, true), [__spreadArray(__spreadArray([], add(pts[0], [1, 1]), true), pts[0].slice(2), true)], false); 322 | } 323 | // The strokePoints array will hold the points for the stroke. 324 | // Start it out with the first point, which needs no adjustment. 325 | var strokePoints = [ 326 | { 327 | point: [pts[0][0], pts[0][1]], 328 | pressure: pts[0][2] >= 0 ? pts[0][2] : 0.25, 329 | vector: [1, 1], 330 | distance: 0, 331 | runningLength: 0, 332 | }, 333 | ]; 334 | // A flag to see whether we've already reached out minimum length 335 | var hasReachedMinimumLength = false; 336 | // We use the runningLength to keep track of the total distance 337 | var runningLength = 0; 338 | // We're set this to the latest point, so we can use it to calculate 339 | // the distance and vector of the next point. 340 | var prev = strokePoints[0]; 341 | var max = pts.length - 1; 342 | // Iterate through all of the points, creating StrokePoints. 343 | for (var i = 1; i < pts.length; i++) { 344 | var point = isComplete && i === max 345 | ? // If we're at the last point, and `options.last` is true, 346 | // then add the actual input point. 347 | pts[i].slice(0, 2) 348 | : // Otherwise, using the t calculated from the streamline 349 | // option, interpolate a new point between the previous 350 | // point the current point. 351 | lrp(prev.point, pts[i], t); 352 | // If the new point is the same as the previous point, skip ahead. 353 | if (isEqual(prev.point, point)) 354 | continue; 355 | // How far is the new point from the previous point? 356 | var distance = dist(point, prev.point); 357 | // Add this distance to the total "running length" of the line. 358 | runningLength += distance; 359 | // At the start of the line, we wait until the new point is a 360 | // certain distance away from the original point, to avoid noise 361 | if (i < max && !hasReachedMinimumLength) { 362 | if (runningLength < size) 363 | continue; 364 | hasReachedMinimumLength = true; 365 | // TODO: Backfill the missing points so that tapering works correctly. 366 | } 367 | // Create a new strokepoint (it will be the new "previous" one). 368 | prev = { 369 | // The adjusted point 370 | point: point, 371 | // The input pressure (or .5 if not specified) 372 | pressure: pts[i][2] >= 0 ? pts[i][2] : 0.5, 373 | // The vector from the current point to the previous point 374 | vector: uni(sub(prev.point, point)), 375 | // The distance between the current point and the previous point 376 | distance: distance, 377 | // The total distance so far 378 | runningLength: runningLength, 379 | }; 380 | // Push it to the strokePoints array. 381 | strokePoints.push(prev); 382 | } 383 | // Set the vector of the first point to be the same as the second point. 384 | strokePoints[0].vector = ((_a = strokePoints[1]) === null || _a === void 0 ? void 0 : _a.vector) || [0, 0]; 385 | return strokePoints; 386 | } 387 | function getStrokeRadius(size, thinning, pressure, easing) { 388 | if (easing === void 0) { easing = function (t) { return t; }; } 389 | return size * easing(0.5 - thinning * (0.5 - pressure)); 390 | } 391 | 392 | /** 393 | * Negate a vector. 394 | * @param A 395 | * @internal 396 | */ 397 | function neg(A) { 398 | return [-A[0], -A[1]]; 399 | } 400 | /** 401 | * Add vectors. 402 | * @param A 403 | * @param B 404 | * @internal 405 | */ 406 | function add(A, B) { 407 | return [A[0] + B[0], A[1] + B[1]]; 408 | } 409 | /** 410 | * Subtract vectors. 411 | * @param A 412 | * @param B 413 | * @internal 414 | */ 415 | function sub(A, B) { 416 | return [A[0] - B[0], A[1] - B[1]]; 417 | } 418 | /** 419 | * Vector multiplication by scalar 420 | * @param A 421 | * @param n 422 | * @internal 423 | */ 424 | function mul(A, n) { 425 | return [A[0] * n, A[1] * n]; 426 | } 427 | /** 428 | * Vector division by scalar. 429 | * @param A 430 | * @param n 431 | * @internal 432 | */ 433 | function div(A, n) { 434 | return [A[0] / n, A[1] / n]; 435 | } 436 | /** 437 | * Perpendicular rotation of a vector A 438 | * @param A 439 | * @internal 440 | */ 441 | function per(A) { 442 | return [A[1], -A[0]]; 443 | } 444 | /** 445 | * Dot product 446 | * @param A 447 | * @param B 448 | * @internal 449 | */ 450 | function dpr(A, B) { 451 | return A[0] * B[0] + A[1] * B[1]; 452 | } 453 | /** 454 | * Get whether two vectors are equal. 455 | * @param A 456 | * @param B 457 | * @internal 458 | */ 459 | function isEqual(A, B) { 460 | return A[0] === B[0] && A[1] === B[1]; 461 | } 462 | /** 463 | * Length of the vector 464 | * @param A 465 | * @internal 466 | */ 467 | function len(A) { 468 | return Math.hypot(A[0], A[1]); 469 | } 470 | /** 471 | * Length of the vector squared 472 | * @param A 473 | * @internal 474 | */ 475 | function len2(A) { 476 | return A[0] * A[0] + A[1] * A[1]; 477 | } 478 | /** 479 | * Dist length from A to B squared. 480 | * @param A 481 | * @param B 482 | * @internal 483 | */ 484 | function dist2(A, B) { 485 | return len2(sub(A, B)); 486 | } 487 | /** 488 | * Get normalized / unit vector. 489 | * @param A 490 | * @internal 491 | */ 492 | function uni(A) { 493 | return div(A, len(A)); 494 | } 495 | /** 496 | * Dist length from A to B 497 | * @param A 498 | * @param B 499 | * @internal 500 | */ 501 | function dist(A, B) { 502 | return Math.hypot(A[1] - B[1], A[0] - B[0]); 503 | } 504 | /** 505 | * Mean between two vectors or mid vector between two vectors 506 | * @param A 507 | * @param B 508 | * @internal 509 | */ 510 | function med(A, B) { 511 | return mul(add(A, B), 0.5); 512 | } 513 | /** 514 | * Rotate a vector around another vector by r (radians) 515 | * @param A vector 516 | * @param C center 517 | * @param r rotation in radians 518 | * @internal 519 | */ 520 | function rotAround(A, C, r) { 521 | var s = Math.sin(r); 522 | var c = Math.cos(r); 523 | var px = A[0] - C[0]; 524 | var py = A[1] - C[1]; 525 | var nx = px * c - py * s; 526 | var ny = px * s + py * c; 527 | return [nx + C[0], ny + C[1]]; 528 | } 529 | /** 530 | * Interpolate vector A to B with a scalar t 531 | * @param A 532 | * @param B 533 | * @param t scalar 534 | * @internal 535 | */ 536 | function lrp(A, B, t) { 537 | return add(A, mul(sub(B, A), t)); 538 | } 539 | /** 540 | * Project a point A in the direction B by a scalar c 541 | * @param A 542 | * @param B 543 | * @param c 544 | * @internal 545 | */ 546 | function prj(A, B, c) { 547 | return add(A, mul(B, c)); 548 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /AnkiDraw/Caligrapher.js: -------------------------------------------------------------------------------- 1 | /* 2 | -------------------------------- Caligrapher ------------------------------------------ 3 | Created By: August Toman-Yih 4 | Git Repository: https://github.com/atomanyih/Calligrapher 5 | */ 6 | /* ------------------------------Unchanged Caligrapher Code------------------------------*/ 7 | /* ------------------------------ Corners.js ------------------------------*/ 8 | /** 9 | * @classDescription A shape made out of bezier curves. Hopefully connected 10 | * @param {Array} sections 11 | */ 12 | function BezierShape(sections) { 13 | this.sections = sections; 14 | this.name = ""; //optional 15 | this.skeleton = []; 16 | } 17 | 18 | BezierShape.prototype.copy = function() { 19 | var newSections = [], 20 | newSkeleton = []; 21 | for(var i in this.sections) { 22 | newSections[i] = []; 23 | for(var j = 0; j<4; j++) { 24 | newSections[i][j] = this.sections[i][j].slice(0); 25 | } 26 | } 27 | for(var i in this.skeleton) 28 | newSkeleton[i] = this.skeleton[i].copy(); 29 | 30 | var copy = new BezierShape(newSections); 31 | copy.name = this.name; 32 | copy.skeleton = newSkeleton; 33 | return copy; 34 | }; 35 | 36 | /** 37 | * Draws the BezierShape NO SCALING OR NUFFIN. Probably only used internally 38 | * @param {Object} ctx 39 | */ 40 | BezierShape.prototype.draw = function(ctx) { 41 | var x = this.sections[0][0][0], //ew 42 | y = this.sections[0][0][1]; 43 | ctx.beginPath(); 44 | ctx.moveTo(x,y); 45 | for(var i = 0; i < this.sections.length; i++) { 46 | var b = this.sections[i]; 47 | ctx.bezierCurveTo(b[1][0],b[1][1],b[2][0],b[2][1],b[3][0],b[3][1]); 48 | } 49 | ctx.closePath(); 50 | 51 | ctx.fill(); 52 | }; 53 | 54 | function Bone(points,offset) { 55 | this.points = points; 56 | this.offset = offset; 57 | } 58 | 59 | Bone.prototype.copy = function() { 60 | var nP = []; 61 | for(var i in this.points) 62 | nP[i] = this.points[i].slice(0); 63 | return new Bone(nP,this.offset); 64 | }; 65 | 66 | function drawCornerScaled(corner,pos,dir,width,height,ctx) { //FIXME degree, radian inconsistency 67 | ctx.save(); 68 | ctx.translate(pos[0],pos[1]); 69 | ctx.rotate(dir); 70 | ctx.scale(height,width); 71 | 72 | corner.draw(ctx); 73 | ctx.restore(); 74 | } 75 | 76 | function drawCorner(corner,pos,dir,width,ctx) { 77 | drawCornerScaled(corner,pos,dir,width,width,ctx); 78 | } 79 | 80 | function drawDICorner(corner,attrs,width,ctx) { 81 | if(corner == null) 82 | return; 83 | 84 | // corner rotation 85 | var pos = attrs.point, 86 | inAngle = attrs.inAngle-corner.skeleton["armA"].offset, //This is so the whole corner is rotated //FIXME a little gross 87 | outAngle = attrs.outAngle, 88 | c = setBoneAngles(corner,[["armB",(outAngle-inAngle)/180*Math.PI]]); 89 | 90 | drawCorner(c,pos,inAngle/180*Math.PI,width,ctx); 91 | } 92 | 93 | 94 | 95 | // HERE ARE SOME CORNERS // some may need to be rotated 96 | kappa = 0.5522847498; 97 | // Circle-ish thing. Not a corner. 98 | CIRCLE = new BezierShape([ 99 | [[-5,0],[-5,-5*kappa],[-5*kappa,-5],[0,-5]], 100 | [[0,-5],[5*kappa,-5],[5,-5*kappa],[5,0]], 101 | [[5,0],[5,5*kappa],[5*kappa,5],[0,5]], 102 | [[0,5],[-5*kappa,5],[-5,5*kappa],[-5,0]] 103 | ]); 104 | 105 | 106 | C1 = new BezierShape([ 107 | [[15,6], [-3,4], [-11,5], [-20,0]] 108 | ,[[-20,0], [-15,-5], [4,-9], [13,-5]] 109 | ,[[13,-5], [20,0], [21,8], [15,6]] 110 | ]); 111 | C1.name = "C1"; 112 | 113 | C2 = new BezierShape([ 114 | [[2,5], [-2,5], [-12,2], [-13,-2]] 115 | ,[[-13,2], [-7,-5], [0,-5], [2,-5]] 116 | ,[[2,-5], [3,-5], [3,5], [2,5]] 117 | ]); 118 | C2.name = "C2"; 119 | 120 | C3 = new BezierShape([ 121 | [[-8,5], [-10,5], [-10,-5], [-8,-5]] 122 | ,[[-8,-5], [3,-5], [15,0], [15,5]] 123 | ,[[15,5], [10,7], [2,5], [-8,5]] 124 | ]); 125 | C3.name = "C3"; 126 | 127 | C4 = new BezierShape([ 128 | [[0,5], [-2,5], [-4,7], [-5,8]] 129 | ,[[-5,8], [-7,10], [-9,12], [-8,5]] 130 | ,[[-8,5], [-7,3], [-5,-5], [0,-5]] 131 | ,[[0,-5], [3,-5], [3,5], [0,5]] 132 | ]); 133 | C4.name = "C4"; 134 | 135 | C5 = new BezierShape([ 136 | [[0,-5], [-3,-5], [-3,5], [0,5]] 137 | ,[[0,5], [8,5], [10,5], [15,2]] 138 | ,[[15,2], [12,-2], [-2,-5], [0,-5]] 139 | ]); 140 | C5.name = "C5"; 141 | 142 | C6 = new BezierShape([ 143 | [[0,5], [-6,6], [-8,7], [-12,8]] 144 | ,[[-12,8], [-13,9], [-13,7], [-12,6]] 145 | ,[[-12,6], [-10,3], [-5,-4], [0,-5]] 146 | ,[[0,-5], [3,-5], [3,5], [0,5]] 147 | ]); 148 | C6.name = "C6"; 149 | 150 | C7 = new BezierShape([ 151 | [[-5,-5],[0,-5],[11,-7],[15,-6]] 152 | ,[[15,-6],[17,-5],[2,4],[1,5]] 153 | ,[[1,5],[0,5],[0,5],[-5,5]] 154 | ,[[-5,5],[-8,5],[-8,-5],[-5,-5]] 155 | ]); 156 | C7.name = "C7"; 157 | 158 | SI_CORNERS = [C1,C2,C3,C4,C5,C6,C7]; 159 | 160 | C8 = new BezierShape([ 161 | [[-13,3], [-20,3], [-20,-3], [-13,-3]], 162 | [[-13,-3], [-5,-5], [-6,-7], [-4,-8]], 163 | [[-4,-8], [0,-8], [12,3], [7,5]], 164 | [[7,5], [5,6], [5,8], [3,13]], 165 | [[3,13], [3,20], [-3,20], [-3,13]], 166 | [[-3,13], [-5,5], [-10,5], [-13,3]] 167 | ]); 168 | C8.name = "C8"; 169 | C8.skeleton["armA"] = new Bone([[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[5,2],[5,3]],0); 170 | C8.skeleton["armB"] = new Bone([[4,0],[4,1],[4,2],[4,3],[3,2],[3,3],[5,0],[5,1], 171 | [1,2],[1,3],[2,0],[2,1]],90); 172 | 173 | C8R = horizFlipCopy(C8); 174 | 175 | /*C9 = new BezierShape([ //TODO fix corner so that stem moves depending on angle 176 | [[-3,-10], [-3,-15], [3,-15], [3,-10]], 177 | [[3,-10], [5,-5], [6,6], [0,11]], 178 | [[0,11], [-5,15], [-3,5], [-10,3]], 179 | [[-10,3], [-15,3], [-15,-3], [-10,-3]], 180 | [[-10,-3], [-5,-5], [-5,-7], [-3,-10]] 181 | ]); 182 | C9.name = "C9"; 183 | C9.skeleton["armA"] = new Bone([[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[4,2],[4,3]],90); 184 | C9.skeleton["armB"] = new Bone([[3,0],[3,1],[3,2],[3,3],[4,0],[4,1],[2,2],[2,3]],180);*/ 185 | 186 | C9 = new BezierShape([ //note, 90º angles look a little weird 187 | [[-4,-12],[-4,-15],[4,-15],[5,-12]], 188 | [[5,-12],[5,-2],[6,3],[1,8]], 189 | [[-1,8],[-3,11],[-4,2],[-12,-5]], 190 | [[-12,-5],[-15,-7],[-15,-9],[-10,-8]], 191 | [[-10,-8],[-6,-8],[-4,-7],[-4,-12]] 192 | ]); 193 | C9.name = "C9"; 194 | C9.skeleton["armA"] = new Bone([[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[4,2],[4,3],[1,2]],90); //not that this actually matters 195 | C9.skeleton["armB"] = new Bone([[3,0],[3,1],[3,2],[3,3],[4,0],[4,1],[2,2],[2,3]],210); 196 | 197 | C9R = vertFlipCopy(C9); 198 | 199 | C10 = new BezierShape([ 200 | [[-5,5],[-6,5],[-6,-5],[-5,-5]], 201 | [[-5,-5],[-2,-7],[2,-7],[5,-5]], 202 | [[5,-5],[6,-5],[6,5],[5,5]], 203 | [[5,5],[2,7],[-2,7],[-5,5]] 204 | ]); 205 | 206 | C10.name = "C10"; 207 | C10.skeleton["armA"] = new Bone([[0,0],[0,1],[0,2],[0,3],[1,0],[1,2],[3,2],[3,3]],0); 208 | C10.skeleton["armB"] = new Bone([[2,0],[2,1],[2,2],[2,3],[3,0],[3,1],[1,2],[1,3]],0); 209 | 210 | function linInterpolate(y0,y1,mu) { 211 | return y0*(1-mu) + y1*mu; 212 | } 213 | 214 | function cosInterpolate(y0,y1,mu) { 215 | var mu2 = (1-Math.cos(mu*Math.PI))/2; 216 | return y0*(1-mu2)+y1*mu2; 217 | } 218 | 219 | /** 220 | * Returns a function that linearly interpolates between the values given 221 | */ 222 | function linFunction(points) { 223 | return function(t) { 224 | if(t==0) 225 | return points[0][1]; 226 | for(var i = 1; ip0[0]) { 230 | var mu = (t-p0[0])/(p1[0]-p0[0]); 231 | return linInterpolate(p0[1],p1[1],mu); //cubic might be better 232 | } 233 | } 234 | }; 235 | } 236 | 237 | /** 238 | * Returns a function that cosine interpolates between the values given 239 | */ 240 | function cosFunction(points) { 241 | return function(t) { 242 | if(t==0) 243 | return points[0][1]; 244 | for(var i = 1; ip0[0]) { 248 | var mu = (t-p0[0])/(p1[0]-p0[0]); 249 | return cosInterpolate(p0[1],p1[1],mu); //cubic might be better 250 | } 251 | } 252 | }; 253 | } 254 | 255 | //example thickness functions 256 | function one(t) { 257 | return 1; 258 | } 259 | 260 | function test(t) { 261 | return t; 262 | } 263 | 264 | //These are ugly 265 | SEGMENT_I = cosFunction([[0,1],[.5,.7],[1,1]]); //FIXME, sometimes extends past corners 266 | SEGMENT_II = linFunction([[0,1],[.5,.8],[1,.2]]); //kinda ugly :|| 267 | SEGMENT_III = linFunction([[0,.2],[.5,.8],[1,1]]); 268 | 269 | HEN = [C2,SEGMENT_I,C3]; 270 | SHU1 = [C4,SEGMENT_I,C5]; 271 | SHU2 = [C4,SEGMENT_II]; 272 | NA = [C6,SEGMENT_I,C7]; 273 | DIAN = [C1]; 274 | OTHER = [C4,SEGMENT_II]; 275 | 276 | function RAND(t) { 277 | return Math.random(); 278 | } 279 | 280 | function setBoneAngles(c,dirList) { 281 | var c = c.copy(); 282 | 283 | for(var i in dirList) { 284 | var dir = dirList[i][1], 285 | bone = dirList[i][0]; 286 | for(var j in c.skeleton[bone].points) { 287 | var p = c.skeleton[bone].points[j], 288 | offset = c.skeleton[bone].offset/180*Math.PI, 289 | vec = c.sections[p[0]][p[1]]; 290 | //console.log(vec); 291 | //console.log(dir-offset); 292 | //console.log(rotate(vec,dir-offset)); 293 | c.sections[p[0]][p[1]] = rotate(vec,dir-offset); 294 | 295 | } 296 | } 297 | 298 | return c; 299 | } 300 | 301 | function vertFlipCopy(c) { 302 | var c = c.copy(); 303 | 304 | for(var i in c.sections){ 305 | for(var j in c.sections[i]) { 306 | c.sections[i][j][1] = -c.sections[i][j][1]; 307 | } 308 | } 309 | for(var i in c.skeleton) { 310 | c.skeleton[i].offset = 360 - c.skeleton[i].offset; 311 | } 312 | return c 313 | } 314 | 315 | function horizFlipCopy(c) { 316 | var c = c.copy(); 317 | 318 | for(var i in c.sections){ 319 | for(var j in c.sections[i]) { 320 | c.sections[i][j][0] = -c.sections[i][j][0]; 321 | } 322 | } 323 | for(var i in c.skeleton) { 324 | c.skeleton[i].offset = 180 - c.skeleton[i].offset; 325 | if(c.skeleton[i].offset<0) 326 | c.skeleton[i].offset += 360; 327 | } 328 | return c 329 | } 330 | 331 | /* ------------------------------ bezier.js ------------------------------*/ 332 | 333 | //TODO use vectors for everything so it's less stupid 334 | 335 | // Generalized recurvsive BEZIER FUNCTIONS (why am I doing it this way I don't know) 336 | /** 337 | * returns a point on the bezier curve 338 | * @param {Array} ps Control points of bezier curve 339 | * @param {Numeric} t Location along bezier curve [0,1] 340 | * @return {Array} Returns the point on the bezier curve 341 | */ 342 | function bezierPos(ps, t) { 343 | var size = ps.length; 344 | if(size == 1) 345 | return ps[0]; 346 | 347 | //WARNING, changed direction on this. May cause problems 348 | var bx = (t) * bezierPos(ps.slice(1),t)[0] + (1-t) * bezierPos(ps.slice(0,size-1),t)[0], 349 | by = (t) * bezierPos(ps.slice(1),t)[1] + (1-t) * bezierPos(ps.slice(0,size-1),t)[1]; 350 | 351 | return [bx,by]; 352 | } 353 | 354 | function bezierSlo(ps, t) { 355 | var size = ps.length; 356 | 357 | if(size == 1) 358 | return ps[0]; 359 | 360 | var dx = bezierPos(ps.slice(0,size-1),t)[0] - bezierPos(ps.slice(1),t)[0] , 361 | dy = bezierPos(ps.slice(0,size-1),t)[1] - bezierPos(ps.slice(1),t)[1]; 362 | 363 | return dy/dx; 364 | } 365 | 366 | // Bezier function class. Meant simply as a math thing (no drawing or any bullshit) 367 | /** 368 | * @class Bezier function class. 369 | * @return {Bezier} Returns the bezier function 370 | */ 371 | function Bezier(controlPoints) { 372 | this.order = controlPoints.length-1; //useful? or obtuse? //Answer: not used anywhere 373 | this.controlPoints = controlPoints; 374 | } 375 | 376 | Bezier.prototype.getStart = function() { 377 | return this.controlPoints[0]; 378 | }; 379 | 380 | Bezier.prototype.getEnd = function() { 381 | return this.controlPoints[this.order]; 382 | }; 383 | 384 | Bezier.prototype.getPoint = function(t) { 385 | return bezierPos(this.controlPoints,t); 386 | }; 387 | 388 | Bezier.prototype.drawPlain = function(ctx) { 389 | if(this.order == 3) { 390 | var c = this.controlPoints; 391 | ctx.beginPath(); 392 | ctx.moveTo(c[0][0],c[0][1]); 393 | ctx.bezierCurveTo(c[1][0],c[1][1],c[2][0],c[2][1],c[3][0],c[3][1]); 394 | ctx.stroke(); 395 | } 396 | 397 | }; 398 | 399 | Bezier.prototype.getDerivativeVector = function(t) { 400 | var size = 0.001, 401 | p0 = null, 402 | p1 = null; 403 | if(t=1) 459 | return 1; //so we don't extrapolate or anything stupid 460 | } 461 | return t; 462 | }; 463 | 464 | Bezier.prototype.getPointByLengthBack = function(l) {//doesn't actually return a point. bad name 465 | var t = 1, 466 | len = 0, 467 | point = this.getEnd(); 468 | while(len < l) { 469 | var newPoint = this.getPoint(t) 470 | len += getDist(point,newPoint); 471 | point = newPoint; 472 | t -= 0.01; 473 | if(t<=0) 474 | return 1; //so we don't extrapolate or anything stupid 475 | } 476 | return t; 477 | }; 478 | 479 | function getSlopeVector(slope,length) { 480 | var x = length * Math.cos(Math.atan(slope)), 481 | y = length * Math.sin(Math.atan(slope)); 482 | return [x,y]; 483 | } 484 | 485 | function scalePoint(s0,s1,p0,p1,v) { //Could probs be simplified, also currently not used 486 | var xScale = (p1[0]-p0[0])/(s1[0]-s0[0]), //scaling factos 487 | yScale = (p1[1]-p0[1])/(s1[1]-s0[1]), 488 | x = p0[0]+xScale*(v[0]-s0[0]), //Scaled x and y 489 | y = p0[1]+yScale*(v[1]-s0[1]); 490 | return [x,y]; 491 | } 492 | 493 | //Draws a bezier curve scaled between the two points (good idea? bad idea? dunno.) 494 | /** 495 | * @param {Bezier} curve The bezier curve to be drawn 496 | * @param {Numerical} wid Nominal width 497 | * @param {Function} wF Width function 498 | * @param {Context} ctx Context to draw to 499 | */ 500 | //FIXME width function gets "bunched up" around control points (detail below) 501 | // the bezier calculation means that more of t is spent near control points. turn on debug to see 502 | // this is good for detail b/c it means higher resolution at tight curves (a happy accident) 503 | // but the width contour gets a bit bunched up. solution: instead of wF(t), use wF(currentLength/totalLength) 504 | 505 | //FIXME Ugly (code) 506 | function drawBezier(curve,wid,wF,ctx) { 507 | var length = curve.getLength(), 508 | numPoints = Math.round(length/RESOLUTION), 509 | leftPoints = [], 510 | rightPoints = [], 511 | currentPoint = sub(scale(curve.getStart(),2),curve.controlPoints[1]); 512 | 513 | for(var i = 0; i <= numPoints; i++){ 514 | var t = i/numPoints, 515 | centerPoint = curve.getPoint(t) 516 | offset = scale(perpNorm(sub(centerPoint,currentPoint)),wF(t)*wid/2); 517 | 518 | leftPoints.push(add(centerPoint,offset)); 519 | rightPoints.push(sub(centerPoint,offset)); 520 | currentPoint = centerPoint; 521 | 522 | } 523 | //Drawing the polygon 524 | var s = leftPoints[0]; 525 | ctx.beginPath(); 526 | ctx.moveTo(s[0],s[1]); //starting from start center 527 | for(var i = 0; i < leftPoints.length; i++){ 528 | var p = leftPoints[i]; 529 | ctx.lineTo(p[0],p[1]); 530 | } 531 | for(var i = rightPoints.length-1; i >= 0; i--){ 532 | var p = rightPoints[i]; 533 | ctx.lineTo(p[0],p[1]); 534 | } 535 | ctx.closePath(); 536 | ctx.fill(); 537 | } 538 | 539 | function drawBezierTransformed(p0,p1,curve,wid,wF,ctx) { 540 | var s0 = curve.getStart(), 541 | s1 = curve.getEnd(), 542 | xScale = (p1[0]-p0[0])/(s1[0]-s0[0]), //scaling factos 543 | yScale = (p1[1]-p0[1])/(s1[1]-s0[1]), 544 | controlPoints = []; 545 | 546 | for(var i = 0; i <= curve.order; i++) { 547 | var p = curve.controlPoints[i], 548 | x = p0[0]+xScale*(p[0]-s0[0]), //Scaled x and y 549 | y = p0[1]+yScale*(p[1]-s0[1]); 550 | controlPoints[i] = [x,y]; 551 | } 552 | drawBezier(new Bezier(controlPoints),wid,wF,ctx); 553 | 554 | } 555 | 556 | /* ------------------------------ curveFitting.js ------------------------------*/ 557 | function getLengths(chord) { 558 | var lens = [0]; //first is 0 559 | 560 | for(var i = 1; ilist[i]) { 588 | iMin = i; 589 | min = list[i]; 590 | } 591 | } 592 | return [iMin,min]; 593 | } 594 | 595 | function parameterize(chord) { 596 | /*var lens = getLengths(chord); 597 | return normalizeList(lens);*/ 598 | var lens = [0]; //first is 0 599 | 600 | for(var i = 1; i max) { 664 | max = dist; 665 | iMax = i; 666 | } 667 | } 668 | return [iMax,max]; 669 | } 670 | 671 | function fitStroke(chord) { 672 | var chords = splitChord(chord,detectCorners(chord)), 673 | curves = []; 674 | 675 | for(var i in chords) { 676 | var ts = parameterize(chords[i]), 677 | curve = leastSquaresFit(chords[i],ts); 678 | curves.push(curve); 679 | } 680 | 681 | return curves; 682 | } 683 | 684 | function splitCurve(chord,ts,curve) { //TODO FIGURE THIS FUCKING SHIT OUT 685 | var errs = []; 686 | for(var i = 1; i= chord.length) //if it's not long enough just return the whole thing 742 | return chord; 743 | dist+=getDist(chord[i],chord[i-1]); 744 | } 745 | return chord.slice(0,i); 746 | } 747 | 748 | function splitChord(chord,indices) { 749 | var newChords = [], 750 | ind = 0; 751 | for(var i in indices) { 752 | newChords.push(chord.slice(ind,indices[i]+1)); 753 | ind = indices[i]; 754 | } 755 | newChords.push(chord.slice(ind)); 756 | return newChords; 757 | } 758 | 759 | function chordPrint(chord) { 760 | var s = "| "; 761 | for(var i in chord) { 762 | s+= chord[i] + " | "; 763 | } 764 | //console.log(s); 765 | } 766 | 767 | /* ------------------------------ strokeDrawing.js ------------------------------*/ 768 | 769 | //Stroke drawing and analysis 770 | //Basically, a "stroke" will be a collection of segments 771 | //the segments when drawn will be assigned corners and types and stuff 772 | 773 | function drawSegment(wF,segment,width,ctx) { 774 | drawBezier(segment,width,wF,ctx); 775 | //ctx.fillStyle = "rgba(0,0,0,1)"; 776 | } 777 | 778 | 779 | 780 | function drawBasicStroke(segment,width,ctx) { //TODO 781 | var attrs = getSegmentAttributes(segment), 782 | comps = checkRules2(attrs,RULE_BS); 783 | 784 | //corners 785 | if(comps.length == 1){ //dian 786 | var point = midpoint(attrs.startPoint,attrs.endPoint,0.5); //FIXME these stupid width division factors 787 | drawCornerScaled(comps[0],point,degToRad(attrs.startAngle),width/13,attrs.length/20,ctx); 788 | } else { 789 | drawCorner(comps[0],attrs.startPoint,degToRad(attrs.startAngle),width/10,ctx); 790 | if(comps.length == 3) { 791 | drawCorner(comps[2],attrs.endPoint,degToRad(attrs.endAngle),width/10,ctx); 792 | } 793 | 794 | drawSegment(comps[1],segment,width,ctx); 795 | } 796 | } 797 | 798 | function Stroke(segments) { 799 | this.segments = segments; 800 | } 801 | 802 | Stroke.prototype.drawPlain = function(ctx) { 803 | var x = this.segments[0].getStart()[0], 804 | y = this.segments[0].getStart()[1]; 805 | ctx.moveTo(x,y); 806 | for(var i = 0; i < this.segments.length; i++) { 807 | var b = this.segments[i].controlPoints; 808 | ctx.bezierCurveTo(b[1][0],b[1][1],b[2][0],b[2][1],b[3][0],b[3][1]); 809 | } 810 | ctx.stroke(); 811 | }; 812 | 813 | Stroke.prototype.draw = function(width, ctx) { 814 | if(this.segments.length == 1){ //Basic Stroke 815 | drawBasicStroke(this.segments[0],width,ctx); 816 | } else { //Compound stroke 817 | drawCompoundStroke(this,width,ctx); 818 | } 819 | }; 820 | 821 | function drawCompoundStroke(stroke,width,ctx) { //FIXME copypasta 822 | var numSegments = stroke.segments.length; 823 | 824 | //corners 825 | var attrs = getSegmentAttributes(stroke.segments[0]), 826 | corners = []; 827 | 828 | var corner = checkRules2(attrs,RULE_CC_START);//checkRules(attrs,COMPOUND_CORNER_START); 829 | if(corner != null) 830 | drawCorner(corner,attrs.startPoint,attrs.startAngle/180*Math.PI,width/10,ctx); 831 | corners.push(corner); 832 | 833 | for(var i = 1; i= range[0] && num < range[1]; 865 | } 866 | 867 | function inRanges(num,ranges) { 868 | for(var i = 0; ioutAngle){ 902 | if(inAngle-180180) 915 | return angle-360; 916 | return angle; 917 | } 918 | 919 | function checkRule(obj,rule) { 920 | if(rule[0] == "Result") 921 | return rule[1]; 922 | //console.log(rule[0]); 923 | if(inRange(obj[rule[0]],rule[1])) 924 | return checkRule(obj,rule[2]); 925 | return null; 926 | } 927 | 928 | function checkRules(obj,ruleset) { //checks all rules, no shortcircuiting currently 929 | var results = []; 930 | //console.log("Checking rules"); 931 | for(var i = 0; i 1) 937 | throw "Overlapping conditions"; 938 | if(results.length == 1) 939 | return results[0]; 940 | //console.log("no result"); 941 | return ruleset[ruleset.length-1]; //default 942 | } 943 | 944 | function checkRules2(obj,ruleset) { 945 | var results = []; 946 | //console.log("Checking rules"); 947 | for(var i = 0; i=r[i][0] && n=r; 988 | }, 989 | "LESS_THAN" : function(a,n,r) { 990 | return nMath.abs(matrix[iMax][c])) 1258 | iMax = i; 1259 | } 1260 | return iMax 1261 | } 1262 | 1263 | function swapRows(matrix,r0,r1) { 1264 | var i = matrix[r0]; 1265 | matrix[r0]=matrix[r1]; 1266 | matrix[r1]=i; 1267 | return matrix; 1268 | } 1269 | 1270 | /* ------------------------------ Vector.js ------------------------------*/ 1271 | 1272 | // Math 1273 | function truncate(vector, max) { 1274 | var mag = getMag(vector); 1275 | if(mag > max) 1276 | return scale(vector,max/mag); 1277 | return vector; 1278 | } 1279 | 1280 | function perp(vector) { 1281 | return [vector[1],-vector[0]]; 1282 | } 1283 | 1284 | function perpNorm(vector) { 1285 | return normalize(perp(vector)); 1286 | } 1287 | 1288 | function normalize(vector) { 1289 | //if(vector[0]==0 && vector[1]==0) 1290 | // return [0,1]; 1291 | var mag = getMag(vector); 1292 | return scale(vector,1/mag); 1293 | } 1294 | 1295 | function normalizeTo(vector,mag) { 1296 | return scale(normalize(vector),mag); 1297 | } 1298 | 1299 | function projectedLength(vector,along) { 1300 | return dot(vector,along)/getMag(along); 1301 | } 1302 | 1303 | function project(vector,along) { 1304 | 1305 | } 1306 | 1307 | function scale(vector,factor) { 1308 | return [vector[0]*factor,vector[1]*factor]; 1309 | } 1310 | 1311 | function add(vector1, vector2) { 1312 | return [vector1[0]+vector2[0],vector1[1]+vector2[1]]; 1313 | } 1314 | 1315 | function sub(vector1, vector2) { 1316 | return [vector1[0]-vector2[0],vector1[1]-vector2[1]]; 1317 | } 1318 | 1319 | function getMag(vector) { 1320 | return getDist([0,0],vector); 1321 | } 1322 | 1323 | function getDist(vector1,vector2) { 1324 | return Math.sqrt(Math.pow((vector2[0]-vector1[0]),2)+Math.pow((vector2[1]-vector1[1]),2)); 1325 | } 1326 | 1327 | function getAngle(vector) { 1328 | var quad = 0; 1329 | if(vector[0]===0) // because 0 and -0 are not always the same 1330 | vector[0] = +0; 1331 | if(vector[0]<0) 1332 | quad = Math.PI; 1333 | else if(vector[0]>0 && vector[1]<0) 1334 | quad = 2*Math.PI; 1335 | return reduceAngle(Math.atan(vector[1]/vector[0])+quad); 1336 | } 1337 | 1338 | function getAngleBetween(vector1,vector2) { 1339 | return Math.abs(getAngle(vector1)-getAngle(vector2)); 1340 | } 1341 | 1342 | function getSmallerAngle(angle) { 1343 | if(angle > Math.PI) 1344 | return 2*Math.PI-angle; 1345 | if(angle < -Math.PI) 1346 | return -2*Math.PI-angle 1347 | return angle; 1348 | } 1349 | 1350 | function getSmallerAngleDeg(angle) { 1351 | if(angle > 180) 1352 | return 360-angle; 1353 | if(angle < -180) 1354 | return -360-angle; 1355 | return angle; 1356 | } 1357 | 1358 | function radToDeg(angle) { 1359 | return angle*180/Math.PI; 1360 | } 1361 | 1362 | function degToRad(angle) { 1363 | return angle*Math.PI/180; 1364 | } 1365 | 1366 | function reduceAngle(angle) { 1367 | return angle-Math.floor(angle/(2*Math.PI))*2*Math.PI; 1368 | } 1369 | 1370 | function reduceAngleDeg(angle) { 1371 | return angle-Math.floor(angle/360)*360; 1372 | } 1373 | 1374 | function dot(vector1,vector2) { 1375 | return vector1[0]*vector2[0]+vector1[1]*vector2[1]; 1376 | } 1377 | 1378 | function point(vector,dir) { 1379 | var mag = getMag(vector); 1380 | return [Math.cos(dir)*mag,Math.sin(dir)*mag]; 1381 | } 1382 | 1383 | function rotate(v,rad) { 1384 | var ang = getAngle(v); 1385 | if(v[0] == 0 && v[1] == -8) { 1386 | //console.log(v); 1387 | //console.log("!"); 1388 | //console.log(ang); 1389 | //console.log(rad); 1390 | //console.log(point(v,rad+ang)); 1391 | } 1392 | return point(v,rad+ang); 1393 | } 1394 | 1395 | function midpoint(p1,p2,t) { 1396 | return add(scale(p1,1-t),scale(p2,t)); 1397 | } 1398 | 1399 | 1400 | function drawVector(vector,pos,ctx) { 1401 | ctx.beginPath(); 1402 | ctx.moveTo(pos[0],pos[1]); 1403 | ctx.lineTo(pos[0]+vector[0],pos[1]+vector[1]); 1404 | ctx.stroke(); 1405 | } -------------------------------------------------------------------------------- /AnkiDraw/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright: Michal Krassowski 3 | # License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html 4 | """ 5 | Initially based on the Anki-TouchScreen addon, updated ui and added pressure pen/stylus capabilities, perfect freehand(line smoothing) and calligrapher functionality. 6 | 7 | 8 | It adds an AnkiDraw menu entity with options like: 9 | 10 | switching AnkiDraw 11 | modifying some of the colors 12 | thickness 13 | toolbar settings 14 | 15 | 16 | If you want to contribute visit GitHub page: https://github.com/Rytisgit/Anki-StylusDraw 17 | Also, feel free to send me bug reports or feature requests. 18 | 19 | Copyright: Michal Krassowski 20 | License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html, 21 | Important parts of Javascript code inspired by http://creativejs.com/tutorials/painting-with-pixels/index.html 22 | """ 23 | 24 | __addon_name__ = "AnkiDraw" 25 | __version__ = "1.5" 26 | 27 | from pathlib import Path 28 | 29 | from aqt import mw 30 | from aqt.utils import showWarning 31 | 32 | from anki.lang import _ 33 | from anki.hooks import addHook 34 | 35 | from aqt.qt import QAction, QMenu, QColorDialog, QMessageBox, QInputDialog, QLabel,\ 36 | QPushButton, QDialog, QVBoxLayout, QComboBox, QHBoxLayout, QSpinBox, QCheckBox 37 | from aqt.qt import QKeySequence,QColor 38 | from aqt.qt import pyqtSlot as slot 39 | 40 | # Load extra JS libraries from external files to simplify the __init__.py 41 | file = Path(__file__) 42 | with open(file.with_name("Caligrapher.js"), encoding="utf8") as f: 43 | caligrapher_js = f.read() 44 | with open(file.with_name("PerfectFreehand.js"), encoding="utf8") as f: 45 | perfect_freehand_js = f.read() 46 | # This declarations are there only to be sure that in case of troubles 47 | # with "profileLoaded" hook everything will work. 48 | 49 | ts_state_on = False 50 | ts_profile_loaded = False 51 | ts_auto_hide = True 52 | ts_auto_hide_pointer = True 53 | ts_default_small_canvas = False 54 | ts_zen_mode = False 55 | ts_follow = False 56 | ts_ConvertDotStrokes = True 57 | ts_pressure_sensitivity = True 58 | 59 | ts_pen1_color = "#272828" 60 | ts_pen1_width = 4 61 | ts_pen2_color = "#149beb" 62 | ts_pen2_width = 8 63 | ts_pen3_color = "#ced51a" 64 | ts_pen3_width = 20 65 | ts_pen4_color = "#da13a8" 66 | ts_pen4_width = 2 67 | # TODO Handle opacity selection and saving 68 | ts_opacity = 0.7 69 | ts_location = 1 70 | ts_x_offset = 2 71 | ts_y_offset = 2 72 | ts_small_width = 500 73 | ts_small_height = 500 74 | ts_background_color = "#FFFFFF00" 75 | ts_orient_vertical = True 76 | ts_default_review_html = mw.reviewer.revHtml 77 | 78 | ts_default_VISIBILITY = "true" 79 | ts_default_PerfFreehand = "false" 80 | ts_default_Calligraphy = "false" 81 | 82 | def ts_save(): 83 | """ 84 | Saves configurable variables into profile, so they can 85 | be used to restore previous state after Anki restart. 86 | """ 87 | mw.pm.profile['ts_state_on'] = ts_state_on 88 | mw.pm.profile['ts_pen1_color'] = ts_pen1_color 89 | mw.pm.profile['ts_pen2_color'] = ts_pen2_color 90 | mw.pm.profile['ts_pen3_color'] = ts_pen3_color 91 | mw.pm.profile['ts_pen4_color'] = ts_pen4_color 92 | mw.pm.profile['ts_pen1_width'] = ts_pen1_width 93 | mw.pm.profile['ts_pen2_width'] = ts_pen2_width 94 | mw.pm.profile['ts_pen3_width'] = ts_pen3_width 95 | mw.pm.profile['ts_pen4_width'] = ts_pen4_width 96 | mw.pm.profile['ts_opacity'] = ts_opacity 97 | mw.pm.profile['ts_default_ConvertDotStrokes'] = ts_ConvertDotStrokes 98 | mw.pm.profile['ts_auto_hide'] = ts_auto_hide 99 | mw.pm.profile['ts_auto_hide_pointer'] = ts_auto_hide_pointer 100 | mw.pm.profile['ts_default_small_canvas'] = ts_default_small_canvas 101 | mw.pm.profile['ts_zen_mode'] = ts_zen_mode 102 | mw.pm.profile['ts_follow'] = ts_follow 103 | mw.pm.profile['ts_pressure_sensitivity'] = ts_pressure_sensitivity 104 | mw.pm.profile['ts_location'] = ts_location 105 | mw.pm.profile['ts_x_offset'] = ts_x_offset 106 | mw.pm.profile['ts_y_offset'] = ts_y_offset 107 | mw.pm.profile['ts_small_height'] = ts_small_height 108 | mw.pm.profile['ts_background_color'] = ts_background_color 109 | mw.pm.profile['ts_small_width'] = ts_small_width 110 | mw.pm.profile['ts_orient_vertical'] = ts_orient_vertical 111 | 112 | def ts_load(): 113 | """ 114 | Load configuration from profile, set states of checkable menu objects 115 | and turn on night mode if it were enabled on previous session. 116 | """ 117 | global ts_state_on, ts_pen1_color, ts_pen2_color, ts_pen3_color, ts_pen4_color, ts_profile_loaded, ts_pen1_width, ts_pen2_width, ts_pen3_width, ts_pen4_width, ts_opacity, ts_ConvertDotStrokes, ts_auto_hide, ts_auto_hide_pointer, ts_default_small_canvas, ts_zen_mode, ts_follow, ts_orient_vertical, ts_y_offset, ts_x_offset, ts_location, ts_small_width, ts_small_height, ts_background_color, ts_pressure_sensitivity 118 | try: 119 | ts_state_on = mw.pm.profile['ts_state_on'] 120 | ts_opacity = mw.pm.profile['ts_opacity'] 121 | ts_auto_hide = mw.pm.profile['ts_auto_hide'] 122 | ts_auto_hide_pointer = mw.pm.profile['ts_auto_hide_pointer'] 123 | ts_default_small_canvas = mw.pm.profile['ts_default_small_canvas'] 124 | ts_zen_mode = mw.pm.profile['ts_zen_mode'] 125 | ts_follow = mw.pm.profile['ts_follow'] 126 | ts_pressure_sensitivity = mw.pm.profile.get('ts_pressure_sensitivity', True) 127 | ts_ConvertDotStrokes = bool(mw.pm.profile['ts_default_ConvertDotStrokes'])#fix for previously being a string value, defaults string value to true bool, will be saved as true or false bool after 128 | ts_orient_vertical = mw.pm.profile['ts_orient_vertical'] 129 | ts_y_offset = mw.pm.profile['ts_y_offset'] 130 | ts_small_width = mw.pm.profile['ts_small_width'] 131 | ts_small_height = mw.pm.profile['ts_small_height'] 132 | ts_background_color = mw.pm.profile['ts_background_color'] 133 | ts_x_offset = mw.pm.profile['ts_x_offset'] 134 | ts_location = mw.pm.profile['ts_location'] 135 | except KeyError: 136 | ts_state_on = True 137 | ts_pen1_width = 4 138 | ts_opacity = 0.8 139 | ts_auto_hide = True 140 | ts_auto_hide_pointer = True 141 | ts_default_small_canvas = False 142 | ts_zen_mode = False 143 | ts_follow = False 144 | ts_pressure_sensitivity = True 145 | ts_ConvertDotStrokes = True 146 | ts_orient_vertical = True 147 | ts_y_offset = 2 148 | ts_small_width = 500 149 | ts_small_height = 500 150 | ts_background_color = "#FFFFFF00" 151 | ts_x_offset = 2 152 | ts_location = 1 153 | 154 | try: 155 | ts_pen1_color = mw.pm.profile['ts_pen1_color'] 156 | ts_pen2_color = mw.pm.profile['ts_pen2_color'] 157 | ts_pen3_color = mw.pm.profile['ts_pen3_color'] 158 | ts_pen4_color = mw.pm.profile['ts_pen4_color'] 159 | except KeyError: 160 | ts_pen1_color = "#272828" 161 | ts_pen2_color = "#149beb" 162 | ts_pen3_color = "#ced51a" 163 | ts_pen4_color = "#da13a8" 164 | 165 | try: 166 | ts_pen1_width = mw.pm.profile['ts_pen1_width'] 167 | ts_pen2_width = mw.pm.profile['ts_pen2_width'] 168 | ts_pen3_width = mw.pm.profile['ts_pen3_width'] 169 | ts_pen4_width = mw.pm.profile['ts_pen4_width'] 170 | except KeyError: 171 | ts_pen1_width = 4 172 | ts_pen2_width = 6 173 | ts_pen3_width = 20 174 | ts_pen4_width = 8 175 | 176 | 177 | 178 | ts_profile_loaded = True 179 | ts_menu_auto_hide.setChecked(ts_auto_hide) 180 | ts_menu_auto_hide_pointer.setChecked(ts_auto_hide_pointer) 181 | ts_menu_small_default.setChecked(ts_default_small_canvas) 182 | ts_menu_zen_mode.setChecked(ts_zen_mode) 183 | ts_menu_follow.setChecked(ts_follow) 184 | ts_menu_pressure.setChecked(ts_pressure_sensitivity) 185 | ts_menu_dots.setChecked(ts_ConvertDotStrokes) 186 | if ts_state_on: 187 | ts_on() 188 | 189 | assure_plugged_in() 190 | 191 | def execute_js(code): 192 | web_object = mw.reviewer.web 193 | web_object.eval(code) 194 | 195 | def assure_plugged_in(): 196 | global ts_default_review_html 197 | if not mw.reviewer.revHtml == custom: 198 | ts_default_review_html = mw.reviewer.revHtml 199 | mw.reviewer.revHtml = custom 200 | 201 | def resize_js(): 202 | execute_js("if (typeof resize === 'function') { setTimeout(resize, 101); }"); 203 | 204 | def clear_blackboard(): 205 | assure_plugged_in() 206 | 207 | if ts_state_on: 208 | execute_js("if (typeof clear_canvas === 'function') { clear_canvas(); }") 209 | # is qFade the reason for having to wait? 210 | execute_js("if (typeof resize === 'function') { setTimeout(resize, 101); }"); 211 | 212 | def blackboard_html(): 213 | return u""" 214 |
215 | 216 | 217 | 218 |
219 | 220 | 224 | 225 | 229 | 230 | 234 | 235 | 239 | 240 | 244 | 245 | 253 | 254 | 258 | 259 | 263 | 264 | 268 | 269 | 273 | 274 | 278 | 279 |
280 |
281 | """ 282 | 283 | def get_css_for_toolbar_location(location, x_offset, y_offset, orient_column, canvas_width, canvas_height, background_color): 284 | orient = "column" if orient_column else "row" 285 | switch = { 286 | 0: f""" 287 | --button-bar-pt: {y_offset}px; 288 | --button-bar-pr: unset; 289 | --button-bar-pb: unset; 290 | --button-bar-pl: {x_offset}px; 291 | --button-bar-orientation: {orient}; 292 | --small-canvas-height: {canvas_height}; 293 | --small-canvas-width: {canvas_width}; 294 | --background-color: {background_color}; 295 | """, 296 | 1: f""" 297 | --button-bar-pt: {y_offset}px; 298 | --button-bar-pr: {x_offset}px; 299 | --button-bar-pb: unset; 300 | --button-bar-pl: unset; 301 | --button-bar-orientation: {orient}; 302 | --small-canvas-height: {canvas_height}; 303 | --small-canvas-width: {canvas_width}; 304 | --background-color: {background_color}; 305 | """, 306 | 2: f""" 307 | --button-bar-pt: unset; 308 | --button-bar-pr: unset; 309 | --button-bar-pb: {y_offset}px; 310 | --button-bar-pl: {x_offset}px; 311 | --button-bar-orientation: {orient}; 312 | --small-canvas-height: {canvas_height}; 313 | --small-canvas-width: {canvas_width}; 314 | --background-color: {background_color}; 315 | """, 316 | 3: f""" 317 | --button-bar-pt: unset; 318 | --button-bar-pr: {x_offset}px; 319 | --button-bar-pb: {y_offset}px; 320 | --button-bar-pl: unset; 321 | --button-bar-orientation: {orient}; 322 | --small-canvas-height: {canvas_height}; 323 | --small-canvas-width: {canvas_width}; 324 | --background-color: {background_color}; 325 | """, 326 | } 327 | return switch.get(location, """ 328 | --button-bar-pt: 2px; 329 | --button-bar-pr: 2px; 330 | --button-bar-pb: unset; 331 | --button-bar-pl: unset; 332 | --button-bar-orientation: column; 333 | --small-canvas-height: 500; 334 | --small-canvas-width: 500; 335 | --background-color: #FFFFFF00; 336 | """) 337 | 338 | def get_css_for_auto_hide(auto_hide, zen): 339 | return "none" if auto_hide or zen else "flex" 340 | 341 | def get_css_for_zen_mode(hide): 342 | return "none" if hide else "flex" 343 | 344 | def get_css_for_auto_hide_pointer(auto_hide): 345 | return "none" if auto_hide else "default" 346 | 347 | def blackboard_css(): 348 | return u""" 349 | """ 416 | 417 | def blackboard_js(): 418 | return u""" 419 | 1357 | """ 1358 | 1359 | def custom(*args, **kwargs): 1360 | global ts_state_on 1361 | default = ts_default_review_html(*args, **kwargs) 1362 | if not ts_state_on: 1363 | return default 1364 | output = ( 1365 | default + 1366 | blackboard_html() + 1367 | blackboard_css() + 1368 | blackboard_js() + 1369 | "" 1373 | ) 1374 | return output 1375 | mw.reviewer.revHtml = custom 1376 | 1377 | @slot() 1378 | def ts_change_pen_color(pen_number): 1379 | """ 1380 | Open color picker and set chosen color for the specified pen. 1381 | """ 1382 | # Get current color from global variable 1383 | current_color = globals()[f"ts_pen{pen_number}_color"] 1384 | qcolor_old = QColor(current_color) 1385 | qcolor = QColorDialog.getColor(qcolor_old) 1386 | 1387 | if qcolor.isValid(): 1388 | # Update the global variable 1389 | globals()[f"ts_pen{pen_number}_color"] = qcolor.name() 1390 | 1391 | # Reload the reviewer to apply the new color 1392 | execute_js(f"pen{pen_number}Color = '{qcolor.name()}';") 1393 | execute_js("if (typeof update_pen_settings === 'function') { update_pen_settings(); }") 1394 | 1395 | @slot() 1396 | def ts_change_pen_width(pen_number): 1397 | """ 1398 | Open width picker and set chosen width for the specified pen. 1399 | """ 1400 | # Get current width from global variable 1401 | current_width = globals()[f"ts_pen{pen_number}_width"] 1402 | value, accepted = QInputDialog.getDouble(mw, "AnkiDraw", f"Enter the pen {pen_number} width:", current_width) 1403 | 1404 | if accepted: 1405 | # Update the global variable 1406 | globals()[f"ts_pen{pen_number}_width"] = value 1407 | 1408 | # Reload the reviewer to apply the new width 1409 | execute_js(f"pen{pen_number}Width = '{value}';") 1410 | execute_js("if (typeof update_pen_settings === 'function') { update_pen_settings(); }") 1411 | 1412 | @slot() 1413 | def ts_change_opacity(): 1414 | global ts_opacity 1415 | value, accepted = QInputDialog.getDouble(mw, "AnkiDraw", "Enter the opacity (0 = transparent, 100 = opaque):", 100 * ts_opacity, 0, 100, 2) 1416 | if accepted: 1417 | ts_opacity = value / 100 1418 | execute_js("canvas.style.opacity = " + str(ts_opacity)) 1419 | 1420 | class CustomDialog(QDialog): 1421 | def __init__(self): 1422 | super().__init__() 1423 | 1424 | self.setWindowTitle("AnkiDraw Toolbar And Canvas") 1425 | 1426 | self.combo_box = QComboBox() 1427 | self.combo_box.addItem("Top-Left") 1428 | self.combo_box.addItem("Top-Right") 1429 | self.combo_box.addItem("Bottom-Left") 1430 | self.combo_box.addItem("Bottom-Right") 1431 | 1432 | combo_label = QLabel("Location:") 1433 | 1434 | range_label = QLabel("Offset:") 1435 | 1436 | start_range_label = QLabel("X Offset:") 1437 | self.start_spin_box = QSpinBox() 1438 | self.start_spin_box.setRange(0, 1000) 1439 | 1440 | small_width_label = QLabel("Non-Fullscreen Canvas Width:") 1441 | self.small_width_spin_box = QSpinBox() 1442 | self.small_width_spin_box.setRange(0, 9999) 1443 | 1444 | small_height_label = QLabel("Non-Fullscreen Canvas Height:") 1445 | self.small_height_spin_box = QSpinBox() 1446 | self.small_height_spin_box.setRange(0, 9999) 1447 | 1448 | end_range_label = QLabel("Y Offset:") 1449 | self.end_spin_box = QSpinBox() 1450 | self.end_spin_box.setRange(0, 1000) 1451 | 1452 | range_layout = QVBoxLayout() 1453 | 1454 | small_height_layout = QHBoxLayout() 1455 | small_height_layout.addWidget(small_height_label) 1456 | small_height_layout.addWidget(self.small_height_spin_box) 1457 | 1458 | small_width_layout = QHBoxLayout() 1459 | small_width_layout.addWidget(small_width_label) 1460 | small_width_layout.addWidget(self.small_width_spin_box) 1461 | 1462 | color_layout = QHBoxLayout() 1463 | self.color_button = QPushButton("Select Color") 1464 | self.color_button.clicked.connect(self.select_color) 1465 | 1466 | self.color_label = QLabel("Background color: #FFFFFF00") # Initial color label 1467 | 1468 | color_layout.addWidget(self.color_label) 1469 | color_layout.addWidget(self.color_button) 1470 | 1471 | start_layout = QHBoxLayout() 1472 | start_layout.addWidget(start_range_label) 1473 | start_layout.addWidget(self.start_spin_box) 1474 | 1475 | end_layout = QHBoxLayout() 1476 | end_layout.addWidget(end_range_label) 1477 | end_layout.addWidget(self.end_spin_box) 1478 | range_layout.addLayout(start_layout) 1479 | range_layout.addLayout(end_layout) 1480 | range_layout.addLayout(small_width_layout) 1481 | range_layout.addLayout(small_height_layout) 1482 | 1483 | 1484 | checkbox_label2 = QLabel("Orient vertically:") 1485 | self.checkbox2 = QCheckBox() 1486 | 1487 | checkbox_layout2 = QHBoxLayout() 1488 | checkbox_layout2.addWidget(checkbox_label2) 1489 | checkbox_layout2.addWidget(self.checkbox2) 1490 | 1491 | accept_button = QPushButton("Accept") 1492 | cancel_button = QPushButton("Cancel") 1493 | reset_button = QPushButton("Default") 1494 | 1495 | accept_button.clicked.connect(self.accept) 1496 | cancel_button.clicked.connect(self.reject) 1497 | reset_button.clicked.connect(self.reset_to_default) 1498 | 1499 | button_layout = QHBoxLayout() 1500 | button_layout.addWidget(accept_button) 1501 | button_layout.addWidget(reset_button) 1502 | button_layout.addWidget(cancel_button) 1503 | 1504 | 1505 | dialog_layout = QVBoxLayout() 1506 | dialog_layout.addWidget(combo_label) 1507 | dialog_layout.addWidget(self.combo_box) 1508 | dialog_layout.addWidget(range_label) 1509 | dialog_layout.addLayout(range_layout) 1510 | dialog_layout.addLayout(checkbox_layout2) 1511 | dialog_layout.addLayout(color_layout) 1512 | dialog_layout.addLayout(button_layout) 1513 | 1514 | self.setLayout(dialog_layout) 1515 | 1516 | def set_values(self, combo_index, start_value, end_value, checkbox_state2, width, height, background_color): 1517 | self.combo_box.setCurrentIndex(combo_index) 1518 | self.start_spin_box.setValue(start_value) 1519 | self.small_height_spin_box.setValue(height) 1520 | self.small_width_spin_box.setValue(width) 1521 | self.end_spin_box.setValue(end_value) 1522 | self.checkbox2.setChecked(checkbox_state2) 1523 | self.color_label.setText(f"Background color: {background_color}") 1524 | 1525 | def reset_to_default(self): 1526 | self.combo_box.setCurrentIndex(1) 1527 | self.start_spin_box.setValue(2) 1528 | self.end_spin_box.setValue(2) 1529 | self.small_height_spin_box.setValue(500) 1530 | self.small_width_spin_box.setValue(500) 1531 | self.checkbox2.setChecked(True) 1532 | self.color_label.setText("Background color: #FFFFFF00") # Reset color label 1533 | 1534 | def select_color(self): 1535 | color_dialog = QColorDialog() 1536 | qcolor_old = QColor(self.color_label.text()[-9:-2]) 1537 | color = color_dialog.getColor(qcolor_old, options=QColorDialog.ColorDialogOption.ShowAlphaChannel) 1538 | if color.isValid(): 1539 | self.color_label.setText(f"Background color: {(color.name()+color.name(QColor.NameFormat.HexArgb)[1:3]).upper()}") # Update color label 1540 | 1541 | @slot() 1542 | def ts_change_toolbar_settings(): 1543 | global ts_orient_vertical, ts_y_offset, ts_x_offset, ts_location, ts_small_width, ts_small_height, ts_background_color 1544 | 1545 | dialog = CustomDialog() 1546 | dialog.set_values(ts_location, ts_x_offset, ts_y_offset, ts_orient_vertical, ts_small_width, ts_small_height, ts_background_color) 1547 | result = dialog.exec() 1548 | 1549 | if result == QDialog.DialogCode.Accepted: 1550 | ts_location = dialog.combo_box.currentIndex() 1551 | ts_x_offset = dialog.start_spin_box.value() 1552 | ts_y_offset = dialog.end_spin_box.value() 1553 | ts_small_height = dialog.small_height_spin_box.value() 1554 | ts_background_color = dialog.color_label.text()[-9:] 1555 | ts_small_width = dialog.small_width_spin_box.value() 1556 | ts_orient_vertical = dialog.checkbox2.isChecked() 1557 | ts_switch() 1558 | ts_switch() 1559 | 1560 | @slot() 1561 | def ts_dots(): 1562 | """ 1563 | Switch dot conversion. 1564 | """ 1565 | global ts_ConvertDotStrokes 1566 | ts_ConvertDotStrokes = not ts_ConvertDotStrokes 1567 | execute_js("convertDotStrokes = " + str(ts_ConvertDotStrokes).lower() + ";") 1568 | execute_js("if (typeof resize === 'function') { resize(); }") 1569 | 1570 | @slot() 1571 | def ts_change_auto_hide_settings(): 1572 | """ 1573 | Switch auto hide toolbar setting. 1574 | """ 1575 | global ts_auto_hide 1576 | ts_auto_hide = not ts_auto_hide 1577 | ts_switch() 1578 | ts_switch() 1579 | 1580 | @slot() 1581 | def ts_change_follow_settings(): 1582 | """ 1583 | Switch whiteboard follow screen. 1584 | """ 1585 | global ts_follow 1586 | ts_follow = not ts_follow 1587 | execute_js("fullscreen_follow = " + str(ts_follow).lower() + ";") 1588 | execute_js("if (typeof resize === 'function') { resize(); }") 1589 | 1590 | @slot() 1591 | def ts_change_small_default_settings(): 1592 | """ 1593 | Switch default small canvas mode setting. 1594 | """ 1595 | global ts_default_small_canvas 1596 | ts_default_small_canvas = not ts_default_small_canvas 1597 | ts_switch() 1598 | ts_switch() 1599 | 1600 | @slot() 1601 | def ts_change_zen_mode_settings(): 1602 | """ 1603 | Switch default zen mode setting. 1604 | """ 1605 | global ts_zen_mode 1606 | ts_zen_mode = not ts_zen_mode 1607 | ts_switch() 1608 | ts_switch() 1609 | 1610 | @slot() 1611 | def ts_change_pressure_sensitivity_settings(): 1612 | """ 1613 | Switch pressure sensitivity setting. 1614 | """ 1615 | global ts_pressure_sensitivity 1616 | ts_pressure_sensitivity = not ts_pressure_sensitivity 1617 | execute_js("pressureSensitivity = " + str(ts_pressure_sensitivity).lower() + ";") 1618 | execute_js("if (typeof resize === 'function') { resize(); }") 1619 | 1620 | @slot() 1621 | def ts_change_auto_hide_pointer_settings(): 1622 | """ 1623 | Switch auto hide pointer setting. 1624 | """ 1625 | global ts_auto_hide_pointer 1626 | ts_auto_hide_pointer = not ts_auto_hide_pointer 1627 | ts_switch() 1628 | ts_switch() 1629 | 1630 | def checkProfile(): 1631 | if not ts_profile_loaded: 1632 | showWarning("No profile loaded. AnkiPenDown may not work correctly.") 1633 | return False 1634 | return True 1635 | 1636 | def ts_on(): 1637 | """ 1638 | Turn on 1639 | """ 1640 | if not checkProfile(): return 1641 | 1642 | global ts_state_on 1643 | ts_state_on = True 1644 | ts_menu_switch.setChecked(True) 1645 | return True 1646 | 1647 | def ts_off(): 1648 | """ 1649 | Turn off 1650 | """ 1651 | if not checkProfile(): return 1652 | 1653 | global ts_state_on 1654 | ts_state_on = False 1655 | ts_menu_switch.setChecked(False) 1656 | return True 1657 | 1658 | @slot() 1659 | def ts_switch(): 1660 | """ 1661 | Switch AnkiDraw. 1662 | """ 1663 | if ts_state_on: 1664 | ts_off() 1665 | else: 1666 | ts_on() 1667 | # Reload current screen. 1668 | if mw.state == "review": 1669 | mw.moveToState("review") 1670 | elif mw.state == "deckBrowser": 1671 | mw.deckBrowser.refresh() 1672 | elif mw.state == "overview": 1673 | mw.overview.refresh() 1674 | 1675 | def ts_setup_menu(): 1676 | """ 1677 | Initialize menu. 1678 | """ 1679 | global ts_menu_switch, ts_menu_dots, ts_menu_auto_hide, ts_menu_auto_hide_pointer, ts_menu_small_default, ts_menu_zen_mode, ts_menu_follow, ts_menu_pressure 1680 | 1681 | try: 1682 | mw.addon_view_menu 1683 | except AttributeError: 1684 | mw.addon_view_menu = QMenu("""&AnkiDraw""", mw) 1685 | mw.form.menubar.insertMenu(mw.form.menuTools.menuAction(), 1686 | mw.addon_view_menu) 1687 | 1688 | # mw.ts_menu = QMenu(_('&AnkiDraw'), mw) 1689 | 1690 | # mw.addon_view_menu.addMenu(mw.ts_menu) 1691 | 1692 | ts_menu_switch = QAction("""&Enable Ankidraw""", mw, checkable=True) 1693 | ts_menu_dots = QAction("""Convert &dot strokes on PF mode""", mw, checkable=True) 1694 | ts_menu_pressure = QAction("""Enable &pressure sensitivity""", mw, checkable=True) 1695 | ts_menu_auto_hide = QAction("""Auto &hide toolbar when drawing""", mw, checkable=True) 1696 | ts_menu_auto_hide_pointer = QAction("""Auto &hide pointer when drawing""", mw, checkable=True) 1697 | ts_menu_follow = QAction("""&Follow when scrolling (faster on big cards)""", mw, checkable=True) 1698 | ts_menu_small_default = QAction("""&Small Canvas by default""", mw, checkable=True) 1699 | ts_menu_zen_mode = QAction("""Enable Zen Mode(hide toolbar until disabled)""", mw, checkable=True) 1700 | ts_menu_opacity = QAction("""Set pen &opacity""", mw) 1701 | ts_toolbar_settings = QAction("""&Toolbar and canvas location settings""", mw) 1702 | 1703 | ts_toggle_seq = QKeySequence("Ctrl+r") 1704 | ts_menu_switch.setShortcut(ts_toggle_seq) 1705 | 1706 | ts_pen_color_menu = QMenu("Set pen 1-4 color", mw) 1707 | ts_menu_pen1_color = QAction("Set Pen 1 Color", mw) 1708 | ts_menu_pen2_color = QAction("Set Pen 2 Color", mw) 1709 | ts_menu_pen3_color = QAction("Set Pen 3 Color", mw) 1710 | ts_menu_pen4_color = QAction("Set Pen 4 Color", mw) 1711 | ts_pen_color_menu.addAction(ts_menu_pen1_color) 1712 | ts_pen_color_menu.addAction(ts_menu_pen2_color) 1713 | ts_pen_color_menu.addAction(ts_menu_pen3_color) 1714 | ts_pen_color_menu.addAction(ts_menu_pen4_color) 1715 | 1716 | ts_pen_width_menu = QMenu("Set pen 1-4 width", mw) 1717 | ts_menu_pen1_width = QAction("Set Pen 1 width", mw) 1718 | ts_menu_pen2_width = QAction("Set Pen 2 width", mw) 1719 | ts_menu_pen3_width = QAction("Set Pen 3 width", mw) 1720 | ts_menu_pen4_width = QAction("Set Pen 4 width", mw) 1721 | ts_pen_width_menu.addAction(ts_menu_pen1_width) 1722 | ts_pen_width_menu.addAction(ts_menu_pen2_width) 1723 | ts_pen_width_menu.addAction(ts_menu_pen3_width) 1724 | ts_pen_width_menu.addAction(ts_menu_pen4_width) 1725 | 1726 | mw.addon_view_menu.addAction(ts_menu_switch) 1727 | mw.addon_view_menu.addAction(ts_menu_dots) 1728 | mw.addon_view_menu.addAction(ts_menu_pressure) 1729 | mw.addon_view_menu.addAction(ts_menu_auto_hide) 1730 | mw.addon_view_menu.addAction(ts_menu_auto_hide_pointer) 1731 | mw.addon_view_menu.addAction(ts_menu_follow) 1732 | mw.addon_view_menu.addAction(ts_menu_small_default) 1733 | mw.addon_view_menu.addAction(ts_menu_zen_mode) 1734 | mw.addon_view_menu.addMenu(ts_pen_color_menu) 1735 | mw.addon_view_menu.addMenu(ts_pen_width_menu) 1736 | mw.addon_view_menu.addAction(ts_menu_opacity) 1737 | mw.addon_view_menu.addAction(ts_toolbar_settings) 1738 | 1739 | ts_menu_pen1_color.triggered.connect(lambda: ts_change_pen_color(1)) 1740 | ts_menu_pen2_color.triggered.connect(lambda: ts_change_pen_color(2)) 1741 | ts_menu_pen3_color.triggered.connect(lambda: ts_change_pen_color(3)) 1742 | ts_menu_pen4_color.triggered.connect(lambda: ts_change_pen_color(4)) 1743 | ts_menu_pen1_width.triggered.connect(lambda: ts_change_pen_width(1)) 1744 | ts_menu_pen2_width.triggered.connect(lambda: ts_change_pen_width(2)) 1745 | ts_menu_pen3_width.triggered.connect(lambda: ts_change_pen_width(3)) 1746 | ts_menu_pen4_width.triggered.connect(lambda: ts_change_pen_width(4)) 1747 | ts_menu_switch.triggered.connect(ts_switch) 1748 | ts_menu_dots.triggered.connect(ts_dots) 1749 | ts_menu_pressure.triggered.connect(ts_change_pressure_sensitivity_settings) 1750 | ts_menu_auto_hide.triggered.connect(ts_change_auto_hide_settings) 1751 | ts_menu_auto_hide_pointer.triggered.connect(ts_change_auto_hide_pointer_settings) 1752 | ts_menu_follow.triggered.connect(ts_change_follow_settings) 1753 | ts_menu_small_default.triggered.connect(ts_change_small_default_settings) 1754 | ts_menu_zen_mode.triggered.connect(ts_change_zen_mode_settings) 1755 | ts_menu_opacity.triggered.connect(ts_change_opacity) 1756 | ts_toolbar_settings.triggered.connect(ts_change_toolbar_settings) 1757 | 1758 | # 1759 | # ONLOAD SECTION 1760 | # 1761 | def ts_onload(): 1762 | """ 1763 | Add hooks and initialize menu. 1764 | Call to this function is placed on the end of this file. 1765 | """ 1766 | addHook("unloadProfile", ts_save) 1767 | addHook("profileLoaded", ts_load) 1768 | addHook("showQuestion", clear_blackboard) 1769 | addHook("showAnswer", resize_js) 1770 | ts_setup_menu() 1771 | 1772 | ts_onload() 1773 | --------------------------------------------------------------------------------