public class CoreConnector { unowned Thread thread; bool running; Erl.Node node; Erl.Connection con; Erl.Term self; Roster roster; private class TermStore { public Erl.Term term; } static construct { Erl.init(); } public CoreConnector(Roster roster0) { running = false; roster = roster0; } public bool start() { if(running) return true; running = true; node = Erl.Node("ephraim-gtk", "magiccookie", 0); con = node.connect("ephraim-core@avalon.local"); self = Erl.mk_self_pid(node); con.reg_send("ephraim", Erl.format("{register_ui,~w}", self)); try { thread = Thread.create(receive, true); return true; } catch(ThreadError e) { return false; } } public void stop() { if(!running) return; running = false; thread.join(); con.reg_send("ephraim", Erl.format("{unregister_ui,~w}", self)); } private void* receive() { while(running) { TermStore response = new TermStore(); Erl.ReceiveType ret = con.receive(out response.term, 1000); switch(ret) { case Erl.ReceiveType.ERROR: if(Erl.errno == Erl.Error.TIMEDOUT) break; running = false; break; case Erl.ReceiveType.TICK: // Do nothing break; case Erl.ReceiveType.MSG: Idle.add(() => {handleTerm(response); return false;}); break; } } return null; } private Erl.Term? match(string pattern, Erl.Term term) { Erl.Term pattern_term = Erl.format(pattern); if(pattern_term.match(term) != 0) return pattern_term; else return null; } private void handleTerm(TermStore store) { unowned Erl.Term term = store.term; Erl.Term match_term; if((match_term = match("{roster_update,JID,Resources}", term)) != null) { Erl.Term JID_term = match_term.var_content("JID"); string JID = ((string)JID_term.bin_ptr()).ndup(JID_term.bin_size()); roster.update_contact(new Contact(JID)); } else { Erl.print_term(stdout, term); stdout.printf("\n"); } } }