-
Notifications
You must be signed in to change notification settings - Fork 38
/
plask.js
2273 lines (1972 loc) · 71.7 KB
/
plask.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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Plask.
// (c) Dean McNamee <dean@gmail.com>, 2010.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
var sys = require('sys');
var fs = require('fs');
var path = require('path');
var events = require('events');
var net = require('net');
var inherits = sys.inherits;
exports.SkPath = PlaskRawMac.SkPath;
exports.SkPaint = PlaskRawMac.SkPaint;
exports.SkCanvas = PlaskRawMac.SkCanvas;
exports.AVPlayer = PlaskRawMac.AVPlayer;
// NOTE(deanm): The SkCanvas constructor has become too complicated in
// supporting different types of canvases and ways to create them. Use one of
// the following factory functions instead of calling the constructor directly.
// static SkCanvas createFromImage(filename)
//
// Create a bitmap SkCanvas with the size/pixels from an image `filename`.
exports.SkCanvas.createFromImage = function(path) {
return new exports.SkCanvas('^IMG', path);
};
// static SkCanvas createFromImageData(data)
//
// Create a bitmap SkCanvas with the size/pixels from an image `data`.
exports.SkCanvas.createFromImageData = function(data) {
return new exports.SkCanvas('^IMG', data);
};
// static SkCanvas create(width, height)
//
// Create a bitmap SkCanvas with the specified size.
exports.SkCanvas.create = function(width, height) {
return new exports.SkCanvas(width, height);
};
// Sizes are in points, at 72 points per inch, letter would be 612x792.
// That makes A4 about 595x842.
// TODO(deanm): The sizes are integer, check the right size to use for A4.
// static SkCanvas createForPDF(filename, page_width, page_height, content_width, content_height)
//
// Create a new vector-mode SkCanvas that can be written to a PDF with `writePDF`.
exports.SkCanvas.createForPDF = function(filename, page_width, page_height,
content_width, content_height) {
return new exports.SkCanvas(
'%PDF',
filename, page_width, page_height,
content_width === undefined ? page_width : content_width,
content_height === undefined ? page_height : content_height);
};
var kPI = 3.14159265358979323846264338327950288;
var kPI2 = 1.57079632679489661923132169163975144;
var kPI4 = 0.785398163397448309615660845819875721;
var k2PI = 6.28318530717958647692528676655900576;
var kLN2 = 0.693147180559945309417232121458176568;
var kLN10 = 2.30258509299404568401799145468436421;
// float min(float a, float b)
function min(a, b) {
if (a < b) return a;
return b;
}
// float max(float a, float b)
function max(a, b) {
if (a > b) return a;
return b;
}
// float clamp(float v, float vmin, float vmax)
//
// GLSL clamp. Keep the value `v` in the range `vmin` .. `vmax`.
function clamp(v, vmin, vmax) {
return min(vmax, max(vmin, v));
}
// float lerp(float a, float b, float t)
//
// Linear interpolation on the line along points (0, `a`) and (1, `b`). The
// position `t` is the x coordinate, where 0 is `a` and 1 is `b`.
function lerp(a, b, t) {
return a + (b-a)*t;
}
// float smoothstep(edge0, edge1, x)
//
// GLSL smoothstep. NOTE: Undefined if edge0 == edge1.
function smoothstep(edge0, edge1, x) {
var t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - t - t);
}
// float smootherstep(edge0, edge1, x)
//
// Ken Perlin's "smoother" step function, with zero 1st and 2nd derivatives at
// the endpoints (whereas smoothstep has a 2nd derivative of +/- 6). This is
// also for example used by Patel and Taylor in smooth simulation noise.
function smootherstep(edge0, edge1, x) {
var t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
return t * t * t * (t * (t * 6 - 15) + 10);
}
// http://en.wikipedia.org/wiki/Fractional_part
//
// There are various conflicting ways to extend the fractional part function to
// negative numbers. It is either defined as frac(x) = x - floor(x)
// (Graham, Knuth & Patashnik 1992), as the part of the number to the
// right of the radix point, frac(x) = |x| - floor(|x|)
// (Daintith 2004), or as the odd function:
// frac(x) = x - floor(x), x >= 0
// x - ceil(x), x < 0
// float fract(float x)
//
// Like GLSL fract(), returns x - floor(x). NOTE, for negative numbers, this
// is a positive value, ex fract(-1.3) == 0.7.
function fract(x) { return x - Math.floor(x); }
// float fract2(float x)
//
// Returns the part of the number to the right of the radix point.
// For negative numbers, this is a positive value, ex fract(-1.25) == 0.25
function fract2(x) { return x < 0 ? (x|0) - x : x - (x|0); }
// float fract3(float x)
//
// Returns the signed part of the number to the right of the radix point.
// For negative numbers, this is a negative value, ex fract(-1.25) == -0.25
function fract3(x) { return x - (x|0); }
// Test if `num` is a floating point -0.
function isNegZero(num) {
return 1/num === -Infinity;
}
PlaskRawMac.NSOpenGLContext.prototype.vertexAttrib1fv = function(idx, seq) {
this.vertexAttrib1f(idx, seq[0]);
};
PlaskRawMac.NSOpenGLContext.prototype.vertexAttrib2fv = function(idx, seq) {
this.vertexAttrib2f(idx, seq[0], seq[1]);
};
PlaskRawMac.NSOpenGLContext.prototype.vertexAttrib3fv = function(idx, seq) {
this.vertexAttrib3f(idx, seq[0], seq[1], seq[2]);
};
PlaskRawMac.NSOpenGLContext.prototype.vertexAttrib4fv = function(idx, seq) {
this.vertexAttrib4f(idx, seq[0], seq[1], seq[2], seq[3]);
};
var flipper_paint = new exports.SkPaint;
flipper_paint.setXfermodeMode(flipper_paint.kSrcMode);
PlaskRawMac.NSOpenGLContext.prototype.texImage2DSkCanvas = function(a, b, c) {
var width = c.width, height = c.height;
var flipped = exports.SkCanvas.create(width, height);
flipped.translate(0, height);
flipped.scale(1, -1);
flipped.drawCanvas(flipper_paint, c, 0, 0, width, height);
var result = this.texImage2DSkCanvasB(a, b, flipped);
return result;
};
PlaskRawMac.NSOpenGLContext.prototype.texImage2DSkCanvasNoFlip = function() {
return this.texImage2DSkCanvasB.apply(this, arguments);
};
PlaskRawMac.CAMIDISource.prototype.noteOn = function(chan, note, vel, ns) {
return this.sendData([0x90 | (chan & 0xf), note & 0x7f, vel & 0x7f], ns);
};
PlaskRawMac.CAMIDISource.prototype.noteOff = function(chan, note, vel, ns) {
return this.sendData([0x80 | (chan & 0xf), note & 0x7f, vel & 0x7f], ns);
};
// Pitch wheel takes a value between -1 .. 1, and will be mapped to 14-bit midi.
PlaskRawMac.CAMIDISource.prototype.pitchWheel = function(chan, val) {
var bits = clamp((val * 0.5 + 0.5) * 16384, 0, 16383); // Not perfect at +1.
return this.sendData([0xe0 | (chan & 0xf), bits & 0x7f, (bits >> 7) & 0x7f]);
};
PlaskRawMac.CAMIDISource.prototype.controller = function(chan, con, val) {
return this.sendData([0xb0 | (chan & 0xf), con & 0x7f, val & 0x7f]);
};
PlaskRawMac.CAMIDISource.prototype.programChange = function(chan, val) {
return this.sendData([0xc0 | (chan & 0xf), val & 0x7f]);
};
inherits(PlaskRawMac.CAMIDIDestination, events.EventEmitter);
PlaskRawMac.CAMIDIDestination.prototype.on = function(evname, callback) {
// TODO(deanm): Move initialization to constructor (need to shim it).
if (this._sock_initialized !== true) {
var sock = new net.Socket({fd: this.getPipeDescriptor()});
sock.writable = false;
var this_ = this;
function processMessage(msg) {
if (msg.length < 1) return 'Received zero length midi message.';
// NOTE(deanm): I would have assumed that every MIDI message should come
// in as its own 'packet', but for example sending a snapshot from a
// UC-33e sends some of the controller messages back to back in the same
// packet. I'm not sure if this is the expected behavior, but we'll
// try to handle it...
// TODO(deanm): Use framing instead of assuming atomic writes on the pipe.
for (var j = 0, jl = msg.length; j < jl; ) {
if ((msg[j] & 0x80) !== 0x80) {
console.trace(msg);
console.trace(msg.slice(j));
return 'First MIDI byte not a status byte.';
}
var rem = jl - j; // Number of bytes remaining.
// NOTE(deanm): We expect MIDI packets are the correct length, for
// example 3 bytes for note on and off. Instead of error checking,
// we'll get undefined from msg[] if the message is shorter, maybe
// should handle this better, but loads of length checking is annoying.
switch (msg[j] & 0xf0) {
case 0x80: // Note off.
if (rem < 3) return 'Short noteOff message.';
this_.emit('noteOff', {type:'noteOff',
chan: msg[j+0] & 0x0f,
note: msg[j+1],
vel: msg[j+2]});
j += 3; break;
case 0x90: // Note on.
if (rem < 3) return 'Short noteOn message.';
this_.emit('noteOn', {type:'noteOn',
chan: msg[j+0] & 0x0f,
note: msg[j+1],
vel: msg[j+2]});
j += 3; break;
case 0xa0: // Aftertouch.
if (rem < 3) return 'Short aftertouch message.';
this_.emit('aftertouch', {type:'aftertouch',
chan: msg[j+0] & 0x0f,
note: msg[j+1],
pressure: msg[j+2]});
j += 3; break;
case 0xb0: // Controller message.
if (rem < 3) return 'Short controller message.';
this_.emit('controller', {type:'controller',
chan: msg[j+0] & 0x0f,
num: msg[j+1],
val: msg[j+2]});
j += 3; break;
case 0xc0: // Program change.
if (rem < 2) return 'Short programChange message.';
this_.emit('programChange', {type:'programChange',
chan: msg[j+0] & 0x0f,
num: msg[j+1]});
j += 2; break;
case 0xd0: // Channel pressure.
if (rem < 2) return 'Short channelPressure message.';
this_.emit('channelPressure', {type:'channelPressure',
chan: msg[j+0] & 0x0f,
pressure: msg[j+1]});
j += 2; break;
case 0xe0: // Pitch wheel.
if (rem < 3) return 'Short pitchWheel message.';
this_.emit('pitchWheel', {type:'pitchWheel',
chan: msg[j+0] & 0x0f,
val: (msg[j+2] << 7) | msg[j+1]});
j += 3; break;
case 0xf0: // SysEx and the 0xFx messages.
if (msg[j] !== 0xf0)
return 'Unhandled MIDI status byte: 0x' + msg[j].toString(16);
var start = j;
while (j+1 < msg.length && msg[j] !== 0xf7) ++j;
if (msg[j++] !== 0xf7) return 'Missing expected SysEx termination.';
this_.emit('sysex', {type: 'sysex', data: msg.slice(start, j)});
break;
default:
return 'Unhandled MIDI status byte: 0x' + msg[j].toString(16);
}
}
return null;
}
sock.on('data', function(msg, rinfo) {
var res = processMessage(msg);
if (res !== null) console.log(res);
});
this._sock_initialized = true;
}
events.EventEmitter.prototype.on.call(this, evname, callback);
};
exports.MidiIn = PlaskRawMac.CAMIDIDestination;
exports.MidiOut = PlaskRawMac.CAMIDISource;
exports.SBApplication = function(bundleid) {
var sbapp = new PlaskRawMac.SBApplication(bundleid);
var methods = sbapp.objcMethods();
for (var i = 0, il = methods.length; i < il; ++i) {
var sig = methods[i];
if (sig.length === 4) {
this[sig[0].replace(/:/g, '_')] = (function(name) {
return function() {
return sbapp.invokeVoid0(name);
};
})(sig[0]);
}
if (sig.length === 5 && sig[4] === '@') { // Assume arg is a string.
this[sig[0].replace(/:/g, '_')] = (function(name) {
return function(arg) {
return sbapp.invokeVoid1s(name, arg);
};
})(sig[0]);
}
}
console.log(methods);
};
exports.AppleScript = PlaskRawMac.NSAppleScript;
exports.Window = function(width, height, opts) {
setInterval(function() { }, 999999999); // Hack to prevent empty event loop.
var nswindow_ = new PlaskRawMac.NSWindow(
opts.type === '3d+skia' ? 2 : opts.type === '3d' ? 1 : 0,
width, height,
opts.multisample === true,
opts.display === undefined ? -1 : opts.display,
opts.borderless === true,
opts.fullscreen === true,
opts.highdpi === undefined ? 0 : opts.highdpi);
var this_ = this;
var dpi_scale = opts.highdpi === 2 ? 2 : 1; // For scaling mouse events.
this.context = nswindow_.context; // Export the 3d context (if it exists).
this.width = width; this.height = height;
// About mouse buttons. One day it will be important to have consistent
// numbering across platforms. We name from base 1:
// 1 left
// 2 right
// 3 middle
// ... Others (figure out wheel, etc).
function buttonNumberToName(numBaseOne) {
switch (numBaseOne) {
case 1: return 'left';
case 2: return 'right';
case 3: return 'middle';
default: return 'button' + numBaseOne;
}
}
this.setTitle = function(title) { return nswindow_.setTitle(title); };
this.setFullscreen = function(fs) { return nswindow_.setFullscreen(fs); };
// This is quite noisy on the event loop if you don't need it.
//nswindow_.setAcceptsMouseMovedEvents(true);
function nsEventNameToEmitName(nsname) {
switch (nsname) {
case PlaskRawMac.NSEvent.NSLeftMouseUp: return 'leftMouseUp';
case PlaskRawMac.NSEvent.NSLeftMouseDown: return 'leftMouseDown';
case PlaskRawMac.NSEvent.NSRightMouseUp: return 'rightMouseUp';
case PlaskRawMac.NSEvent.NSRightMouseDown: return 'rightMouseDown';
case PlaskRawMac.NSEvent.NSOtherMouseUp: return 'otherMouseUp';
case PlaskRawMac.NSEvent.NSOtherMouseDown: return 'otherMouseDown';
case PlaskRawMac.NSEvent.NSLeftMouseDragged: return 'leftMouseDragged';
case PlaskRawMac.NSEvent.NSRightMouseDragged: return 'rightMouseDragged';
case PlaskRawMac.NSEvent.NSOtherMouseDragged: return 'otherMouseDragged';
case PlaskRawMac.NSEvent.NSKeyUp: return 'keyUp';
case PlaskRawMac.NSEvent.NSKeyDown: return 'keyDown';
case PlaskRawMac.NSEvent.NSScrollWheel: return 'scrollWheel';
case PlaskRawMac.NSEvent.NSTabletPoint: return 'tabletPoint';
case PlaskRawMac.NSEvent.NSTabletProximity: return 'tabletProximity';
case PlaskRawMac.NSEvent.NSMouseMoved: return 'mouseMoved';
default: return '';
}
}
this.setMouseMovedEnabled = function(enabled) {
return nswindow_.setAcceptsMouseMovedEvents(enabled);
};
this.setFileDragEnabled = function(enabled) {
return nswindow_.setAcceptsFileDrag(enabled);
};
this.setFrameTopLeftPoint = function(x, y) {
return nswindow_.setFrameTopLeftPoint(x, y);
};
this.screenSize = function() {
return nswindow_.screenSize();
};
this.hideCursor = function() {
return nswindow_.hideCursor();
};
function cursor_name_to_selector_name(name) {
switch (name) {
case 'arrow': return 'arrowCursor';
case 'context': return 'contextualMenuCursor';
case 'closedhand': return 'closedHandCursor';
case 'crosshair': return 'crosshairCursor';
case 'poof':
case 'disappearingitem': return 'disappearingItemCursor';
case 'dragcopy': return 'dragCopyCursor';
case 'draglink': return 'dragLinkCursor';
case 'ibeam': return 'IBeamCursor';
case 'openhand': return 'openHandCursor';
case 'notallowed': return 'operationNotAllowedCursor';
case 'pointinghand': return 'pointingHandCursor';
case 'resizedown': return 'resizeDownCursor';
case 'resizeleft': return 'resizeLeftCursor';
case 'resizeleftright': return 'resizeLeftRightCursor';
case 'resizeright': return 'resizeRightCursor';
case 'resizeup': return 'resizeUpCursor';
case 'resizeupdown': return 'resizeUpDownCursor';
case 'vibeam': return 'IBeamCursorForVerticalLayout';
};
return null;
}
this.unhideCursor = function() {
return nswindow_.unhideCursor();
};
this.setCursor = function(name) {
var selector = cursor_name_to_selector_name(name);
return selector !== null ? nswindow_.setCursor(selector) : undefined;
};
this.pushCursor = function(name) {
var selector = cursor_name_to_selector_name(name);
return selector !== null ? nswindow_.pushCursor(selector) : undefined;
};
this.popCursor = function() {
return nswindow_.popCursor();
};
this.setCursorPosition = function(x, y) {
return nswindow_.setCursorPosition(x, y);
};
this.warpCursorPosition = function(x, y) {
return nswindow_.warpCursorPosition(x, y);
};
this.associateMouse = function(connected) {
return nswindow_.associateMouse(connected);
};
this.center = function() {
nswindow_.center();
};
function handleRawNSEvent(e) {
var type = e.type();
if (0) {
sys.puts("event: " + type);
for (var key in e) {
if (e[key] === type) sys.puts(key);
}
}
switch (type) {
case PlaskRawMac.NSEvent.NSLeftMouseDown:
case PlaskRawMac.NSEvent.NSLeftMouseUp:
case PlaskRawMac.NSEvent.NSRightMouseDown:
case PlaskRawMac.NSEvent.NSRightMouseUp:
case PlaskRawMac.NSEvent.NSOtherMouseDown:
case PlaskRawMac.NSEvent.NSOtherMouseUp:
var mods = e.modifierFlags();
var loc = e.locationInWindow();
var button = e.buttonNumber() + 1; // We work starting from 1.
var type_name = nsEventNameToEmitName(type);
// We want to also emit middleMouseUp, etc, but NS buckets it as other.
if (button === 3) type_name = type_name.replace('other', 'middle');
var te = {
type: type_name,
x: loc.x * dpi_scale,
y: height - loc.y * dpi_scale, // Map from button left to top left.
buttonNumber: button,
buttonName: buttonNumberToName(button),
clickCount: e.clickCount(),
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0
};
// Filter out clicks on the title bar.
if (te.y < 0) break;
// Emit the specific per-button event.
this_.emit(te.type, te);
// Emit a generic up / down event for all buttons.
this_.emit(te.type.substr(-2) === 'Up' ? 'mouseUp' : 'mouseDown', te);
break;
case PlaskRawMac.NSEvent.NSLeftMouseDragged:
case PlaskRawMac.NSEvent.NSRightMouseDragged:
case PlaskRawMac.NSEvent.NSOtherMouseDragged:
var mods = e.modifierFlags();
var loc = e.locationInWindow();
var button = e.buttonNumber() + 1; // We work starting from 1.
var type_name = nsEventNameToEmitName(type);
// We want to also emit middleMouseUp, etc, but NS buckets it as other.
if (button === 3) type_name = type_name.replace('other', 'middle');
var te = {
type: type_name,
x: loc.x * dpi_scale,
y: height - loc.y * dpi_scale,
dx: e.deltaX() * dpi_scale,
dy: e.deltaY() * dpi_scale, // Doesn't need flip, in device space.
dz: e.deltaZ(),
pressure: e.pressure(),
buttonNumber: button,
buttonName: buttonNumberToName(button),
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0
};
// TODO(deanm): This is wrong if the drag started in the content view.
if (te.y < 0) break;
// Emit the specific per-button event.
this_.emit(te.type, te);
// Emit a generic up / down event for all buttons.
this_.emit('mouseDragged', te);
break;
case PlaskRawMac.NSEvent.NSTabletPoint:
var mods = e.modifierFlags();
var loc = e.locationInWindow();
var te = {
type: nsEventNameToEmitName(type),
x: loc.x * dpi_scale,
y: height - loc.y * dpi_scale,
pressure: e.pressure(),
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0
};
this_.emit(te.type, te);
break;
case PlaskRawMac.NSEvent.NSTabletProximity:
var te = {
type: nsEventNameToEmitName(type),
entering: e.isEnteringProximity()
};
this_.emit(te.type, te);
break;
case PlaskRawMac.NSEvent.NSKeyUp:
case PlaskRawMac.NSEvent.NSKeyDown:
var mods = e.modifierFlags();
var te = {
type: nsEventNameToEmitName(type),
str: e.characters(),
keyCode: e.keyCode(), // I'll probably regret this.
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0,
repeat: e.isARepeat()
};
this_.emit(te.type, te);
break;
case PlaskRawMac.NSEvent.NSMouseMoved:
var mods = e.modifierFlags();
var loc = e.locationInWindow();
var te = {
type: nsEventNameToEmitName(type),
x: loc.x * dpi_scale,
y: height - loc.y * dpi_scale,
dx: e.deltaX() * dpi_scale,
dy: e.deltaY() * dpi_scale, // Doesn't need flip, in device space.
dz: e.deltaZ(),
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0
};
this_.emit(te.type, te);
break;
case PlaskRawMac.NSEvent.NSScrollWheel:
var mods = e.modifierFlags();
var loc = e.locationInWindow();
var te = {
type: nsEventNameToEmitName(type),
x: loc.x * dpi_scale,
y: height - loc.y * dpi_scale,
dx: e.deltaX() * dpi_scale,
dy: e.deltaY() * dpi_scale, // Doesn't need flip, in device space.
dz: e.deltaZ(),
hasPreciseScrollingDeltas: e.hasPreciseScrollingDeltas(),
scrollingDeltaX: e.scrollingDeltaX(),
scrollingDeltaY: e.scrollingDeltaY(),
phase: e.phase(),
momentumPhase: e.momentumPhase(),
capslock: (mods & e.NSAlphaShiftKeyMask) !== 0,
shift: (mods & e.NSShiftKeyMask) !== 0,
ctrl: (mods & e.NSControlKeyMask) !== 0,
option: (mods & e.NSAlternateKeyMask) !== 0,
cmd: (mods & e.NSCommandKeyMask) !== 0,
function: (mods & e.NSFunctionKeyMask) !== 0
};
this_.emit(te.type, te);
break;
default:
break;
}
}
// Handle events coming from the native layer.
nswindow_.setEventCallback(function(msgtype, msgdata) {
// Since emit is synchronous, we need to catch any exceptions that might
// happen during event handlers.
try {
if (msgtype === 0) { // Cocoa NSEvent.
handleRawNSEvent(msgdata);
} else if (msgtype === 1) { // File drag.
this_.emit('filesDropped', {type: 'filesDropped',
paths: msgdata.paths,
x: msgdata.x,
y: height - msgdata.y});
}
} catch(ex) {
sys.puts(ex.stack);
}
});
this.getRelativeMouseState = function() {
var res = nswindow_.mouseLocationOutsideOfEventStream();
res.x *= dpi_scale;
res.y = height - res.y * dpi_scale; // Map from bottom left to top left.
var buttons = PlaskRawMac.NSEvent.pressedMouseButtons();
for (var i = 0; i < 6; ++i) {
res[buttonNumberToName(i + 1)] = ((buttons >> i) & 1) === 1;
}
return res;
};
};
inherits(exports.Window, events.EventEmitter);
exports.Window.screensInfo = PlaskRawMac.NSWindow.screensInfo;
exports.simpleWindow = function(obj) {
// NOTE(deanm): Moving to a settings object to reduce the pollution of the
// main simpleWindow object. For now fall back for compat.
var settings = obj.settings;
if (settings === undefined) settings = { };
var wintype = settings.type === '2dx' ? '3d+skia' : '3d';
var width = settings.width === undefined ? 400 : settings.width;
var height = settings.height === undefined ? 300 : settings.height;
var syphon_server = null;
// TODO(deanm): Fullscreen.
var window_ = new exports.Window(
width, height, {type: wintype,
multisample: settings.multisample === true,
display: settings.display,
borderless: settings.borderless === undefined ?
settings.fullscreen : settings.borderless,
fullscreen: settings.fullscreen,
highdpi: settings.highdpi});
if (settings.position !== undefined) {
var position_x = settings.position.x;
var position_y = settings.position.y;
if (position_y < 0 || isNegZero(position_y))
position_y = window_.screenSize().height + position_y;
if (position_x < 0 || isNegZero(position_x))
position_x = window_.screenSize().width + position_x;
window_.setFrameTopLeftPoint(position_x, position_y);
} else if (settings.center === true ||
(settings.fullscreen !== true && settings.center !== false)) {
window_.center();
}
var gl_ = window_.context;
// obj.window = window_;
obj.width = width;
obj.height = height;
if (settings.title !== undefined)
window_.setTitle(settings.title);
obj.setTitle = function(title) { return window_.setTitle(title); };
obj.setFullscreen = function(title) { return window_.setFullscreen(title); };
obj.hideCursor = function() { return window_.hideCursor(); };
obj.unhideCursor = function() { return window_.unhideCursor(); };
obj.setCursor = function(name) { return window_.setCursor(name); };
obj.pushCursor = function(name) { return window_.pushCursor(name); };
obj.popCursor = function() { return window_.popCursor(); };
obj.setCursorPosition = function(x, y) { return window_.setCursorPosition(x, y); };
obj.warpCursorPosition = function(x, y) { return window_.warpCursorPosition(x, y); };
obj.associateMouse = function(connected) { return window_.associateMouse(connected); };
if (settings.cursor === false)
window_.hideCursor();
obj.getRelativeMouseState = function() {
return window_.getRelativeMouseState();
};
var bitmap_canvas = null; // Protected from getting clobbered on obj.
var gpu_canvas = null;
var canvas = null;
// Default 3d2d windows to vsync also.
if (settings.type !== '3d' || settings.vsync === true)
gl_.setSwapInterval(1);
if (settings.type === '3d') { // Don't expose gl for 3d2d windows.
obj.gl = gl_;
} else { // Create a canvas and paint for 3d2d windows.
obj.paint = new exports.SkPaint;
if (settings.type === '2dx') { // GPU accelerated
canvas = gpu_canvas = new exports.SkCanvas(gl_);
canvas.width = width; canvas.height = height;
obj.gl = gl_; // Expose the OpenGL context for mixed usage.
} else {
canvas = bitmap_canvas = exports.SkCanvas.create(width, height); // Offscreen.
}
obj.canvas = canvas;
}
if (settings.syphon_server !== undefined) {
syphon_server = gl_.createSyphonServer(settings.syphon_server);
}
var framerate_handle = null;
obj.framerate = function(fps) {
if (framerate_handle !== null)
clearInterval(framerate_handle);
if (fps === 0) return;
framerate_handle = setInterval(function() {
obj.redraw();
}, 1000 / fps);
}
// Export listener API so you can "this.on" instead of "this.window.on".
obj.on = function(e, listener) {
// TODO(deanm): Do this properly
if (e === 'mouseMoved')
window_.setMouseMovedEnabled(true);
if (e === 'filesDropped')
window_.setFileDragEnabled(true);
var this_ = this;
return window_.on(e, function() {
return listener.apply(this_, arguments);
});
};
obj.removeListener = function(e, listener) {
return window_.removeListener(e, listener);
};
this.getRelativeMouseState = function() {
return window_.getRelativeMouseState();
};
// Call init as early as possible, to give the init routine a chance to
// setup anything on the object it might want to do at runtime.
if ('init' in obj) {
try {
obj.init();
} catch (ex) {
sys.error('Exception caught in simpleWindow init:\n' +
ex + '\n' + ex.stack);
}
}
var draw = null;
var framenum = 0;
var frame_start_time = Date.now();
if ('draw' in obj)
draw = obj.draw;
obj.redraw = function() {
if (gl_ !== undefined)
gl_.makeCurrentContext();
if (draw !== null) {
obj.framenum = framenum;
obj.frametime = (Date.now() - frame_start_time) / 1000; // Secs.
try {
obj.draw();
} catch (ex) {
sys.error('Exception caught in simpleWindow draw:\n' +
ex + '\n' + ex.stack);
}
framenum++;
}
// TODO(deanm): For bitmap_canvas too?
if (gpu_canvas !== null) gpu_canvas.flush();
if (bitmap_canvas !== null) { // 3d2d
// Blit to Syphon.
if (syphon_server !== null && syphon_server.hasClients() === true) {
if (syphon_server.bindToDrawFrameOfSize(width, height) === true) {
gl_.drawSkCanvas(canvas);
syphon_server.unbindAndPublish();
} else {
console.log('Error blitting for Syphon.');
}
}
// Blit to the screen OpenGL context.
gl_.drawSkCanvas(canvas);
}
gl_.blit(); // Update the screen automatically.
};
// Sort of a debouncing version of redraw, which is convenient for use in
// interaction event callbacks like mouse and keyboard. If you have a big
// flood of mouse move events, you don't want to synchronously redraw for
// each one. This throttles it a bit by only doing the redraw the next time
// around on the event loop.
var redraw_soon_handle = null;
obj.redrawSoon = function() {
if (redraw_soon_handle === null) {
redraw_soon_handle = setTimeout(function() {
redraw_soon_handle = null;
obj.redraw();
}, 0);
}
};
obj.redraw(); // Draw the first frame.
return obj;
};
// new Vec3(x, y, z)
//
// A class representing a 3 dimensional point and/or vector. There isn't a
// good reason to differentiate between the two, and you often want to change
// how you think about the same set of values. So there is only "vector".
//
// The class is designed without accessors or individual mutators, you should
// access the x, y, and z values directly on the object.
//
// Almost all of the core operations happen in place, writing to the current
// object. If you want a copy, you can call `dup`. For convenience, many
// operations have a passed-tense version that returns a new object. Most
// methods return `this` to support chaining.
function Vec3(x, y, z) {
this.x = x; this.y = y; this.z = z;
}
// this set(x, y, z)
Vec3.prototype.set = function(x, y, z) {
this.x = x; this.y = y; this.z = z;
return this;
};
// this setVec3(Vec3 v)
Vec3.prototype.setVec3 = function(v) {
this.x = v.x; this.y = v.y; this.z = v.z;
return this;
};
// this cross2(Vec3 a, Vec3 b)
//
// Cross product, this = a x b.
Vec3.prototype.cross2 = function(a, b) {
var ax = a.x, ay = a.y, az = a.z,
bx = b.x, by = b.y, bz = b.z;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
};
// this cross(Vec3 b)
//
// Cross product, this = this x b.
Vec3.prototype.cross = function(b) {
return this.cross2(this, b);
};
// float dot(Vec3 b)
//
// Returns the dot product, this . b.
Vec3.prototype.dot = function(b) {
return this.x * b.x + this.y * b.y + this.z * b.z;
};
// this add2(Vec3 a, Vec3 b)
//
// Add two Vec3s, this = a + b.
Vec3.prototype.add2 = function(a, b) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
};
// this add(Vec3 b)
//
// Add a Vec3, this = this + b.
Vec3.prototype.add = function(b) {
return this.add2(this, b);
};
// Vec3 added(Vec3 b)
Vec3.prototype.added = function(b) {
return new Vec3(this.x + b.x,
this.y + b.y,
this.z + b.z);
};
// this sub2(Vec3 a, Vec3 b)
//
// Subtract two Vec3s, this = a - b.
Vec3.prototype.sub2 = function(a, b) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
};
// this sub(Vec3 b)
//
// Subtract another Vec3, this = this - b.
Vec3.prototype.sub = function(b) {
return this.sub2(this, b);
};
// Vec3 subbed(Vec3 b)
Vec3.prototype.subbed = function(b) {
return new Vec3(this.x - b.x,
this.y - b.y,
this.z - b.z);
};
// this mul2(Vec3 a, Vec3 b)
//
// Multiply two Vec3s, this = a * b.
Vec3.prototype.mul2 = function(a, b) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
};
// this mul(Vec3 b)
//
// Multiply by another Vec3, this = this * b.