Skip to content

Instantly share code, notes, and snippets.

@shanewholloway
Last active August 29, 2015 14:13
Show Gist options
  • Save shanewholloway/161a4eaf46724eacc03b to your computer and use it in GitHub Desktop.
Save shanewholloway/161a4eaf46724eacc03b to your computer and use it in GitHub Desktop.
NodObjC EventLoop implementation
/* Cocoa application event loop implementation for NodObjC.
* Code created for https://github.com/TooTallNate/NodObjC/pull/56
* Working as of 2015-Jan-11 on Mac OS 10.10, Node 0.10.35, NodObjC 1.0.0
*
* Copyright (c) 2015, Shane Holloway
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
var $, EventEmitter = require('events').EventEmitter;
// export EventLoop at module and as 'EventLoop'
module.exports = EventLoop.EventLoop = EventLoop
EventLoop.initObjC = function(NodObjC) {
$ = NodObjC || $ || require('NodObjC')
$.import('Cocoa')
EventLoop.prototype._runLoopMode = $.NSDefaultRunLoopMode
if (EventLoop.prototype._runLoopMode === null) {
EventLoop.prototype._runLoopMode = $('kCFRunLoopDefaultMode')
console.warn('WARNING: Falling back to hard-coded string for NSDefaultRunLoopMode constant. See https://github.com/TooTallNate/NodObjC/pull/56 for details.')
}
}
function EventLoop(start, options) {
EventEmitter.call(this)
if (options) {
if (options.runLoopMode) this._runLoopMode = options.runLoopMode
}
this.runInfo = {recurring:null, schedule_id:null, loop:{}}
if (start) this.start()
return this
}
require('util').inherits(EventLoop, EventEmitter)
EventLoop.prototype.start = function() {
this.emit('start')
return this.schedule(true)
}
EventLoop.prototype.stop = function() {
this.runInfo.recurring = false
this.emit('stop')
return this
}
EventLoop.prototype._schedule = setTimeout
EventLoop.prototype._clearSchedule = clearTimeout
EventLoop.prototype.schedule = function(runRecurring) {
var runInfo = this.runInfo
if (runRecurring !== undefined)
runInfo.recurring = !!runRecurring
if (runInfo.schedule_id != null)
return this; // exit if already scheduled
var id = this._schedule(this.eventLoop.bind(this))
runInfo.schedule_id = (id !== undefined) ? id : true
this.emit('scheduled', runInfo)
return this
}
EventLoop.prototype.clearSchedule = function() {
var runInfo = this.runInfo
var id = runInfo.schedule_id
runInfo.recurring = false
if (id != null) {
runInfo.schedule_id = null
this._clearSchedule(id)
this.emit('unscheduled', runInfo)
}
return this
}
EventLoop.prototype.isScheduled = function(runInfo) {
if (!runInfo) runInfo = this.runInfo
return runInfo.schedule_id!=null }
EventLoop.prototype.isActive = function(runInfo) {
if (!runInfo) runInfo = this.runInfo
return this.isScheduled(runInfo) || runInfo.recurring }
EventLoop.prototype.eventLoop = function(runRecurring) {
var runInfo = this.runInfo
runInfo.schedule_id = null
this.eventLoopCore()
if (runInfo.recurring || runRecurring)
this.schedule(runRecurring)
else if (runInfo.schedule_id==null)
this.emit('deactivate', this.runInfo)
return this
}
EventLoop.prototype.eventLoopCore = function(block) {
if ($==null) EventLoop.initObjC();
var runInfo = this.runInfo,
loopInfo = {running:true, count:0, t0:Date.now()},
event, app = $.NSApplication('sharedApplication'),
untilDate = block ? $.NSDate('distantFuture') : null, // or $.NSDate('distantPast') to not block
inMode = this._runLoopMode
var runLoopPool = $.NSAutoreleasePool('alloc')('init')
try {
runInfo.loop = loopInfo
this.emit('eventLoop-enter', runInfo)
do {
this.emit('event-next', event, app, runInfo)
event = app('nextEventMatchingMask',
$.NSAnyEventMask.toString(), // …grumble… uint64 as string …grumble…
'untilDate', untilDate,
'inMode', inMode,
'dequeue', 1)
this.emit('event-match', event, app, runInfo)
if (event) {
app('sendEvent', event)
this.emit('event-sent', event, app, runInfo)
}
++loopInfo.count
} while (event)
loopInfo.t1 = Date.now()
loopInfo.running = false
this.emit('eventLoop-exit', runInfo)
} catch (err) {
loopInfo.t1 = Date.now()
loopInfo.running = false
loopInfo.error = err
this.emit('error', err, runInfo)
throw err
} finally {
runLoopPool('drain')
}
delete loopInfo.running
this.emit('eventLoop', runInfo)
return this
}
/* Copyright (c) 2015, Shane Holloway
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
var $ = require('NodObjC')
$.import('Foundation')
exports.asArray = asArray
function asArray(arr, immutable) {
var i, len=arr.length,
res=$.NSMutableArray('arrayWithCapacity', len)
for(i=0; i<len; i++) res('addObject', arr[i])
return immutable ? $.NSArray('arrayWithArray', res) : res
}
exports.fromArray = fromArray
function fromArray(nsArr, res) {
if (res == null) res = []
var i, len=nsArr('count')
for(i=0; i<len; i++) res.push(nsArr('objectAtIndex', i))
return res
}
exports.enumArray = enumArray
function enumArray(nsArr, callback) {
nsArr('enumerateObjectsUsingBlock', $(function (self, obj, index, stop) {
callback(obj, index)
}, ['v',['?', '@','I','^B']]));
}
exports.fromDict = fromDict
function fromDict(nsDict, res) {
if (res==null) res = {}
enumDict(nsDict, function(k,v) {
console.log({k:k, v:v, tv:typeof v})
res[k] = v })
return res
}
exports.asDict = asDict
function asDict(obj, immutable) {
var keys = Object.keys(obj), i, len=keys.length,
res=$.NSMutableDictionary('dictionaryWithCapacity', len)
for(i=0; i<len; i++) res('setObject', obj[keys[i]], 'forKey', $(keys[i]))
return immutable ? $.NSDictionary('dictionaryWithDictionary', res) : res
}
exports.enumDict = enumDict
function enumDict(nsDict, callback) {
var en = nsDict('enumerateKeysAndObjectsUsingBlock', $(function(self, key, obj, stop){
callback(key, obj)
}, ['v',['?', '@','@','^B']]))
}
exports.fromString = fromString
function fromString(nsStr) { return nsStr('UTF8String') }
exports.toJSON = toJSON
function toJSON(obj, pretty) {
var error = $.alloc($.NSError);
var jsonData = $.NSJSONSerialization('dataWithJSONObject', obj,
'options', pretty ? $.NSJSONWritingPrettyPrinted : 0, 'error', error.ref());
jsonData = $.NSString('alloc')('initWithData', jsonData, 'encoding', $.NSUTF8StringEncoding)
return fromString(jsonData);
}
/* Copyright (c) 2015, Shane Holloway
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
var $ = require('NodObjC')
var NS = require('./nsDataUtils')
var pool = $.NSAutoreleasePool('alloc')('init');
$.import('Cocoa');
var EventLoop = require('./EventLoop')
var evtLoop = new EventLoop(true)
var pool = $.NSAutoreleasePool('alloc')('init')
evtLoop.on('deactivate', function(){ pool('drain') })
var searchList = [$('*.js'), $('*.json')]
var predicate = $.NSPredicate('predicateWithFormat', $("kMDItemFSName LIKE %@"), 'argumentArray', NS.asArray(searchList))
var query = $.NSMetadataQuery('alloc')('init');
query('setPredicate', predicate)
var t0 = Date.now()
function getQueryInfo(query) {
return {resultCount: query('resultCount'), isGathering: query('isGathering'), ts:Date.now()-t0}
}
var pollResultsTimer = setInterval(function() {
console.log('timer interval:', getQueryInfo(query))
}, 100)
function shutdownDemo() {
clearInterval(pollResultsTimer)
query('stopQuery')
console.log('stopping query:', getQueryInfo(query))
evtLoop.stop()
}
var DemoQueryDelegate = $.NSObject.extend('DemoQueryDelegate')
function onQueryNotification(self, cmd, notif) {
console.log(cmd, getQueryInfo(query))
}
function onFinishNotification(self, cmd, notif) {
console.log(cmd, getQueryInfo(query))
shutdownDemo()
}
DemoQueryDelegate.addMethod('didStart:', 'v@:@', onQueryNotification)
DemoQueryDelegate.addMethod('didUpdate:', 'v@:@', onQueryNotification)
DemoQueryDelegate.addMethod('gathering:', 'v@:@', onQueryNotification)
DemoQueryDelegate.addMethod('didFinish:', 'v@:@', onFinishNotification)
DemoQueryDelegate.register()
var queryDelegate = DemoQueryDelegate('alloc')('init')
$.NSNotificationCenter('defaultCenter')('addObserver', queryDelegate, 'selector', 'didStart:',
'name', $.NSMetadataQueryDidStartGatheringNotification, 'object', query)
$.NSNotificationCenter('defaultCenter')('addObserver', queryDelegate, 'selector', 'didUpdate:',
'name', $.NSMetadataQueryDidUpdateNotification, 'object', query)
$.NSNotificationCenter('defaultCenter')('addObserver', queryDelegate, 'selector', 'gathering:',
'name', $.NSMetadataQueryGatheringProgressNotification, 'object', query)
$.NSNotificationCenter('defaultCenter')('addObserver', queryDelegate, 'selector', 'didFinish:',
'name', $.NSMetadataQueryDidFinishGatheringNotification, 'object', query)
console.log('starting query:', getQueryInfo(query))
query('startQuery')
console.log('post-start query:', getQueryInfo(query))
@shanewholloway
Copy link
Author

Example run without the patch:

WARNING: Falling back to hard-coded string for NSDefaultRunLoopMode constant. See https://github.com/TooTallNate/NodObjC/pull/56 for details.
starting query: { resultCount: 0, isGathering: false, ts: 9 }
didStart: { resultCount: 0, isGathering: true, ts: 99 }
didUpdate: { resultCount: 0, isGathering: true, ts: 100 }
gathering: { resultCount: 0, isGathering: true, ts: 102 }
didFinish: { resultCount: 0, isGathering: true, ts: 103 }
stopping query: { resultCount: 0, isGathering: false, ts: 105 }
post-start query: { resultCount: 0, isGathering: false, ts: 106 }

Example run with the patch applied:

starting query: { resultCount: 0, isGathering: false, ts: 13 }
didStart: { resultCount: 0, isGathering: true, ts: 104 }
post-start query: { resultCount: 0, isGathering: true, ts: 105 }
timer interval: { resultCount: 20, isGathering: true, ts: 139 }
gathering: { resultCount: 20, isGathering: true, ts: 177 }
timer interval: { resultCount: 20, isGathering: true, ts: 242 }
gathering: { resultCount: 24054, isGathering: true, ts: 261 }
didFinish: { resultCount: 24054, isGathering: false, ts: 269 }
stopping query: { resultCount: 24054, isGathering: false, ts: 271 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment