import { EventEmitter2 } from 'eventemitter2' ; import { IDiscordStatus , DiscordStatusEvent , DiscordEvents } from './Discord' ; import { bus } from './EventHandler' ; export interface IGUITunnel { send ( evt_id , evt ) : void ; } export class GUITunnelPacket { id : string ; event : string | string [ ] ; data : any ; constructor ( id , event , data ) { this . id = id ; this . event = event ; this . data = data ; } } const outputemitterTunnel = new EventEmitter2 ( ) ; process . on ( 'message' , ( message ) => { let evt = JSON . parse ( message ) ; outputemitterTunnel . emit ( evt . event , evt . data ) ; } ) ; export class GUITunnel implements IGUITunnel { private id : string ; private dest : any ; private emitter : EventEmitter2 = new EventEmitter2 ( ) ; constructor ( dest , id , instance ) { this . id = id ; this . dest = dest ; this . emitter . onAny ( ( event , ... values ) => { if ( this . dest . send ) { this . dest . send ( JSON . stringify ( new GUITunnelPacket ( this . id , event , values ) ) ) ; } } ) ; if ( instance !== null && instance !== undefined ) { this . setupTunnelMessageHandlers ( instance ) ; } } send ( evt_id , evt ) { this . emitter . emit ( evt_id , evt ) ; } setupTunnelMessageHandlers ( instance ) { let p = Object . getPrototypeOf ( instance ) ; if ( p . hasOwnProperty ( 'ModLoader' ) ) { if ( p . ModLoader . hasOwnProperty ( 'TunnelMessageHandler' ) ) { if ( p . ModLoader . TunnelMessageHandler . hasOwnProperty ( 'MessageHandlers' ) !== null ) { p . ModLoader . TunnelMessageHandler . MessageHandlers . forEach ( function ( value , key ) { let a = ( instance as any ) [ value ] . bind ( instance ) ; outputemitterTunnel . on ( key , a ) ; } ) ; } } } } } export function TunnelMessageHandler ( key ) { return function ( target , propertyKey , descriptor ) { if ( target . ModLoader === undefined ) { target [ 'ModLoader' ] = { } ; } if ( target . ModLoader . TunnelMessageHandler === undefined ) { target . ModLoader [ 'TunnelMessageHandler' ] = { } ; } if ( target . ModLoader . TunnelMessageHandler . MessageHandlers === undefined ) { target . ModLoader . TunnelMessageHandler [ 'MessageHandlers' ] = new Map < string , Function > ( ) ; } target . ModLoader . TunnelMessageHandler . MessageHandlers . set ( key , propertyKey ) ; } ; } const APITunnel = new GUITunnel ( process , 'modloader64_api' , null ) ; export interface IGUIAPI { openWindow ( width , height , file ) : void ; setDiscordStatus ( status ) : void ; tunnel : IGUITunnel ; } export class GUIAPI implements IGUIAPI { tunnel : IGUITunnel ; constructor ( id , instance ) { this . tunnel = new GUITunnel ( process , id , instance ) ; } openWindow ( width , height , file ) { APITunnel . send ( 'openWindow' , { width , height , file } ) ; } setDiscordStatus ( status ) { let evt = new DiscordStatusEvent ( status ) ; bus . emit ( DiscordEvents . SET_STATUS , evt ) ; if ( evt . canceled ) { return ; } APITunnel . send ( 'setDiscordStatus' , evt . status ) ; } }