Permalink
Browse files

Rewrote some of the getch logic to make it behave more in accordance …

…with the behaviour gen_server. Also cleaned up some unnecessary code lines and made things more readable.
  • Loading branch information...
1 parent 76bd46c commit 42cd2edac9a87a9a5d613e493f62979b8e6acf55 @mazenharake mazenharake committed Mar 29, 2010
Showing with 10 additions and 17 deletions.
  1. +10 −17 src/cecho_srv.erl
View
27 src/cecho_srv.erl
@@ -38,7 +38,7 @@
-export([start_link/0, call/2, getch/0]).
%% Records
--record(state, { port, getpid }).
+-record(state, { port, getch }).
%% =============================================================================
%% Module API
@@ -50,11 +50,7 @@ call(Cmd, Args) ->
gen_server:call(?MODULE, {call, Cmd, Args}, infinity).
getch() ->
- ?MODULE ! {getch, self()},
- receive
- {ch, Chr} ->
- Chr
- end.
+ gen_server:call(?MODULE, getch, infinity).
%% =============================================================================
%% Behaviour Callbacks
@@ -74,26 +70,23 @@ init(no_args) ->
end.
handle_call({call, Cmd, Args}, _From, State) ->
- Response = do_call(State#state.port, Cmd, Args),
- {reply, Response, State}.
+ {reply, do_call(State#state.port, Cmd, Args), State};
+handle_call(getch, From, #state{ getch = undefined } = State) ->
+ {noreply, State#state{ getch = From }};
+handle_call(getch, _From, State) ->
+ {reply, -1, State}.
terminate(_Reason, State) ->
do_call(State#state.port, ?ENDWIN),
do_call(State#state.port, ?CURS_SET, ?ceCURS_NORMAL),
erlang:port_close(State#state.port),
erl_ddll:unload("cecho").
-handle_info({getch, From}, #state{ getpid = undefined } = State) ->
- {noreply, State#state{ getpid = From }};
-handle_info({getch, From}, State) ->
- exit(From, kill),
- {noreply, State};
-handle_info({_Port, {data, _Binary}}, #state{ getpid = undefined } = State) ->
+handle_info({_Port, {data, _Binary}}, #state{ getch = undefined } = State) ->
{noreply, State};
handle_info({_Port, {data, Binary}}, State) ->
- Ch = binary_to_term(Binary),
- State#state.getpid ! {ch, Ch},
- {noreply, State#state{ getpid = undefined }}.
+ gen_server:reply(State#state.getch, binary_to_term(Binary)),
+ {noreply, State#state{ getch = undefined }}.
%% @hidden
handle_cast(_, State) ->

0 comments on commit 42cd2ed

Please sign in to comment.