Example #1
0
akala.injectWithName(['$isModule', '$master', '$worker'], function (isModule: akala.worker.IsModule, master: akala.worker.MasterRegistration, worker: EventEmitter)
{
    if (isModule('@domojs/lifttt'))
    {
        worker.on('ready', function ()
        {
            // Called when all modules have been initialized
        });
        worker.on('after-master', function ()
        {
            // Called when all modules have been initialized
            require('./services/console');
            require('./services/fs');
            require('./services/http');
            require('./api');
        });


        master(__filename, './master');


        akala.injectWithName([AssetRegistration.name], function (virtualasset: PromiseLike<AssetRegistration>)
        {
            virtualasset.then((va) =>
            {
                va.register('/js/tiles.js', require.resolve('../tile'));
                va.register('/js/routes.js', require.resolve('../routes'));
            });
        })();

    }
})()
Example #2
0
 zoneA.run(() => {
   emitter.on('test', shouldNotRun);
   emitter.on('test1', shouldNotRun);
   emitter.removeAllListeners();
   expect(emitter.listeners('test').length).toEqual(0);
   expect(emitter.listeners('test1').length).toEqual(0);
 });
Example #3
0
  constructor(eventEmitter : EventEmitter, perspective : Perspective){
    this.pointers = new Map<number, Pointer>();
    this.perspective = perspective;
    this.changed = false;

    eventEmitter.on(POINTER_DOWN, (data : PointerDownEvent) => {
      this.pointers.set(data.id, {
        x: data.x,
        y: data.y,
        mapPos: perspective.viewportToMap(data.x, data.y)
      });
    });

    eventEmitter.on(POINTER_MOVE, (data : PointerMoveEvent) => {
      if(!this.pointers.has(data.id)) return;

      const pointer = this.pointers.get(data.id);
      if(pointer === undefined) return;
      this.changed = true;
      pointer.x = data.x;
      pointer.y = data.y;
    });

    eventEmitter.on(CANCEL_PAN_ZOOM, (data : CancelPanZoomEvent) => {
      if(!this.pointers.has(data.id)) return;
      this.pointers.delete(data.id);
    });

    eventEmitter.on(POINTER_UP, (data : PointerUpEvent) => {
      if(!this.pointers.has(data.id)) return;
      this.pointers.delete(data.id);
    });
  }
Example #4
0
 zoneA.run(() => {
   const testSymbol = Symbol('test');
   const test1Symbol = Symbol('test1');
   emitter.on(testSymbol, expectZoneA);
   emitter.on(test1Symbol, shouldNotRun);
   emitter.removeListener(test1Symbol, shouldNotRun);
   expect(emitter.listeners(testSymbol).length).toBe(1);
   expect(emitter.listeners(test1Symbol).length).toBe(0);
   emitter.emit(testSymbol, 'test value');
 });
Example #5
0
 zoneA.run(() => {
   emitter.on('removeListener', function(type: string, handler: any) {
     zoneResults.push('remove' + type);
   });
   emitter.on('test', shouldNotRun);
   emitter.on('test1', expectZoneA);
   emitter.removeAllListeners('test');
   expect(zoneResults).toEqual(['removetest']);
   expect(emitter.listeners('removeListener').length).toBe(1);
 });
Example #6
0
function addHandler(emitter: EventEmitter, event: string, handler: Function) {
  if (isLogEvent) {
    emitter.on(event, function (...args: any[]) {
      console.log("%s %s", event, args)
      handler.apply(null, args)
    })
  }
  else {
    emitter.on(event, handler)
  }
}
Example #7
0
 zoneA.run(() => {
   emitter.on('removeListener', function(type: string, handler: any) {
     zoneResults.push('remove' + type);
   });
   emitter.on('newListener', function(type: string, handler: any) {
     zoneResults.push('new' + type);
   });
   emitter.on('test', shouldNotRun);
   emitter.removeListener('test', shouldNotRun);
   expect(zoneResults).toEqual(['newtest', 'removetest']);
 });
Example #8
0
function addHandler(emitter: EventEmitter, event: string, handler: (...args: Array<any>) => void) {
  if (isLogEvent) {
    emitter.on(event, (...args: Array<any>) => {
      console.log("%s %s", event, args)
      handler.apply(null, args)
    })
  }
  else {
    emitter.on(event, handler)
  }
}
Example #9
0
    zoneA.run(() => {
      emitter.on('test', listenerA);
      emitter.on('test', listenerB);
      expect(emitter.listeners('test')).toEqual([listenerA, listenerB]);
      emitter.emit('test');
      expect(zoneResults).toEqual(['A', 'B']);
      zoneResults = [];

      emitter.removeAllListeners('test');

      emitter.on('test', listenerA);
      emitter.prependListener('test', listenerB);
      expect(emitter.listeners('test')).toEqual([listenerB, listenerA]);
      emitter.emit('test');
      expect(zoneResults).toEqual(['B', 'A']);
    });
 test('it broadcasts if case sensitivity has been updated', done => {
     eventBus.on(Event.TOGGLED_CASE_SENSITIVITY, (mode: any) => {
         assertKeyExists(mode, 'ignoreCase');
         done();
     });
     registry.toggleCaseSensitivity();
 });
 test('it broadcasts if whole/partial match has been toggled', done => {
     eventBus.on(Event.WHOLE_MATCH_MODE_TOGGLED, (mode: any) => {
         assertKeyExists(mode, 'wholeMatch');
         done();
     });
     registry.toggleWholeMatch();
 });
 test('after extension started, it broadcast if it is ready', done => {
     eventBus.on(Event.MATCHING_MODE_INITIALISED, (mode: any) => {
         assertKeyExists(mode, 'ignoreCase');
         done();
     });
     eventBus.emit(Event.EXTENSION_READY);
 });
Example #13
0
function maybeEmit(emitter : EventEmitter, condition : () => boolean, when : string, then : string){
  emitter.on(when, (data : any) => {
    if(condition()){
      emitter.emit(then, data);
    }
  });
}
	public initialize(): void {
		this.$devicesService.on(DeviceDiscoveryEventNames.DEVICE_FOUND, (device: Mobile.IDevice) => {
			this.emit(DeviceDiscoveryEventNames.DEVICE_FOUND, device.deviceInfo);
			this.attachApplicationChangedHandlers(device);

			// await: Do not await as this will require to mark the lambda with async keyword, but there's no way to await the lambda itself.
			/* tslint:disable:no-floating-promises */
			device.openDeviceLogStream();
			/* tslint:enable:no-floating-promises */
		});

		this.$devicesService.on(DeviceDiscoveryEventNames.DEVICE_LOST, (device: Mobile.IDevice) => {
			this.emit(DeviceDiscoveryEventNames.DEVICE_LOST, device.deviceInfo);
		});

		this.$deviceLogProvider.on("data", (identifier: string, data: any) => {
			this.emit(DEVICE_LOG_EVENT_NAME, identifier, data.toString());
		});

		this.$devicesService.on(EmulatorDiscoveryNames.EMULATOR_IMAGE_FOUND, (emulator: Mobile.IDeviceInfo) => {
			this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_FOUND, emulator);
		});

		this.$devicesService.on(EmulatorDiscoveryNames.EMULATOR_IMAGE_LOST, (emulator: Mobile.IDeviceInfo) => {
			this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_LOST, emulator);
		});
	}
Example #15
0
export function dispatchOn(emitter : EventEmitter, dispatch : Dispatch<Action>, eventMap : {
  [event : string] : (event : any) => any
}){
  for(let event in eventMap){
    const map = eventMap[event];
    emitter.on(event, (event : any) => dispatch(map(event)));
  }
}
Example #16
0
  const promise = new Promise((resolve, reject) => {
    // start listening for events, remove listeners once an event is received
    eventEmitter.on(INCREMENTAL_BUILD_FAILED, (err: Error) => {
      Logger.debug('Webpack Bundle Update Failed');
      eventEmitter.removeAllListeners();
      handleWebpackBuildFailure(resolve, reject, err, promise, pendingPromises);
    });

    eventEmitter.on(INCREMENTAL_BUILD_SUCCESS, (stats: any) => {
      Logger.debug('Webpack Bundle Updated');
      eventEmitter.removeAllListeners();
      handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises);
    });

    if (initializeWatch) {
      startWebpackWatch(context, config);
    }
  });
Example #17
0
export const createCommitControl = (pubsub: EventEmitter) => {
    let connection: IClientConnection
    let uncommited: IUpdatedEvent[]

    const emitUpdate = () => {
        const event: ICommitControlUpdateEvent = {
            uncommited,
            autoCommit: connection.settings().autoCommit,
        }
        pubsub.emit('commit-ctrl-update', event)
    }

    pubsub.on('connected', c => {
        connection = c
        uncommited = []
        emitUpdate()
    })
    pubsub.on('data-updated', (res: IUpdatedEvent) => {
        if (!connection.settings().autoCommit) {
            uncommited.push(res)
            emitUpdate()
        }
    })

    pubsub.on('commit', () => {
        if (connection) {
            connection.commit()
            uncommited = []
            emitUpdate()
        }
        pubsub.emit('editor-focus', {})
    })

    pubsub.on('rollback', () => {
        if (connection) {
            connection.rollback()
            uncommited = []
            emitUpdate()
        }
        pubsub.emit('editor-focus', {})
    })
}
   addListener: (apiModuleUrl, event, callback, entityId) => {
     if (!socket().isConnected()) {
       throw 'Listeners can be added only for a connected socket';
     }
 
     const subscriptionId = getEmitId(event, entityId);
     const subscriptionUrl = getSubscriptionUrl(apiModuleUrl, entityId, event);
 
     emitter.on(subscriptionId, callback);
     return addPendingEntry(subscriptionUrl, subscriptionId, callback);
   },
Example #19
0
 addChangeListener<T>(query: string, onSuccess: (json?: Falcor.JSONEnvelope<T>) => any) {
     var handler = () => {
         this.get<T>(query).then(res => {
             if(res) {
                 onSuccess(res);
             }
         });
     };
     this.emitter.on('change', handler);
     var off = () => {
         this.emitter.removeListener('change', handler);
     };
     return off;
 }
Example #20
0
export const createGlobalShortcuts = (pubsub: EventEmitter) => {
    const isCmdOrCtrl =
        process.platform === 'darwin' ? isCmdAndNotCtrl : isCtrlAndNotCmd
    const showCommands = (e: KeyboardEvent) => {
        if (e.shiftKey && isCmdOrCtrl(e) && e.key === 'P') {
            pubsub.emit('actions-toggle-show')
        } else if (!e.shiftKey && isCmdOrCtrl(e) && e.key === 'p') {
            pubsub.emit('table-search-toggle-show')
        } else if (!e.shiftKey && isCmdOrCtrl(e) && e.key === 'h') {
            pubsub.emit('history-list')
        } else if (!e.shiftKey && isCmdOrCtrl(e) && e.key === '1') {
            pubsub.emit('editor-focus')
        } else if (!e.shiftKey && isCmdOrCtrl(e) && e.key === '2') {
            pubsub.emit('results-focus')
        }
    }
    pubsub.on('connected', () => {
        window.addEventListener('keydown', showCommands)
    })

    pubsub.on('disconnect', () => {
        window.removeEventListener('keydown', showCommands)
    })
}
Example #21
0
	constructor(stream: EventEmitter) {
		let buffer = '',
		    self = this;
		super();
		stream.on('data', function(data) {
		  buffer += data;
			let boundary = buffer.indexOf('\n');
			while(boundary !== -1) {
				let input = buffer.substr(0, boundary);
				buffer = buffer.substr(boundary + 1);
				self.emit('message', JSON.parse(input));
				boundary = buffer.indexOf('\n');
			} 
		});
	}
Example #22
0
    ipcMain.on("data-request", (event, request) => {

        // console.log("Request", request.message, request.id, request.data.length);

        /**
         * Message should be mapped to a route name (controller function)
         * Take the function that should be executed.
         */
        const controllerFn = routes[request.message] as RouteController;

        /**
         * We need to create a callback for the controller. That callback will take incoming errors and responses
         * and attach the ID of the original message, pack it, and send it downstream, so {@link IpcService} can link the
         * message on the IPC channel to the open request.
         */
        const reply = (id: string) => (error?: Error, data?: any) => {
            if (error) {
                error = Object.assign({}, error, {message: error.message});

                // console.log("Reply", request.id);
                event.sender.send("data-reply", {id, error});
                return;
            }

            event.sender.send("data-reply", {id, data});
        };

        // If this requests accepts data over time, both client and server need to be able to terminate
        // the connection
        if (request.watch) {
            const emitter = new events.EventEmitter();

            activeChannels[request.id] = emitter;

            controllerFn(request.data, reply(request.id), emitter);

            emitter.on("stop", () => {
                delete activeChannels[request.id];
            });

        } else {
            controllerFn(request.data, reply(request.id));
        }


    });
function main(li: HTMLLIElement, arr_emitter: EventEmitter[], eventName: string, start_hour: number, start_min: number, end_hour: number, end_min: number): void {

    const emitter = new EventEmitter();
    arr_emitter.push(emitter);

    emitter.on(eventName, () => {

        const current_time = new Date();

        if (end_hour == current_time.getHours()) {
            if (end_min <= current_time.getMinutes()) {

                endOfEvent(li, arr_emitter, emitter, start_hour, start_min, end_hour, end_min);
            }
        }
    });
}
Example #24
0
        bag.add(s1.subscribeOnCompleted(() => {
          if (start) {
            let s2: Observable<string>;

            if (readyActionObservables) {
              s2 = Observable
                .merge
                .apply(null, readyActionObservables)
                .startWith(null)
                .flatMapLatest(() => spawn(start));
            } else {
              s2 = spawn(start);
            }

            let d: Disposable;

            if (match) {
              d = s2.subscribeOnNext((val) => {
                const action = match(val);
                if (action) {
                  observer.onNext(action);
                }
              });
            } else {
              d = s2.subscribe(() => {});
            }

            bag.add(d);
          } else { // "process"
            input = new EventEmitter();
            output = new EventEmitter();

            output.on('action', (obj: Object) => {
              observer.onNext(obj);
            });

            process(input, output);

            const d = Observable.merge.apply(null, connectables)
              .subscribeOnNext((action: Object) => input.emit('action', action));

            bag.add(d);
          }
        }));
Example #25
0
  private subscribeToEvent(eventName: string, params: any, publish: (data: {}) => void): string {
    const subscription: string = uuidv4();

    const handler = (data: {}): void => {
      this.emit(eventName, data);
    };
    this.parentEmitter.on(eventName, handler);

    this.on(eventName, publish)
      .once(`unsubscribe:${subscription}`, (): void => {
        this.removeListener(eventName, publish);
        this.parentEmitter.removeListener(eventName, handler);
      })
      .once("removeAllListeners", (): void => {
        this.parentEmitter.removeListener(eventName, handler);
      });

    return subscription;
  }
Example #26
0
  constructor(eventEmitter : EventEmitter){
    let data = {
      x: 0,
      y: 0,
      now: window.performance.now()
    };

    eventEmitter.on(POINTER_TAP, function(event : Pos) {
      const now = window.performance.now();
      if(now - data.now < MAX_HOLD_TIME
        && Math.abs(data.x - event.x) < MAX_UNMOVED_DISTANCE
        && Math.abs(data.y - event.y) < MAX_UNMOVED_DISTANCE){
          eventEmitter.emit(POINTER_DOUBLE_TAP, {x: event.x, y: event.y});
      }

      data.now = now;
      data.x = event.x;
      data.y = event.y;
    });
  }
   addHook: <DataT extends object, CompletionDataT extends object | undefined>(
     apiModuleUrl: string, 
     event: string, 
     callback: Subscriptions.HookCallback<DataT, CompletionDataT>, 
     subscriberInfo: Subscriptions.HookSubscriberInfo
   ) => {
     if (!socket().isConnected()) {
       throw 'Hooks can be added only for a connected socket';
     }
 
     const subscriptionId = event;
     if (subscriptions[subscriptionId] || pendingSubscriptions[subscriptionId]) {
       throw 'Hook exists';
     }
 
     const subscriptionUrl = `${apiModuleUrl}/hooks/${event}`;
 
     callback = handleHookAction.bind(SocketSubscriptionHandler, subscriptionUrl, callback);
     emitter.on(subscriptionId, callback);
 
     return addPendingEntry(subscriptionUrl, subscriptionId, callback, subscriberInfo);
   },
Example #28
0
		return (() => {
			this.$androidDeviceDiscovery.ensureAdbServerStarted().wait();
			this.$androidDeviceDiscovery.on("deviceFound", (device: Mobile.IDevice) => {
				this.emit("deviceFound", device.deviceInfo);
				this.attachApplicationChangedHandlers(device);
				device.openDeviceLogStream();
			});

			this.$androidDeviceDiscovery.on("deviceLost", (device: Mobile.IDevice) => {
				this.emit("deviceLost", device.deviceInfo);
			});

			this.$iOSDeviceDiscovery.on("deviceFound", (device: Mobile.IDevice) => {
				this.emit("deviceFound", device.deviceInfo);
				this.attachApplicationChangedHandlers(device);
				device.openDeviceLogStream();
			});

			this.$iOSDeviceDiscovery.on("deviceLost", (device: Mobile.IDevice) => {
				this.emit("deviceLost", device.deviceInfo);
			});

			this.$iOSSimulatorDiscovery.on("deviceFound", (device: Mobile.IDevice) => {
				this.emit("deviceFound", device.deviceInfo);
				device.openDeviceLogStream();
				this.attachApplicationChangedHandlers(device);
			});

			this.$iOSSimulatorDiscovery.on("deviceLost", (device: Mobile.IDevice) => {
				this.emit("deviceLost", device.deviceInfo);
			});

			this.$devicesService.initialize({skipInferPlatform: true}).wait();

			this.$deviceLogProvider.on("data", (identifier: string, data: any) => {
				this.emit('deviceLogData', identifier, data.toString());
			});
		}).future<void>()();
Example #29
0
    ViewModel.count({}, (counterror:any, count:number):void => {
        if (!counterror) {
            if (count <= 0) {
                logger.trace("Creating init View");
                var ev = new emitter;
                ev.on("view", function (data) {
                    var view = new ViewModel();
                    view.Name = data.Name;
                    view.Pages = data.Pages;
                    view.save(function (error) {
                        logger.trace("Created init View");
                    });
                });

                var config = new Settings;
                var views = config.initView.Views;
                _.each(views, function (data, index) {
                    ev.emit("view", data);
                });
            }
        } else {
            logger.error("count open");
        }
    });
Example #30
0
    exists(recipeFile).then(async (exists) =>
    {
        if (exists)
        {
            logger.verbose(recipeFile + ' exists')
            var recipeStore: { [id: string]: Recipe } = JSON.parse(await readFile(recipeFile, { encoding: 'utf8' }));
            logger.verbose(recipeStore);
            init = true;
            worker.on('ready', function ()
            {
                setTimeout(function ()
                {

                    logger.verbose('initializing recipes')
                    akala.eachAsync(recipeStore, async function (recipe, name, next)
                    {
                        delete recipe.triggerId;
                        try
                        {
                            await cl.insert(recipe, init);
                        }
                        catch
                        {
                            setTimeout(cl.insert, 60000, recipe, true);
                        }
                        next();
                    }, function ()
                        {
                            init = false;
                        });
                }, 30000)
            })
        }
        else
            logger.info(recipeFile + ' does not exist');
    });