-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathgroup.erl
More file actions
1437 lines (1307 loc) · 59.2 KB
/
Copy pathgroup.erl
File metadata and controls
1437 lines (1307 loc) · 59.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% SPDX-License-Identifier: Apache-2.0
%%
%% Copyright Ericsson AB 1996-2026. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(group).
-moduledoc false.
-compile([nowarn_deprecated_catch,
{nowarn_deprecated_function, [{erlang,exit,2}]},
{nowarn_unsafe_function, {os, cmd, 1}}]).
-include_lib("kernel/include/logger.hrl").
%% A group leader process for user io.
%% This process receives input data from user_drv in this format
%% {Drv,{data,unicode:charlist()}}
%% It then keeps that data as unicode in its state and converts it
%% to latin1/unicode on a per request basis. If any data is left after
%% a request, that data is again kept as unicode.
%%
%% There are two major modes of group that work in similar though subtly different
%% ways, xterm and dumb. The xterm mode is used when a "newshell" is used and dumb
%% is used when "oldshell" or "noshell" are used.
-export([start/1, start/2, start/3, whereis_shell/0, init/3, server/3,
xterm/3, dumb/3, handle_info/3]).
%% gen statem callbacks
-export([init/1, callback_mode/0, format_status/1]).
%% Logger report format fun
-export([format_io_request_log/1, log_io_request/3]).
-type mfargs() :: {module(), atom(), [term()]}.
-type nmfargs() :: {node(), module(), atom(), [term()]}.
-define(IS_PUTC_REQ(Req), element(1, Req) =:= put_chars orelse
element(1, Req) =:= requests orelse
element(1, Req) =:= put_ansi).
-define(IS_INPUT_REQ(Req),
element(1, Req) =:= get_chars orelse element(1, Req) =:= get_line orelse
element(1, Req) =:= get_until orelse element(1, Req) =:= get_password).
-record(input_state,
{
%% Used by all input routines
from,
reply_as,
prompt_bytes,
encoding,
collect,
cont,
%% Used by xterm state
lines = [], %% Previously entered lines that have not yet been consumed
save_history = true, %% Whether this input request should save history
%% used by dumb state
get_fun,
io_lib_state = start
}).
-record(state,
{ read_type :: list | binary,
driver :: pid(),
echo :: boolean(),
log = none :: none | input | output | all,
dumb :: boolean(),
shell = noshell :: noshell | pid(),
%% Only used by dumb
terminal_mode = cooked :: raw | cooked | disabled,
%% Only used by xterm
line_history :: [string()] | undefined,
save_history :: boolean(), %% Whether get_line and get_until should save history
expand_fun :: function() | undefined,
expand_below :: boolean() | undefined,
%% Used to push details about a input requests
%% if there are multiple ones in progress.
input_queue = queue:new(),
%% Keeps extra data inbetween input routines
buf = [] :: unicode:chardata() | eof,
input = undefined :: #input_state{} | undefined
}).
-spec start(pid()) -> pid().
start(Drv) ->
start(Drv, noshell).
-spec start(pid(), function() | nmfargs() | mfargs() | noshell) -> pid().
start(Drv, Shell) ->
start(Drv, Shell, []).
-spec start(pid(), function() | nmfargs() | mfargs() | noshell,
[{name, atom()} |
{dumb, boolean()} |
{echo, boolean()} |
{expand_fun, function()} |
{expand_below, boolean()}]) -> pid().
start(Drv, Shell, Options) ->
{ok, Pid} =
case proplists:get_value(name, Options) of
undefined ->
gen_statem:start(?MODULE, [Drv, Shell, Options], []);
Name ->
gen_statem:start({local, Name}, ?MODULE, [Drv, Shell, Options], [])
end,
Pid.
callback_mode() -> state_functions.
init([Drv, Shell, Options]) ->
process_flag(trap_exit, true),
%% Cleanup ancestors so that observer looks nice
_ = [put('$ancestors',tl(get('$ancestors'))) || Shell =:= noshell],
%% We link here instead of using start_link so that Drv does not become our parent
%% We don't want Drv as our parent as Drv will send EXIT signals to us and we need
%% to handle those and not just terminate.
link(Drv),
Dumb = proplists:get_value(dumb, Options, Shell =:= noshell),
State = #state{
driver = Drv,
read_type = list,
dumb = Dumb,
save_history = not Dumb,
%% echo is normally false for dumb and true for non-dumb, but when group is used by
%% ssh, it can also be set to true when dumb is true.
echo = proplists:get_value(echo, Options, not Dumb)
},
edlin:init(),
{ok, init, State, {next_event, internal, [Shell, Options]}}.
format_status(#{state := State}) ->
State#state{ line_history = undefined }.
init(internal, [Shell, Options], State = #state{ dumb = Dumb }) ->
StartedShell = start_shell(Shell),
NonDumbState =
if not Dumb ->
State#state{
line_history = group_history:load(),
expand_below = proplists:get_value(expand_below, Options, not Dumb),
expand_fun = normalize_expand_fun(Options, fun edlin_expand:expand/2)
};
Dumb ->
State
end,
{next_state, server, NonDumbState#state{ shell = StartedShell }}.
-spec whereis_shell() -> undefined | pid().
whereis_shell() ->
case node(group_leader()) of
Node when Node =:= node() ->
case user_drv:whereis_group() of
undefined -> undefined;
GroupPid ->
{dictionary, Dict} = erlang:process_info(GroupPid, dictionary),
proplists:get_value(shell, Dict)
end;
OtherNode ->
erpc:call(OtherNode, group, whereis_shell, [])
end.
%% start_shell(Shell)
%% Spawn a shell with its group_leader from the beginning set to ourselves.
%% If Shell a pid the set its group_leader.
-spec start_shell(mfargs() | nmfargs() |
module() | function() | pid() | noshell) -> pid() | noshell.
start_shell(noshell) -> noshell;
start_shell({Mod,Func,Args}) ->
start_shell_mfa(Mod, Func, Args);
start_shell({Node,Mod,Func,Args}) ->
start_shell_mfa(erpc, call, [Node,Mod,Func,Args]);
start_shell(Shell) when is_atom(Shell) ->
start_shell_mfa(Shell, start, []);
start_shell(Shell) when is_function(Shell) ->
start_shell_fun(Shell);
start_shell(Shell) when is_pid(Shell) ->
group_leader(self(), Shell), % we are the shells group leader
link(Shell), % we're linked to it.
put(shell, Shell),
proc_lib:set_label({group, Shell}),
Shell.
start_shell_mfa(M, F, Args) ->
G = group_leader(),
group_leader(self(), self()),
case apply(M, F, Args) of
Shell when is_pid(Shell) ->
group_leader(G, self()),
link(Shell), % we're linked to it.
proc_lib:set_label({group, {M, F, Args}}),
put(shell, Shell),
Shell;
Error -> % start failure
exit(Error) % let the group process crash
end.
start_shell_fun(Fun) ->
G = group_leader(),
group_leader(self(), self()),
case Fun() of
Shell when is_pid(Shell) ->
group_leader(G, self()),
link(Shell), % we're linked to it.
proc_lib:set_label({group, Fun}),
put(shell, Shell),
Shell;
Error -> % start failure
exit(Error) % let the group process crash
end.
%% When there are no outstanding input requests we are in this state
server(info, {io_request,From,ReplyAs,Req} = IOReq, Data) when is_pid(From), ?IS_INPUT_REQ(Req) ->
log_io_request(IOReq, Data#state.log, server_name()),
{next_state,
if Data#state.dumb orelse not Data#state.echo -> dumb; true -> xterm end,
Data#state{ input = #input_state{ from = From, reply_as = ReplyAs } },
{next_event, internal, Req} };
server(info, {Drv, _}, #state{ driver = Drv }) ->
%% We postpone any Drv event sent to us as they are handled in xterm or dumb states
{keep_state_and_data, postpone};
server(info, Msg, Data) ->
handle_info(server, Msg, Data).
%% This is the dumb terminal state, also used for noshell and xterm get_password
%% When terminal_mode == raw, the terminal is in '{noshell,raw}' mode, which means that
%% for get_until and get_chars we change the behaviour a bit so that characters are
%% delivered as they are typed instead of at new-lines.
dumb(internal, {get_chars, Encoding, Prompt, N}, Data = #state{ terminal_mode = raw }) ->
dumb(input_request, {collect_chars_eager, N, Prompt, Encoding, fun get_chars_dumb/5}, Data);
dumb(internal, {get_line, Encoding, Prompt}, Data = #state{ terminal_mode = raw }) ->
dumb(input_request, {collect_line, [], Prompt, Encoding, fun get_line_dumb/5}, Data);
dumb(internal, {get_until, Encoding, Prompt, M, F, As}, Data = #state{ terminal_mode = raw }) ->
dumb(input_request, {get_until, {M, F, As}, Prompt, Encoding, fun get_chars_dumb/5}, Data);
dumb(internal, {get_chars, Encoding, Prompt, N}, Data) ->
dumb(input_request, {collect_chars, N, Prompt, Encoding, fun get_chars_dumb/5}, Data);
dumb(internal, {get_line, Encoding, Prompt}, Data) ->
dumb(input_request, {collect_line, [], Prompt, Encoding, fun get_line_dumb/5}, Data);
dumb(internal, {get_until, Encoding, Prompt, M, F, As}, Data) ->
dumb(input_request, {get_until, {M, F, As}, Prompt, Encoding, fun get_line_dumb/5}, Data);
dumb(internal, {get_password, Encoding}, Data = #state{ terminal_mode = raw }) ->
%% When getting the password we force echo to be off for the time of
%% the get password and set a shell in order to use edit_line_dumb instead
%% of edit_line_noshell.
GetLine = fun(Buf, Pbs, Cont, LineEncoding, LineData) ->
get_line_dumb(Buf, Pbs, Cont, LineEncoding,
LineData#state{ echo = false, shell = self() })
end,
dumb(input_request, {collect_line_no_eol, [], "", Encoding, GetLine}, Data);
dumb(internal, {get_password, _Encoding}, Data) ->
%% TODO: Implement for noshell by disabling characters echo if isatty(stdin)
io_reply(Data, {error, enotsup}),
pop_state(Data);
dumb(input_request, {CollectF, CollectAs, Prompt, Encoding, GetFun},
Data = #state{ input = OrigInputState }) ->
InputState = OrigInputState#input_state{
prompt_bytes = prompt_bytes(Prompt, Encoding),
collect = {CollectF, CollectAs},
encoding = Encoding, get_fun = GetFun },
dumb(data, Data#state.buf, Data#state{ input = InputState, buf = [] });
%% If we get an input request while handling this request we push the current state
%% and re-issue event in server state
dumb(info, {io_request, _From, _ReplyAs, Req}, Data) when ?IS_INPUT_REQ(Req) ->
{next_state, server, push_state(dumb, Data), [{postpone, true}]};
dumb(internal, restore_input_request, Data = #state{ buf = Buf }) ->
dumb(data, Buf, Data#state{ buf = [] });
dumb(data, Buf, Data = #state{ input = #input_state{ prompt_bytes = Pbs, encoding = Encoding,
io_lib_state = State, cont = Cont,
collect = {CollectF, CollectAs},
get_fun = GetFun } = InputState }) ->
%% Get a single line using get_line_dumb, or a single character using get_chars_dumb
case GetFun(Buf, Pbs, Cont, Encoding, Data) of
{no_translation, unicode, latin1} ->
io_reply(Data, {error,{no_translation, unicode, latin1}}),
pop_state(Data#state{ buf = [] });
{done, NewLine, RemainBuf} ->
EncodedLine = cast(NewLine, Data#state.read_type, Encoding),
case io_lib:CollectF(State, EncodedLine, Encoding, CollectAs) of
{stop, eof, _} ->
io_reply(Data, eof),
pop_state(Data#state{ buf = eof });
{stop, Result, eof} ->
io_reply(Data, Result),
pop_state(Data#state{ buf = eof });
{stop, Result, Rest} ->
io_reply(Data, Result),
pop_state(Data#state{ buf = append(Rest, RemainBuf, Encoding) });
{'EXIT',_} ->
io_reply(Data, {error,err_func(io_lib, CollectF, CollectAs)}),
pop_state(Data#state{ buf = [] });
NewState ->
[Data#state.driver ! {self(), read, io_lib:CollectF(NewState)} || Data#state.shell =:= noshell],
dumb(data, RemainBuf, Data#state{ input = InputState#input_state{ cont = undefined, io_lib_state = NewState } })
end;
{more_chars, NewCont} ->
[Data#state.driver ! {self(), read, 0} || Data#state.shell =:= noshell],
{keep_state, Data#state{ input = InputState#input_state{ cont = NewCont } } }
end;
dumb(info, {Drv, activate}, #state{ driver = Drv }) ->
keep_state_and_data;
dumb(info, Msg, Data) ->
handle_info(dumb, Msg, Data).
%% The xterm state handles the "newshell" mode. This is the most advanced shell
%% that has a shell history, can open text editors and navigate in multiline shell
%% expressions.
xterm(internal, {get_chars, Encoding, Prompt, N}, Data) ->
xterm(input_request, {collect_chars, N, Prompt, Encoding}, Data);
xterm(internal, {get_line, Encoding, Prompt}, Data) ->
xterm(input_request, {collect_line, [], Prompt, Encoding}, Data);
xterm(internal, {get_until, Encoding, Prompt, M, F, As}, Data) ->
xterm(input_request, {get_until, {M, F, As}, Prompt, Encoding}, Data);
xterm(internal, {get_password, Encoding}, Data) ->
%% When getting the password we change state to dumb and use its
%% implementation and set echo to false.
GetLine = fun(Buf, Pbs, Cont, LineEncoding, LineData) ->
get_line_dumb(Buf, Pbs, Cont, LineEncoding,
LineData#state{ echo = false })
end,
case dumb(input_request, {collect_line_no_eol, [], "", Encoding, GetLine}, Data) of
{keep_state, NewData} ->
%% As we are currently in the xterm state, we transition to dumb
{next_state, dumb, NewData};
Else when element(1, Else) =:= next_state -> Else
end;
xterm(input_request, {CollectF, CollectAs, Prompt, Encoding},
Data = #state{ input = OrigInputState }) ->
InputState = OrigInputState#input_state{
prompt_bytes = prompt_bytes(Prompt, Encoding),
collect = {CollectF, CollectAs},
save_history = Data#state.save_history,
encoding = Encoding },
xterm(data, Data#state.buf, Data#state{ input = InputState, buf = [] });
xterm(info, {io_request, _From, _ReplyAs, Req}, Data = #state{ driver = Drv })
when ?IS_INPUT_REQ(Req) ->
%% We got an new input request while serving this one, we:
%% * erase current line
%% * push the current input state
%% * re-issue the input event in the server state
send_drv_reqs(Drv, edlin:erase_line()),
{next_state, server, push_state(xterm, Data), [{postpone, true}]};
xterm(internal, restore_input_request,
#state{ buf = Buf, driver = Drv, input = #input_state{ cont = {EdlinCont, _} }} = Data) ->
%% We are restoring an input request so we redraw the line
send_drv_reqs(Drv, edlin:redraw_line(EdlinCont)),
xterm(data, Buf, Data#state{ buf = [] });
xterm(data, Buf, Data = #state{ input = #input_state{
prompt_bytes = Pbs, encoding = Encoding,
lines = Lines, cont = Cont,
save_history = SaveHistory,
collect = {CollectF, CollectAs} } = InputState }) ->
%% Get a single line using edlin
case get_line_edlin(Buf, Pbs, Cont, Lines, Encoding, Data) of
{done, NewLines, RemainBuf} ->
CurrentLine = cast(edlin:current_line(NewLines), Data#state.read_type, Encoding),
case io_lib:CollectF(start, CurrentLine, Encoding, CollectAs) of
{stop, eof, _} ->
io_reply(Data, eof),
pop_state(Data#state{ buf = eof });
{stop, Result, eof} ->
io_reply(Data, Result),
pop_state(Data#state{ buf = eof });
{stop, Result, Rest} ->
%% Prompt was valid expression, clear the prompt in user_drv and redraw
%% the formatted expression.
FormattedLine = format_expression(NewLines, Data#state.driver),
[CL1|LB1] = lists:reverse(string:split(FormattedLine, "\n", all)),
LineCont1 = {LB1,{lists:reverse(CL1++"\n"), []},[]},
MultiLinePrompt = lists:duplicate(shell:prompt_width(Pbs), $\s),
send_drv_reqs(Data#state.driver, [{redraw_prompt, Pbs, MultiLinePrompt, LineCont1},new_prompt]),
NewHistory =
if SaveHistory ->
%% Save into history buffer if issued from shell process
save_line_buffer(string:trim(FormattedLine, both)++"\n",
Data#state.line_history);
not SaveHistory ->
Data#state.line_history
end,
io_reply(Data, Result),
pop_state(
Data#state{ line_history = NewHistory,
buf = append(Rest, RemainBuf, Encoding) });
{'EXIT',_} ->
io_reply(Data, {error,err_func(io_lib, CollectF, CollectAs)}),
pop_state(Data#state{ buf = [] });
_NewState ->
xterm(data, RemainBuf, Data#state{ input = InputState#input_state{ cont = undefined, lines = NewLines} })
end;
{blink, NewCont} ->
{keep_state, Data#state{ input = InputState#input_state{ cont = NewCont } }, 1000};
{more_chars, NewCont} ->
{keep_state, Data#state{ input = InputState#input_state{ cont = NewCont } } }
end;
xterm(info, {io_request,From,ReplyAs,Req}, State)
when ?IS_PUTC_REQ(Req) ->
putc_request(Req, From, ReplyAs, State),
keep_state_and_data;
xterm(info, {Drv, activate},
#state{ driver = Drv, input = #input_state{ cont = {EdlinCont, _} } }) ->
send_drv_reqs(Drv, edlin:redraw_line(EdlinCont)),
keep_state_and_data;
xterm(info, Msg, Data) ->
handle_info(xterm, Msg, Data);
xterm(timeout, 1000, Data) ->
%% Blink timeout triggered
xterm(data, [], Data).
%% Handle the info messages that needs to be managed in all states
handle_info(State, {Drv, {data, Buf}}, Data = #state{ driver = Drv }) ->
?MODULE:State(data, Buf, Data);
handle_info(State, {Drv, eof}, Data = #state{ driver = Drv }) ->
?MODULE:State(data, eof, Data);
handle_info(_State, {Drv, echo, Bool}, Data = #state{ driver = Drv }) ->
{keep_state, Data#state{ echo = Bool } };
handle_info(_State, {Drv, {error, _} = Error}, Data = #state{ driver = Drv }) ->
io_reply(Data, Error),
pop_state(Data#state{ buf = [] });
handle_info(_State, {Drv, terminal_mode, Mode}, Data = #state{ driver = Drv }) ->
noshell = Data#state.shell,
true = lists:member(Mode, [raw, cooked, disabled]),
{keep_state, Data#state{ terminal_mode = Mode }};
handle_info(_State, {io_request, From, ReplyAs, {setopts, Opts}}, Data) ->
{Reply, NewData} = setopts(Opts, Data),
io_reply(From, ReplyAs, Reply),
{keep_state, NewData};
handle_info(_State, {io_request,From,ReplyAs, getopts}, Data) ->
io_reply(From, ReplyAs, getopts(Data)),
keep_state_and_data;
handle_info(_State, {io_request,From,ReplyAs, {get_geometry, What}}, Data) ->
case get_tty_geometry(Data#state.driver) of
{Width, _Height} when What =:= columns->
io_reply(From, ReplyAs, Width);
{_Width, Height} when What =:= rows->
io_reply(From, ReplyAs, Height);
_ ->
io_reply(From, ReplyAs, {error, enotsup})
end,
keep_state_and_data;
handle_info(_State, {io_request,From,ReplyAs,Req}, Data) when ?IS_PUTC_REQ(Req) ->
putc_request(Req, From, ReplyAs, Data);
handle_info(_State, {io_request,From,ReplyAs, _Req}, _Data) ->
io_reply(From, ReplyAs, {error, request}),
keep_state_and_data;
handle_info(_State, {reply, undefined, _Reply}, _Data) ->
%% Ignore any reply with an undefined From.
keep_state_and_data;
handle_info(_State, {reply,{From,ReplyAs},Reply}, _Data) ->
io_reply(From, ReplyAs, Reply),
keep_state_and_data;
handle_info(_State, {driver_id,ReplyTo}, Data) -> %% TODO: Remove this?
ReplyTo ! {self(),driver_id, Data#state.driver},
keep_state_and_data;
handle_info(_State, {'EXIT', Drv, interrupt}, #state{ driver = Drv, shell = Shell, input = undefined }) ->
%% Send interrupt to the shell of there is no current input request
[exit(Shell, interrupt) || is_pid(Shell)],
keep_state_and_data;
handle_info(_State, {'EXIT', Drv, interrupt}, #state{ driver = Drv } = Data) ->
%% Interrupt current input request
io_reply(Data, {error, interrupted}),
pop_state(Data#state{ buf = [] });
handle_info(_State, {'EXIT',Drv,_R}, #state{ driver = Drv } = Data) ->
[ exit(Data#state.shell, kill)
|| is_pid(Data#state.shell) andalso Data#state.input =/= undefined],
{stop, normal};
handle_info(_State, {'EXIT',Shell,R}, #state{ shell = Shell, driver = Drv }) ->
%% We propagate the error reason from the shell to the driver, but we don't
%% want to exit ourselves with that reason as it will generate crash report
%% messages that we do not want.
exit(Drv, R),
{stop, normal};
handle_info(_State, _UnknownEvent, _Data) ->
%% Ignore this unknown message.
keep_state_and_data.
%% When we get an input request while already serving another, we
%% push the state of the current request into the input_queue and
%% switch to handling the new request.
push_state(State, Data) ->
Data#state{ input_queue = queue:in({State, Data#state.input}, Data#state.input_queue) }.
%% When an input request is done we then need to check if there was
%% another request in progress, and if so we pop its state and resume it.
pop_state(Data) ->
case queue:out(Data#state.input_queue) of
{empty, _} ->
{next_state, server, Data#state{ input = undefined }};
{{value, {State, InputState}}, NewInputQueue} ->
{next_state, State, Data#state{ input = InputState, input_queue = NewInputQueue },
{next_event, internal, restore_input_request } }
end.
%% Functions for getting data from the driver
get_tty_geometry(Drv) ->
Drv ! {self(),tty_geometry},
receive
{Drv,tty_geometry,Geometry} ->
Geometry
after 2000 ->
timeout
end.
get_unicode_state(Drv) ->
Drv ! {self(),get_unicode_state},
receive
{Drv,get_unicode_state,UniState} ->
UniState;
{Drv,get_unicode_state,error} ->
{error, internal}
after 2000 ->
{error,timeout}
end.
set_unicode_state(Drv,Bool) ->
Drv ! {self(),set_unicode_state,Bool},
receive
{Drv,set_unicode_state,_OldUniState} ->
ok
after 2000 ->
timeout
end.
get_terminal_state(Drv) ->
Drv ! {self(),get_terminal_state},
receive
{Drv,get_terminal_state,Terminal} ->
Terminal;
{Drv,get_terminal_state,error} ->
{error, internal}
after 2000 ->
{error,timeout}
end.
%% This function handles any put_chars request
putc_request(Req, From, ReplyAs, State) ->
log_io_request({io_request, From, ReplyAs, Req}, State#state.log, server_name()),
case putc_request(Req, State#state.driver, {From, ReplyAs}) of
{reply,Reply} ->
io_reply(From, ReplyAs, Reply),
keep_state_and_data;
noreply ->
%% We expect a {reply,_} message from the Drv when request is done
keep_state_and_data
end.
%% Put_chars, unicode is the normal message, characters are always in
%% standard unicode format.
%% You might be tempted to send binaries unchecked, but the driver
%% expects unicode, so that is what we should send...
%% putc_request({put_chars,unicode,Binary}, Drv, Buf) when is_binary(Binary) ->
%% send_drv(Drv, {put_chars,Binary}),
%% {ok,ok,Buf};
%%
%% These put requests have to be synchronous to the driver as otherwise
%% there is no guarantee that the data has actually been printed.
putc_request({put_ansi, Opts, Ansi}, Drv, From) ->
send_drv(Drv, {put_ansi_sync, Opts, Ansi, From}),
noreply;
putc_request({put_chars,unicode,Chars}, Drv, From) ->
case catch unicode:characters_to_binary(Chars,utf8) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars_sync, unicode, Binary, From}),
noreply;
_ ->
{reply,{error,{put_chars, unicode,Chars}}}
end;
putc_request({put_chars,unicode,M,F,As}, Drv, From) ->
case catch apply(M, F, As) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars_sync, unicode, Binary, From}),
noreply;
Chars ->
case catch unicode:characters_to_binary(Chars,utf8) of
B when is_binary(B) ->
send_drv(Drv, {put_chars_sync, unicode, B, From}),
noreply;
_ ->
{reply,{error,F}}
end
end;
putc_request({put_chars,latin1,Output}, Drv, From) ->
send_drv(Drv, {put_chars_sync, latin1, Output, From}),
noreply;
putc_request({put_chars,latin1,M,F,As}, Drv, From) ->
case catch apply(M, F, As) of
Ret when is_list(Ret) =:= false, is_binary(Ret) =:= false ->
{reply, {error, F}};
Chars -> send_drv(Drv, {put_chars_sync, latin1, Chars, From}),
noreply
end;
putc_request({requests,Reqs}, Drv, From) ->
putc_requests(Reqs, {reply, ok}, Drv, From);
%% BC with pre-R13
putc_request({put_chars,Chars}, Drv, From) ->
putc_request({put_chars,latin1,Chars}, Drv, From);
putc_request({put_chars,M,F,As}, Drv, From) ->
putc_request({put_chars,latin1,M,F,As}, Drv, From);
putc_request(_, _Drv, _From) ->
{error,{error,request}}.
%% Status = putc_requests(RequestList, PrevStat, From, Drv, Shell)
%% Process a list of output requests as long as
%% the previous status is 'ok' or noreply.
%%
%% We use undefined as the From for all but the last request
%% in order to discards acknowledgements from those requests.
%%
putc_requests([R|Rs], noreply, Drv, From) ->
ReqFrom = if Rs =:= [] -> From; true -> undefined end,
putc_requests(Rs, putc_request(R, Drv, ReqFrom), Drv, From);
putc_requests([R|Rs], {reply,ok}, Drv, From) ->
ReqFrom = if Rs =:= [] -> From; true -> undefined end,
putc_requests(Rs, putc_request(R, Drv, ReqFrom), Drv, From);
putc_requests([_|_], Error, _Drv, _From) ->
Error;
putc_requests([], Stat, _Drv, _From) ->
Stat.
%% io_reply(From, ReplyAs, Reply)
%% The function for sending i/o command acknowledgement.
%% The ACK contains the return value.
io_reply(#state{ input = #input_state{ from = From, reply_as = As } }, Reply) ->
io_reply(From, As, Reply).
io_reply(undefined, _ReplyAs, _Reply) ->
%% Ignore these replies as they are generated from io_requests/5.
ok;
io_reply(From, ReplyAs, Reply) ->
From ! {io_reply,ReplyAs,Reply},
ok.
%% send_drv(Drv, Message)
%% send_drv_reqs(Drv, Requests)
send_drv(Drv, Msg) ->
Drv ! {self(),Msg},
ok.
send_drv_reqs(_Drv, []) -> ok;
send_drv_reqs(Drv, Rs) ->
send_drv(Drv, {requests,Rs}).
expand_encoding([]) ->
[];
expand_encoding([latin1 | T]) ->
[{encoding,latin1} | expand_encoding(T)];
expand_encoding([unicode | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([H|T]) ->
[H|expand_encoding(T)].
%% setopts
setopts(Opts0,Data) ->
Opts = proplists:unfold(
proplists:substitute_negations(
[{list,binary}],
expand_encoding(Opts0))),
case check_valid_opts(Opts, Data#state.shell =/= noshell) of
true ->
do_setopts(Opts,Data);
false ->
{{error,enotsup},Data}
end.
check_valid_opts([], _) ->
true;
check_valid_opts([{binary,Flag}|T], HasShell) when is_boolean(Flag) ->
check_valid_opts(T, HasShell);
check_valid_opts([{encoding,Valid}|T], HasShell) when Valid =:= unicode;
Valid =:= utf8;
Valid =:= latin1 ->
check_valid_opts(T, HasShell);
check_valid_opts([{echo,Flag}|T], HasShell) when is_boolean(Flag) ->
check_valid_opts(T, HasShell);
check_valid_opts([{line_history,Flag}|T], HasShell = true) when is_boolean(Flag) ->
check_valid_opts(T, HasShell);
check_valid_opts([{expand_fun,Fun}|T], HasShell = true) when is_function(Fun, 1);
is_function(Fun, 2) ->
check_valid_opts(T, HasShell);
check_valid_opts([{log,Flag}|T], HasShell) ->
case lists:member(Flag, [none, output, input, all]) of
true -> check_valid_opts(T, HasShell);
false -> false
end;
check_valid_opts(_, _HasShell) ->
false.
do_setopts(Opts, Data) ->
ExpandFun = normalize_expand_fun(Opts, Data#state.expand_fun),
Echo = proplists:get_value(echo, Opts, Data#state.echo),
case proplists:get_value(encoding, Opts) of
Valid when Valid =:= unicode; Valid =:= utf8 ->
set_unicode_state(Data#state.driver,true);
latin1 ->
set_unicode_state(Data#state.driver,false);
undefined ->
ok
end,
ReadType =
case proplists:get_value(binary, Opts,
case Data#state.read_type of
binary -> true;
_ -> false
end) of
true ->
binary;
false ->
list
end,
LineHistory = proplists:get_value(line_history, Opts, Data#state.save_history),
Log = proplists:get_value(log, Opts, Data#state.log),
{ok, Data#state{ expand_fun = ExpandFun, echo = Echo, read_type = ReadType,
save_history = LineHistory, log = Log }}.
normalize_expand_fun(Options, Default) ->
case proplists:get_value(expand_fun, Options, Default) of
Fun when is_function(Fun, 1) -> fun(X,_) -> Fun(X) end;
Fun -> Fun
end.
getopts(Data) ->
Exp = {expand_fun, case Data#state.expand_fun of
Func when is_function(Func) ->
Func;
_ ->
false
end},
Echo = {echo, case Data#state.echo of
Bool when Bool =:= true; Bool =:= false ->
Bool;
_ ->
false
end},
LineHistory = {line_history,
case Data#state.save_history of
HistBool when HistBool =:= true; HistBool =:= false ->
HistBool;
_ ->
false
end},
Log = {log, Data#state.log},
Bin = {binary, case Data#state.read_type of
binary ->
true;
_ ->
false
end},
Uni = {encoding, case get_unicode_state(Data#state.driver) of
true -> unicode;
_ -> latin1
end},
case get_terminal_state(Data#state.driver) of
Terminal when is_map(Terminal) ->
Tty = {terminal, maps:get(stdout, Terminal)},
[Exp,Echo,LineHistory,Log,Bin,Uni,Tty|maps:to_list(Terminal)];
Error ->
Error
end.
%% Convert error code to make it look as before
err_func(io_lib, get_until, {_,F,_}) ->
F;
err_func(_, F, _) ->
F.
%% get_line(Chars, PromptBytes, Drv)
%% Get a line with eventual line editing.
%% Returns:
%% {done,LineChars,RestChars}
%% {more_data, Cont, Ls}
%% {blink, Cons, Ls}
-record(get_line_edlin_state, {history, encoding, expand_fun, expand_below,
search, search_quit_prompt, search_result}).
get_line_edlin(Chars, Pbs, undefined, Lines, Encoding,
#state{ driver = Drv, line_history = History,
expand_fun = ExpandFun, expand_below = ExpandBelow}) ->
{more_chars,Cont1,Rs} = case Lines of
[] -> edlin:start(Pbs);
_ -> edlin:start(Pbs, Lines)
end,
send_drv_reqs(Drv, Rs),
get_line_edlin(edlin:edit_line(Chars, Cont1), Drv, #get_line_edlin_state{
history = new_stack(History),
encoding = Encoding,
expand_fun = ExpandFun,
expand_below = ExpandBelow });
get_line_edlin(Chars, _Pbs, {EdlinCont, GetLineState}, _Lines, _Encoding,
#state{ driver = Drv }) ->
get_line_edlin(edlin:edit_line(cast(Chars, list), EdlinCont),
Drv, GetLineState).
get_line_edlin({done, Cont, Rest, Rs}, Drv, _State) ->
send_drv_reqs(Drv, Rs),
{done, Cont, Rest};
get_line_edlin({open_editor, _Cs, Cont, Rs}, Drv, State) ->
send_drv_reqs(Drv, Rs),
Buffer = edlin:current_line(Cont),
send_drv(Drv, {open_editor, Buffer}),
receive
{Drv, {editor_data, Cs1}} ->
send_drv_reqs(Drv, edlin:erase_line()),
{more_chars,NewCont,NewRs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, NewRs),
get_line_edlin(edlin:edit_line(Cs1, NewCont), Drv, State);
{Drv, not_supported} ->
get_line_edlin(edlin:edit_line(_Cs, Cont), Drv, State)
end;
get_line_edlin({format_expression, _Cs, {line, _, _, _} = Cont, Rs}, Drv, State) ->
send_drv_reqs(Drv, Rs),
Cs1 = format_expression(Cont, Drv),
send_drv_reqs(Drv, edlin:erase_line()),
{more_chars,NewCont,NewRs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, NewRs),
get_line_edlin(edlin:edit_line(Cs1, NewCont), Drv, State);
%% Move Up, Down in History: Ctrl+P, Ctrl+N
get_line_edlin({history_up,Cs,{_,_,_,Mode0}=Cont,Rs}, Drv, State) ->
send_drv_reqs(Drv, Rs),
case up_stack(save_line(State#get_line_edlin_state.history, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line_edlin(edlin:edit_line(Cs, Cont), Drv, State);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line()),
{more_chars,{A,B,C,_},Nrs} = edlin:start(edlin:prompt(Cont)),
Ncont = {A,B,C,Mode0},
send_drv_reqs(Drv, Nrs),
get_line_edlin(
edlin:edit_line1(
string:to_graphemes(
lists:sublist(Lcs, 1, length(Lcs)-1)),
Ncont),
Drv, State#get_line_edlin_state{ history = Ls })
end;
get_line_edlin({history_down,Cs,{_,_,_,Mode0}=Cont,Rs}, Drv, State) ->
send_drv_reqs(Drv, Rs),
case down_stack(save_line(State#get_line_edlin_state.history, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line_edlin(edlin:edit_line(Cs, Cont), Drv, State);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line()),
{more_chars,{A,B,C,_},Nrs} = edlin:start(edlin:prompt(Cont)),
Ncont = {A,B,C,Mode0},
send_drv_reqs(Drv, Nrs),
get_line_edlin(edlin:edit_line1(string:to_graphemes(lists:sublist(Lcs,
1,
length(Lcs)-1)),
Ncont),
Drv, State#get_line_edlin_state{ history = Ls })
end;
%% ^R = backward search, ^S = forward search.
%% Search is tricky to implement and does a lot of back-and-forth
%% work with edlin.erl (from stdlib). Edlin takes care of writing
%% and handling lines and escape characters to get out of search,
%% whereas this module does the actual searching and appending to lines.
%% Erlang's shell wasn't exactly meant to traverse the wall between
%% line and line stack, so we at least restrict it by introducing
%% new modes: search, search_quit, search_found. These are added to
%% the regular ones (none, meta_left_sq_bracket) and handle special
%% cases of history search.
get_line_edlin({search,Cs,Cont,Rs}, Drv, State) ->
send_drv_reqs(Drv, Rs),
%% drop current line, move to search mode. We store the current
%% prompt ('N>') and substitute it with the search prompt.
Pbs = prompt_bytes("\033[;1;4msearch:\033[0m ", State#get_line_edlin_state.encoding),
{more_chars,Ncont,_Nrs} = edlin:start(Pbs, {search,none}),
get_line_edlin(edlin:edit_line1(Cs, Ncont), Drv,
State#get_line_edlin_state{ search = new_search,
search_quit_prompt = Cont});
get_line_edlin({Help, Before, Cs0, Cont, Rs}, Drv, State)
when Help =:= help; Help =:= help_full ->
send_drv_reqs(Drv, Rs),
NLines = case Help of
help -> 7;
help_full -> 0
end,
{_,Word,_} = edlin:over_word(Before, [], 0),
{R,Docs} = case edlin_context:get_context(Before) of
{function, Mod} when Word =/= [] -> try
{ok, [{atom,_,Module}], _} = erl_scan:string(Mod),
{ok, [{atom,_,Word1}], _} = erl_scan:string(Word),
{function, c:h1(Module, Word1)}
catch _:_ ->
{ok, [{atom,_,Module1}], _} = erl_scan:string(Mod),
{module, c:h1(Module1)}
end;
{function, Mod} ->
{ok, [{atom,_,Module}], _} = erl_scan:string(Mod),
{module, c:h1(Module)};
{function, Mod, Fun, _Args, _Unfinished, _Nesting} ->
{ok, [{atom,_,Module}], _} = erl_scan:string(Mod),
{ok, [{atom,_,Function}], _} = erl_scan:string(Fun),
{function, c:h1(Module, Function)};
{term, _, {atom, Word1}}->
{ok, [{atom,_,Module}], _} = erl_scan:string(Word1),
{module, c:h1(Module)};
_ -> {error, {error, no_help}}
end,
case {R, Docs} of
{_, {error, _}} -> send_drv(Drv, beep);
{module, _} ->
Docs1 = " "++string:trim(lists:nthtail(3, Docs),both),
send_drv(Drv, {put_expand, unicode,
[unicode:characters_to_binary(Docs1)], NLines});
{function, _} ->
Docs1 = " "++string:trim(Docs,both),
send_drv(Drv, {put_expand, unicode,
[unicode:characters_to_binary(Docs1)], NLines})
end,
get_line_edlin(edlin:edit_line(Cs0, Cont), Drv, State);
get_line_edlin({Expand, Before, Cs0, Cont,Rs}, Drv, State = #get_line_edlin_state{ expand_fun = ExpandFun })
when Expand =:= expand; Expand =:= expand_full ->
send_drv_reqs(Drv, Rs),
{Found, CompleteChars, Matches} = ExpandFun(Before, []),
case Found of
no -> send_drv(Drv, beep);
_ -> ok
end,
{Width, _Height} = get_tty_geometry(Drv),
Cs1 = append(CompleteChars, Cs0, State#get_line_edlin_state.encoding),
MatchStr = case Matches of
[] -> [];
_ -> edlin_expand:format_matches(Matches, Width)
end,
Cs = case {Cs1, MatchStr} of
{_, []} -> Cs1;
{Cs1, _} when Cs1 =/= [] -> Cs1;
_ ->
NlMatchStr = unicode:characters_to_binary("\n"++MatchStr),
NLines = case Expand of
expand -> 7;
expand_full -> 0
end,
case State#get_line_edlin_state.expand_below of
true ->
send_drv(Drv, {put_expand, unicode, unicode:characters_to_binary(string:trim(MatchStr, trailing)), NLines}),