-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathdraw.js
726 lines (631 loc) · 21.1 KB
/
draw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/*****************************************************************************
*
* Higgs JavaScript Virtual Machine
*
* This file is part of the Higgs project. The project is distributed at:
* https://github.com/maximecb/Higgs
*
* Copyright (c) 2011-2014, Maxime Chevalier-Boisvert. All rights reserved.
*
* This software is licensed under the following license (Modified BSD
* License):
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
/**
lib/draw - provides basic drawing API using xlib
*/
(function(exports)
{
/* DEPENDENCIES */
// FFI
var ffi = require('lib/ffi');
var CNULL = ffi.nullPtr;
var isNull = ffi.isNullPtr;
var c = ffi.c;
// STDlib
require('lib/stdlib');
var poll = ffi.c.poll;
// Xlib
var Xlib = require('lib/x11');
var XEventMask = Xlib.XEventMask;
var XEvents = Xlib.XEvents;
/**
DrawError
@constructor
*/
function DrawError(message)
{
this.message = message;
}
DrawError.prototype = new Error();
DrawError.prototype.constructor = DrawError;
/**
Default settings
*/
/**
CanvasWindow
Construct a new Window object.
*/
var WindowProto = {
ptr: CNULL,
frame_rate: 60,
render_funs: null,
key_funs: null,
click_funs:null,
move_funs:null,
mousedown_funs:null,
mouseup_funs:null
};
function Window(x, y, width, height, title)
{
var display;
var screen;
var root;
var cw;
// TODO: default to center screen?
x = x || 50;
y = y || 50;
width = width || 500;
height = height || 500;
cw = Object.create(WindowProto);
cw.display = display = Xlib.XOpenDisplay(CNULL);
if (isNull(display))
{
throw 'Could not open X display';
}
// X Values
cw.screen = screen = Xlib.XDefaultScreen(display);
cw.root = root = Xlib.XRootWindow(display, screen);
cw.black_pixel = Xlib.XBlackPixel(display, screen);
cw.white_pixel = Xlib.XWhitePixel(display, screen);
// X Window properties
// TODO: default to center of screen
// other better defaults?
cw.x = x || 50;
cw.y = y || 50;
cw.width = width;
cw.height = height;
cw.title = title || 'Higgs Canvas';
// Create window
cw.create();
// Canvas
cw.canvas = Canvas(display, screen, cw.id, width, height);
// Events
cw.render_funs = [];
cw.key_funs = [];
cw.click_funs = [];
cw.move_funs = [];
cw.mouseup_funs = [];
cw.mousedown_funs = [];
return cw;
}
/**
Create the X Window
*/
WindowProto.create = function()
{
var win;
var title;
var atom_name;
var WM_DELTE_WINDOW;
var display = this.display;
var WDWAtom;
// create window
this.id = win = Xlib.XCreateSimpleWindow(
display, this.root, this.x, this.y, this.width,
this.height, 0, this.black_pixel, this.white_pixel
);
// set title (if any)
if (this.title)
{
title = ffi.cstr(this.title);
Xlib.XStoreName(display, win, title);
c.free(title);
}
// select what events to listen to
Xlib.XSelectInput(display, win,
XEventMask.ExposureMask | XEventMask.KeyPressMask
| XEventMask.ButtonPressMask | XEventMask.ButtonReleaseMask
| XEventMask.PointerMotionMask);
// we need to watch for the window closing
atom_name = ffi.cstr('WM_DELETE_WINDOW');
WM_DELTE_WINDOW = Xlib.XInternAtom(display, atom_name, 0);
ffi.c.free(atom_name);
WDWAtom = Xlib.AtomContainer();
WDWAtom.set_atom(WM_DELTE_WINDOW);
Xlib.XSetWMProtocols(display, win, WDWAtom.ptr, 1);
// set window to display
Xlib.XMapWindow(display, win);
Xlib.XFlush(display);
};
/**
Close the X display
*/
WindowProto.close = function()
{
Xlib.XCloseDisplay(this.display);
};
/**
Register a listener for the render event
*/
WindowProto.onRender = function(cb)
{
if (typeof cb === 'function')
this.render_funs.push(cb);
else
throw 'Argument not a function in onRender';
};
/**
Register a listener for a keypress event
*/
WindowProto.onKeypress = function(cb)
{
if (typeof cb === 'function')
this.key_funs.push(cb);
else
throw 'Argument not a function in onKeypress';
};
WindowProto.onClick = function(cb)
{
if (typeof cb === 'function')
this.click_funs.push(cb);
else
throw 'Argument not a function in onClick';
}
WindowProto.onMouseMove = function(cb)
{
if (typeof cb === 'function')
this.move_funs.push(cb);
else
throw 'Argument not a function in onMouseMove';
}
WindowProto.onMouseUp = function(cb)
{
if (typeof cb ==='function')
this.mouseup_funs.push(cb);
else
throw 'Argument not a function in onMouseUp';
}
WindowProto.onMouseDown = function(cb)
{
if (typeof cb ==='function')
this.mousedown_funs.push(cb);
else
throw 'Argument not a function in onMouseDown';
}
/**
Show the window, and start the event loop
*/
WindowProto.show = function()
{
// canvas/drawing
var draw = true;
var display = this.display;
var canvas = this.canvas;
var window = this.id;
var frame_rate = this.frame_rate;
// TODO: may need to check these each loop in case of resize
var width = this.width;
var height = this.height;
// timing
var work_time;
var timeout;
// events
var event = Xlib.XEvent();
var event_type;
var key_sym;
var key_name_c;
var key_name;
var e = event.ptr;
// mouse events
var xbutton = event.xbutton;
var xmotion = event.xmotion;
var mouseX;
var mouseY;
var button;
// handlers
var key_funs = this.key_funs;
var render_funs = this.render_funs;
var click_funs = this.click_funs;
var move_funs = this.move_funs;
var mouseup_funs = this.mouseup_funs;
var mousedown_funs = this.mousedown_funs;
var key_funs_i = 0;
var render_funs_i = 0;
var click_funs_i = 0;
var move_funs_i = 0;
var mouseup_funs_i = 0;
var mousedown_funs_i = 0;
// event loop
while (draw)
{
// work time includes rendering and time handling events
work_time = $ir_get_time_ms();
key_funs_i = key_funs.length;
render_funs_i = render_funs.length;
click_funs_i = click_funs.length;
move_funs_i = move_funs.length;
mouseup_funs_i = mouseup_funs.length;
mousedown_funs_i = mousedown_funs.length;
// render
while (render_funs_i > 0)
{
render_funs[--render_funs_i](canvas);
}
// Copy from Canvas buffer
Xlib.XCopyArea(display, canvas.id,
window, canvas.gc,
0, 0, width, height, 0, 0
);
// handle events
while (Xlib.XPending(display) > 0)
{
// get event
Xlib.XNextEvent(display, e);
// dispatch on event type
event_type = event.get_type();
if (event_type === XEvents.Expose)
{
// Copy from Canvas buffer
Xlib.XCopyArea(display, canvas.id,
window, canvas.gc,
0, 0, width, height, 0, 0
);
}
// onKeyPress
else if (event_type === XEvents.KeyPress)
{
// TODO: index? change to number?
key_sym = Xlib.XLookupKeysym(e, 0);
key_name_c = Xlib.XKeysymToString(key_sym);
key_name = ffi.string(key_name_c);
while (key_funs_i > 0)
{
key_funs[--key_funs_i](canvas, key_name);
}
}
// onMouseMove
else if (event_type === XEvents.MotionNotify)
{
mouseX = xmotion.get_x();
mouseY = xmotion.get_y();
while (move_funs_i > 0)
{
move_funs[--move_funs_i](canvas, mouseX, mouseY);
}
}
//onMouseUp
else if (event_type === XEvents.ButtonRelease)
{
mouseX = xbutton.get_x();
mouseY = xbutton.get_y();
button = xbutton.get_button();
if (button === 1)
button = "left";
else if (button === 2)
button = "center";
else if (button === 3)
button = "right";
else if (button === 4)
button = "wheelUp";
else if (button === 5)
button = "wheelDown"
while (mouseup_funs_i > 0)
{
mouseup_funs[--mouseup_funs_i](canvas, mouseX, mouseY, button);
}
// onClick (a normal left click)
// TODO: Use timing and XEvent buffer to
// further qualify an onClick from onMouseUp
if (button === "left")
{
while (click_funs_i > 0)
{
click_funs[--click_funs_i](canvas, mouseX, mouseY, button);
}
}
}
//OnMouseDown
else if (event_type === XEvents.ButtonPress)
{
mouseX = xbutton.get_x();
mouseY = xbutton.get_y();
button = xbutton.get_button();
if (button === 1)
button = "left";
else if (button === 2)
button = "center";
else if (button === 3)
button = "right";
else if (button === 4)
button = "wheelUp";
else if (button === 5)
button = "wheelDown";
while (mousedown_funs_i > 0)
{
mousedown_funs[--mousedown_funs_i](canvas, mouseX, mouseY, button);
}
}
else if (event_type === XEvents.ClientMessage)
{
// TODO: Should check here for other client message types -
// for now we just care about the window closing
draw = false;
}
}
// Calculate how long to wait
work_time = $ir_get_time_ms() - work_time;
timeout = 1000 / frame_rate - work_time;
if (timeout < 0)
timeout = 0;
else if ($ir_is_float64(timeout))
timeout = $ir_f64_to_i32(timeout);
// Just sleep for a bit to not grind the CPU
// TODO: eventually this should be more clever;
// polling on the X fd or hooking into some higgs
// event system so that all the libs like this can
// be used together
poll(CNULL, 0, timeout);
}
this.close();
};
/**
Canvas
An object that can be drawn on/has drawing functionality
*/
var CanvasProto = {};
function Canvas(display, screen, window, width, height)
{
var canvas = Object.create(CanvasProto);
// cleanup
canvas.id = Xlib.XCreatePixmap(display, window,
width, height,
Xlib.XDefaultDepth(display, screen)
);
canvas.display = display;
canvas.screen = screen;
canvas.window = window;
canvas.width = width;
canvas.height = height;
canvas.colormap = Xlib.XDefaultColormap(display, 0);
canvas.colors = Object.create(null);
canvas.cached_colors = 0;
canvas.gc = Xlib.XDefaultGC(display, screen);
canvas.setFont();
return canvas;
}
/**
Clear the canvas - just a shortcut for fillRect for the entire canvas
*/
CanvasProto.clear = function(color, g, b)
{
if (arguments.length === 0)
this.setColor('#000000');
else if (arguments.length === 1)
this.setColor(color);
else
this.setColor(color, g, b);
this.fillRect(0, 0, this.width, this.height);
};
/**
Set drawing color for a Canvas, accepts a hex color string
*/
CanvasProto.setColor = function(color, g, b)
{
var gc = this.gc;
var display = this.display;
var colormap;
var XColor;
var color_string_c;
var color_string;
// check whether r,g,b values were passed individually or as a string
if (typeof b === 'number')
{
color_string = '#' + color.toString(16);
if (color_string.length === 2)
color_string += '0';
color_string += g.toString(16);
if (color_string.length === 4)
color_string += '0';
color_string += b.toString(16);
if (color_string.length === 6)
color_string += '0';
}
else if (color && color[0] === '#')
{
color_string = color;
}
else
{
throw new DrawError('Invalid argument in setFG');
}
// Check if we have a graphics context for this color
XColor = this.colors[color_string];
if (XColor)
{
Xlib.XSetForeground(display, gc, XColor.get_pixel());
return true;
}
// .. if not we need to create one
color_string_c = ffi.cstr(color_string);
XColor = Xlib.XColor();
colormap = this.colormap;
Xlib.XParseColor(display, colormap, color_string_c, XColor.ptr);
Xlib.XAllocColor(display, colormap, XColor.ptr);
Xlib.XSetForeground(display, gc, XColor.get_pixel());
// TODO: error checking?
// Cleanup
c.free(color_string_c);
if (this.cached_colors < 256)
{
this.colors[color_string] = XColor;
this.cached_colors += 1;
}
else
{
c.free(XColor.ptr);
}
return true;
};
/**
drawPoint - draw a point
*/
CanvasProto.drawPoint = function(x, y)
{
// Convert FP to int
if (!$ir_is_int32(x))
{
x = $rt_toInt32(x);
}
if (!$ir_is_int32(y))
{
y = rt_toInt32(y);
}
Xlib.XDrawPoint(this.display, this.id, this.gc, x, y);
};
/**
drawLine - draw a line
*/
CanvasProto.drawLine = function(x1, y1, x2, y2)
{
Xlib.XDrawLine(this.display, this.id, this.gc, x1, y1, x2, y2);
};
/**
drawRect - draw a rectangle
*/
CanvasProto.drawRect = function(x, y, width, height)
{
Xlib.XDrawRectangle(this.display, this.id, this.gc, x, y, width, height);
};
/**
drawArc - draw an arc
*/
CanvasProto.drawArc = function(x, y, width, height, angle1, angle2)
{
Xlib.XDrawArc(this.display, this.id, this.gc, x, y, width, height, angle1, angle2);
};
/**
drawCircle - draw a circle
*/
CanvasProto.drawCircle = function(x, y, radius)
{
var diameter = radius * 2;
Xlib.XDrawArc(this.display, this.id, this.gc,
x - radius, y - radius, diameter, diameter, 0, 23040);
};
/**
fillRect - fill a rectangle
*/
CanvasProto.fillRect = function(x, y, width, height)
{
Xlib.XFillRectangle(this.display, this.id,
this.gc, x, y, width, height);
};
/**
fillCircle - fill a circle
*/
CanvasProto.fillCircle = function(x, y, radius)
{
var diameter = radius * 2;
Xlib.XFillArc(this.display, this.id, this.gc,
x - radius, y - radius, diameter, diameter, 0, 23040);
};
/**
setFont - set the font to use
*/
CanvasProto.setFont = function(name, size)
{
var font_str;
var font_name_c;
var font_ptr;
size = (typeof size === 'number') ? size : 40;
// If a font name is not specified, just try to use any monospaced font
if (typeof name !== 'string')
font_str = '-*-*-*-*-*-*-' + size + '-*-*-*-m-*-*-*';
else
font_str = '-*-' + name + '-*-*-*-*-' + size + '-*-*-*-*-*-*-*';
font_name_c = ffi.cstr(font_str);
font_ptr = Xlib.XLoadQueryFont(this.display, font_name_c);
// Check if the font failed to load
if (isNull(font_ptr))
{
// If they specified a name and it failed, try for a default
if (name)
{
this.setFont(null, size);
}
else
{
// cleanup and throw
c.free(font_name_c);
throw 'Unable to load font: ' + (name ? name : 'default');
}
}
else
{
this.font = Xlib.XFontStruct(font_ptr);
Xlib.XSetFont(this.display, this.gc, this.font.get_fid());
}
// cleanup
c.free(font_name_c);
};
/**
drawText - draw some text
*/
var TextItem = Xlib.XTextItem();
CanvasProto.drawText = function (x, y, text)
{
// TODO: wchars
var text_c = ffi.cstr(text);
var text_l = text.length;
TextItem.set_chars(text_c);
TextItem.set_nchars(text_l);
TextItem.set_delta(0);
TextItem.set_font(this.font.get_fid());
Xlib.XDrawText(this.display, this.id, this.gc, x, y, TextItem.ptr, 1);
c.free(text_c);
};
/**
Draw an image object (see lib/image) onto the canvas
*/
CanvasProto.drawImage = function (x, y, img)
{
// TODO: use Pixmap objects to make this faster
for (var imgY = 0; imgY < img.height; ++imgY)
{
for (var imgX = 0; imgX < img.width; ++imgX)
{
var pix = img.getPixel(imgX, imgY);
this.setColor(pix.r, pix.g, pix.b);
this.drawPoint(x + imgX, y + imgY);
}
}
}
/**
EXPORTS
*/
exports.Window = Window;
})(exports);