├── .gitignore ├── Cambios.txt ├── Example ├── project1.ico ├── project1.lpi ├── project1.lpr ├── project1.lps ├── project1.res ├── unit1.lfm └── unit1.pas ├── Example2 ├── project1.ico ├── project1.lpi ├── project1.lpr ├── project1.lps ├── project1.res ├── unit1.lfm └── unit1.pas ├── Example3 ├── project1.lpi ├── project1.lpr └── project1.lps ├── Example4 ├── project1.lpi ├── project1.lpr └── project1.lps ├── HelloWorld ├── project1.ico ├── project1.lpi ├── project1.lpr ├── project1.lps ├── project1.res ├── unit1.lfm └── unit1.pas ├── LICENSE ├── README.md ├── README_es.md ├── TermVT.pas ├── UnTerminal.pas └── screen1.png /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | TTerm/TTerm.lpi 3 | TTerm/TTerm.lps 4 | TTerm/TTerm.res 5 | -------------------------------------------------------------------------------- /Cambios.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/Cambios.txt -------------------------------------------------------------------------------- /Example/project1.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/Example/project1.ico -------------------------------------------------------------------------------- /Example/project1.lpi: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | <ResourceType Value="res"/> 13 | <UseXPManifest Value="True"/> 14 | <Icon Value="0"/> 15 | </General> 16 | <i18n> 17 | <EnableI18N LFM="False"/> 18 | </i18n> 19 | <BuildModes Count="1"> 20 | <Item1 Name="Default" Default="True"/> 21 | </BuildModes> 22 | <PublishOptions> 23 | <Version Value="2"/> 24 | </PublishOptions> 25 | <RunParams> 26 | <FormatVersion Value="2"/> 27 | <Modes Count="1"> 28 | <Mode0 Name="default"/> 29 | </Modes> 30 | </RunParams> 31 | <RequiredPackages Count="1"> 32 | <Item1> 33 | <PackageName Value="LCL"/> 34 | </Item1> 35 | </RequiredPackages> 36 | <Units Count="2"> 37 | <Unit0> 38 | <Filename Value="project1.lpr"/> 39 | <IsPartOfProject Value="True"/> 40 | </Unit0> 41 | <Unit1> 42 | <Filename Value="unit1.pas"/> 43 | <IsPartOfProject Value="True"/> 44 | <ComponentName Value="Form1"/> 45 | <HasResources Value="True"/> 46 | <ResourceBaseClass Value="Form"/> 47 | <UnitName Value="Unit1"/> 48 | </Unit1> 49 | </Units> 50 | </ProjectOptions> 51 | <CompilerOptions> 52 | <Version Value="11"/> 53 | <PathDelim Value="\"/> 54 | <Target> 55 | <Filename Value="project1"/> 56 | </Target> 57 | <SearchPaths> 58 | <IncludeFiles Value="$(ProjOutDir)"/> 59 | <OtherUnitFiles Value=".."/> 60 | <UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/> 61 | </SearchPaths> 62 | <Linking> 63 | <Debugging> 64 | <DebugInfoType Value="dsDwarf3"/> 65 | </Debugging> 66 | <Options> 67 | <Win32> 68 | <GraphicApplication Value="True"/> 69 | </Win32> 70 | </Options> 71 | </Linking> 72 | </CompilerOptions> 73 | <Debugging> 74 | <Exceptions Count="3"> 75 | <Item1> 76 | <Name Value="EAbort"/> 77 | </Item1> 78 | <Item2> 79 | <Name Value="ECodetoolError"/> 80 | </Item2> 81 | <Item3> 82 | <Name Value="EFOpenError"/> 83 | </Item3> 84 | </Exceptions> 85 | </Debugging> 86 | </CONFIG> 87 | -------------------------------------------------------------------------------- /Example/project1.lpr: -------------------------------------------------------------------------------- 1 | program project1; 2 | 3 | {$mode objfpc}{$H+} 4 | 5 | uses 6 | {$IFDEF UNIX}{$IFDEF UseCThreads} 7 | cthreads, 8 | {$ENDIF}{$ENDIF} 9 | Interfaces, // this includes the LCL widgetset 10 | Forms, Unit1; 11 | 12 | {$R *.res} 13 | 14 | begin 15 | RequireDerivedFormResource := True; 16 | Application.Initialize; 17 | Application.CreateForm(TForm1, Form1); 18 | Application.Run; 19 | end. 20 | 21 | -------------------------------------------------------------------------------- /Example/project1.lps: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectSession> 4 | <PathDelim Value="\"/> 5 | <Version Value="12"/> 6 | <BuildModes Active="Default"/> 7 | <Units Count="15"> 8 | <Unit0> 9 | <Filename Value="project1.lpr"/> 10 | <IsPartOfProject Value="True"/> 11 | <CursorPos Y="20"/> 12 | <UsageCount Value="46"/> 13 | </Unit0> 14 | <Unit1> 15 | <Filename Value="unit1.pas"/> 16 | <IsPartOfProject Value="True"/> 17 | <ComponentName Value="Form1"/> 18 | <HasResources Value="True"/> 19 | <ResourceBaseClass Value="Form"/> 20 | <UnitName Value="Unit1"/> 21 | <TopLine Value="65"/> 22 | <CursorPos X="23" Y="83"/> 23 | <UsageCount Value="46"/> 24 | <Loaded Value="True"/> 25 | <LoadedDesigner Value="True"/> 26 | </Unit1> 27 | <Unit2> 28 | <Filename Value="termVT.pas"/> 29 | <UsageCount Value="44"/> 30 | </Unit2> 31 | <Unit3> 32 | <Filename Value="unterminal.pas"/> 33 | <UnitName Value="UnTerminal"/> 34 | <TopLine Value="233"/> 35 | <CursorPos X="39" Y="241"/> 36 | <UsageCount Value="44"/> 37 | </Unit3> 38 | <Unit4> 39 | <Filename Value="..\UnTerminal.pas"/> 40 | <IsVisibleTab Value="True"/> 41 | <EditorIndex Value="1"/> 42 | <TopLine Value="513"/> 43 | <CursorPos X="21" Y="526"/> 44 | <ExtraEditorCount Value="1"/> 45 | <ExtraEditor1> 46 | <EditorIndex Value="-1"/> 47 | <WindowIndex Value="-1"/> 48 | <TopLine Value="114"/> 49 | <CursorPos Y="133"/> 50 | </ExtraEditor1> 51 | <UsageCount Value="20"/> 52 | <Loaded Value="True"/> 53 | </Unit4> 54 | <Unit5> 55 | <Filename Value="C:\lazarus\lcl\include\control.inc"/> 56 | <TopLine Value="3242"/> 57 | <CursorPos Y="3260"/> 58 | <UsageCount Value="9"/> 59 | </Unit5> 60 | <Unit6> 61 | <Filename Value="..\TermVT.pas"/> 62 | <EditorIndex Value="-1"/> 63 | <UsageCount Value="14"/> 64 | </Unit6> 65 | <Unit7> 66 | <Filename Value="C:\lazarus\fpc\3.0.0\source\packages\fcl-process\src\process.pp"/> 67 | <EditorIndex Value="-1"/> 68 | <TopLine Value="32"/> 69 | <CursorPos X="3" Y="50"/> 70 | <UsageCount Value="11"/> 71 | </Unit7> 72 | <Unit8> 73 | <Filename Value="C:\lazarus\fpc\3.0.0\source\packages\fcl-process\src\pipes.pp"/> 74 | <UnitName Value="Pipes"/> 75 | <EditorIndex Value="-1"/> 76 | <UsageCount Value="11"/> 77 | </Unit8> 78 | <Unit9> 79 | <Filename Value="C:\lazarus\lcl\comctrls.pp"/> 80 | <UnitName Value="ComCtrls"/> 81 | <EditorIndex Value="-1"/> 82 | <CursorPos X="14" Y="24"/> 83 | <UsageCount Value="10"/> 84 | </Unit9> 85 | <Unit10> 86 | <Filename Value="C:\lazarus\lcl\graphics.pp"/> 87 | <UnitName Value="Graphics"/> 88 | <EditorIndex Value="-1"/> 89 | <TopLine Value="1028"/> 90 | <CursorPos X="3" Y="1045"/> 91 | <UsageCount Value="10"/> 92 | </Unit10> 93 | <Unit11> 94 | <Filename Value="C:\lazarus\fpc\3.0.0\source\packages\rtl-objpas\src\inc\strutils.pp"/> 95 | <EditorIndex Value="-1"/> 96 | <TopLine Value="76"/> 97 | <CursorPos X="10" Y="94"/> 98 | <UsageCount Value="10"/> 99 | </Unit11> 100 | <Unit12> 101 | <Filename Value="C:\lazarus\lcl\lcltype.pp"/> 102 | <UnitName Value="LCLType"/> 103 | <EditorIndex Value="-1"/> 104 | <TopLine Value="405"/> 105 | <CursorPos X="3" Y="423"/> 106 | <UsageCount Value="10"/> 107 | </Unit12> 108 | <Unit13> 109 | <Filename Value="C:\lazarus\fpc\3.2.2\source\rtl\objpas\classes\classesh.inc"/> 110 | <EditorIndex Value="-1"/> 111 | <TopLine Value="960"/> 112 | <CursorPos X="45" Y="976"/> 113 | <UsageCount Value="11"/> 114 | </Unit13> 115 | <Unit14> 116 | <Filename Value="C:\lazarus\fpc\3.2.2\source\rtl\objpas\classes\streams.inc"/> 117 | <EditorIndex Value="-1"/> 118 | <TopLine Value="52"/> 119 | <CursorPos X="7" Y="56"/> 120 | <UsageCount Value="11"/> 121 | </Unit14> 122 | </Units> 123 | <JumpHistory Count="26" HistoryIndex="25"> 124 | <Position1> 125 | <Filename Value="..\UnTerminal.pas"/> 126 | <Caret Line="412" Column="17" TopLine="170"/> 127 | </Position1> 128 | <Position2> 129 | <Filename Value="..\UnTerminal.pas"/> 130 | <Caret Line="919" Column="14" TopLine="737"/> 131 | </Position2> 132 | <Position3> 133 | <Filename Value="..\UnTerminal.pas"/> 134 | <Caret Line="412" Column="10" TopLine="183"/> 135 | </Position3> 136 | <Position4> 137 | <Filename Value="..\UnTerminal.pas"/> 138 | <Caret Line="146" Column="14" TopLine="129"/> 139 | </Position4> 140 | <Position5> 141 | <Filename Value="..\UnTerminal.pas"/> 142 | <Caret Line="412" Column="17" TopLine="170"/> 143 | </Position5> 144 | <Position6> 145 | <Filename Value="..\UnTerminal.pas"/> 146 | <Caret Line="602" Column="16" TopLine="596"/> 147 | </Position6> 148 | <Position7> 149 | <Filename Value="..\UnTerminal.pas"/> 150 | <Caret Line="806" Column="50" TopLine="225"/> 151 | </Position7> 152 | <Position8> 153 | <Filename Value="..\UnTerminal.pas"/> 154 | <Caret Line="49"/> 155 | </Position8> 156 | <Position9> 157 | <Filename Value="..\UnTerminal.pas"/> 158 | <Caret Line="100" Column="26" TopLine="61"/> 159 | </Position9> 160 | <Position10> 161 | <Filename Value="..\UnTerminal.pas"/> 162 | <Caret Line="100" Column="26" TopLine="61"/> 163 | </Position10> 164 | <Position11> 165 | <Filename Value="..\UnTerminal.pas"/> 166 | <Caret Line="122" Column="29" TopLine="83"/> 167 | </Position11> 168 | <Position12> 169 | <Filename Value="..\UnTerminal.pas"/> 170 | <Caret Line="77" TopLine="48"/> 171 | </Position12> 172 | <Position13> 173 | <Filename Value="..\UnTerminal.pas"/> 174 | <Caret Line="147" Column="24" TopLine="118"/> 175 | </Position13> 176 | <Position14> 177 | <Filename Value="..\UnTerminal.pas"/> 178 | <Caret Line="34" Column="10"/> 179 | </Position14> 180 | <Position15> 181 | <Filename Value="..\UnTerminal.pas"/> 182 | <Caret Line="77" TopLine="44"/> 183 | </Position15> 184 | <Position16> 185 | <Filename Value="..\UnTerminal.pas"/> 186 | <Caret Line="175" Column="37" TopLine="148"/> 187 | </Position16> 188 | <Position17> 189 | <Filename Value="..\UnTerminal.pas"/> 190 | <Caret Line="194" TopLine="168"/> 191 | </Position17> 192 | <Position18> 193 | <Filename Value="..\UnTerminal.pas"/> 194 | <Caret Line="467" Column="16" TopLine="187"/> 195 | </Position18> 196 | <Position19> 197 | <Filename Value="..\UnTerminal.pas"/> 198 | <Caret Line="677" Column="8" TopLine="270"/> 199 | </Position19> 200 | <Position20> 201 | <Filename Value="unit1.pas"/> 202 | <Caret Line="45" Column="48"/> 203 | </Position20> 204 | <Position21> 205 | <Filename Value="..\UnTerminal.pas"/> 206 | <Caret Line="37" Column="30" TopLine="23"/> 207 | </Position21> 208 | <Position22> 209 | <Filename Value="unit1.pas"/> 210 | <Caret Line="32" Column="31" TopLine="14"/> 211 | </Position22> 212 | <Position23> 213 | <Filename Value="unit1.pas"/> 214 | <Caret Line="83" Column="23" TopLine="65"/> 215 | </Position23> 216 | <Position24> 217 | <Filename Value="..\UnTerminal.pas"/> 218 | <Caret Line="531" Column="21" TopLine="513"/> 219 | </Position24> 220 | <Position25> 221 | <Filename Value="..\UnTerminal.pas"/> 222 | <Caret Line="532" Column="19" TopLine="513"/> 223 | </Position25> 224 | <Position26> 225 | <Filename Value="..\UnTerminal.pas"/> 226 | <Caret Line="531" Column="12" TopLine="513"/> 227 | </Position26> 228 | </JumpHistory> 229 | <RunParams> 230 | <FormatVersion Value="2"/> 231 | <Modes ActiveMode="default"/> 232 | </RunParams> 233 | </ProjectSession> 234 | </CONFIG> 235 | -------------------------------------------------------------------------------- /Example/project1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/Example/project1.res -------------------------------------------------------------------------------- /Example/unit1.lfm: -------------------------------------------------------------------------------- 1 | object Form1: TForm1 2 | Left = 248 3 | Height = 396 4 | Top = 180 5 | Width = 457 6 | Caption = 'Form1' 7 | ClientHeight = 396 8 | ClientWidth = 457 9 | OnCreate = FormCreate 10 | OnDestroy = FormDestroy 11 | LCLVersion = '1.8.4.0' 12 | object Memo1: TMemo 13 | Left = 8 14 | Height = 248 15 | Top = 112 16 | Width = 440 17 | ScrollBars = ssAutoBoth 18 | TabOrder = 0 19 | end 20 | object label1: TLabel 21 | Left = 10 22 | Height = 17 23 | Top = 10 24 | Width = 57 25 | Caption = 'Process:' 26 | ParentColor = False 27 | end 28 | object txtProcess: TEdit 29 | Left = 64 30 | Height = 27 31 | Top = 10 32 | Width = 216 33 | TabOrder = 1 34 | Text = 'CMD' 35 | end 36 | object Button1: TButton 37 | Left = 288 38 | Height = 25 39 | Top = 8 40 | Width = 75 41 | Caption = 'S&tart' 42 | OnClick = Button1Click 43 | TabOrder = 2 44 | end 45 | object Button2: TButton 46 | Left = 373 47 | Height = 25 48 | Top = 8 49 | Width = 75 50 | Caption = 'St&op' 51 | OnClick = Button2Click 52 | TabOrder = 3 53 | end 54 | object StatusBar1: TStatusBar 55 | Left = 0 56 | Height = 21 57 | Top = 375 58 | Width = 457 59 | Panels = < 60 | item 61 | Width = 50 62 | end> 63 | SimplePanel = False 64 | end 65 | object label2: TLabel 66 | Left = 8 67 | Height = 17 68 | Top = 40 69 | Width = 74 70 | Caption = 'Command:' 71 | ParentColor = False 72 | end 73 | object txtCommand: TEdit 74 | Left = 72 75 | Height = 27 76 | Top = 40 77 | Width = 208 78 | TabOrder = 5 79 | Text = 'dir' 80 | end 81 | object Button3: TButton 82 | Left = 288 83 | Height = 25 84 | Top = 38 85 | Width = 75 86 | Caption = '&Send' 87 | OnClick = Button3Click 88 | TabOrder = 6 89 | end 90 | object Button4: TButton 91 | Left = 8 92 | Height = 25 93 | Top = 72 94 | Width = 104 95 | Caption = 'Detect Prompt' 96 | OnClick = Button4Click 97 | TabOrder = 7 98 | end 99 | end 100 | -------------------------------------------------------------------------------- /Example/unit1.pas: -------------------------------------------------------------------------------- 1 | {Sample of code implementing a VT100 Terminal, using the unit "UnTerminal".} 2 | unit Unit1; 3 | {$mode objfpc}{$H+} 4 | 5 | interface 6 | uses 7 | Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, 8 | ExtCtrls, ComCtrls, UnTerminal, TermVT; 9 | 10 | type 11 | 12 | { TForm1 } 13 | 14 | TForm1 = class(TForm) 15 | Button1: TButton; 16 | Button2: TButton; 17 | Button3: TButton; 18 | Button4: TButton; 19 | label2: TLabel; 20 | StatusBar1: TStatusBar; 21 | txtProcess: TEdit; 22 | label1: TLabel; 23 | Memo1: TMemo; 24 | txtCommand: TEdit; 25 | procedure Button1Click(Sender: TObject); 26 | procedure Button2Click(Sender: TObject); 27 | procedure Button3Click(Sender: TObject); 28 | procedure Button4Click(Sender: TObject); 29 | procedure FormCreate(Sender: TObject); 30 | procedure FormDestroy(Sender: TObject); 31 | procedure procAddLine(HeightScr: integer); 32 | procedure procChangeState(State: string; pFinal: TPoint); 33 | procedure procInitScreen(const grilla: TtsGrid; fIni, fFin: integer); 34 | procedure procRefreshLine(const grilla: TtsGrid; fIni, HeightScr: integer); 35 | procedure procRefreshLines(const grilla: TtsGrid; fIni, fFin, 36 | HeightScr: integer); 37 | private 38 | { private declarations } 39 | public 40 | { public declarations } 41 | end; 42 | 43 | var 44 | Form1: TForm1; 45 | proc: TConsoleProc; 46 | 47 | implementation 48 | 49 | {$R *.lfm} 50 | 51 | { TForm1 } 52 | 53 | procedure TForm1.Button1Click(Sender: TObject); 54 | begin 55 | proc.Open(txtProcess.Text,''); 56 | end; 57 | 58 | procedure TForm1.Button2Click(Sender: TObject); 59 | begin 60 | proc.Close; 61 | end; 62 | 63 | procedure TForm1.Button3Click(Sender: TObject); 64 | begin 65 | proc.SendLn(txtCommand.Text); 66 | end; 67 | 68 | procedure TForm1.Button4Click(Sender: TObject); 69 | begin 70 | proc.AutoConfigPrompt; 71 | end; 72 | 73 | procedure TForm1.FormCreate(Sender: TObject); 74 | begin 75 | proc:= TConsoleProc.Create(nil); 76 | proc.OnInitScreen :=@procInitScreen; 77 | proc.OnRefreshLine:=@procRefreshLine; 78 | proc.OnRefreshLines:=@procRefreshLines; 79 | proc.OnAddLine:=@procAddLine; 80 | proc.OnChangeState:=@procChangeState; 81 | {$ifdef linux} 82 | txtProcess.Text:= 'bash'; 83 | txtCommand.Text := 'ls'; 84 | proc.LineDelimSend := LDS_LF; 85 | {$endif} 86 | end; 87 | 88 | procedure TForm1.FormDestroy(Sender: TObject); 89 | begin 90 | proc.Destroy; 91 | end; 92 | 93 | procedure TForm1.procChangeState(State: string; pFinal: TPoint); 94 | begin 95 | StatusBar1.Panels[0].Text:=State; 96 | end; 97 | 98 | procedure TForm1.procAddLine(HeightScr: integer); 99 | begin 100 | Memo1.Lines.Add(''); 101 | end; 102 | 103 | procedure TForm1.procInitScreen(const grilla: TtsGrid; fIni, fFin: integer); 104 | var 105 | i: Integer; 106 | begin 107 | for i:=fIni to fFin do Memo1.Lines.Add(grilla[i]); 108 | end; 109 | 110 | procedure TForm1.procRefreshLine(const grilla: TtsGrid; fIni, HeightScr: integer 111 | ); 112 | var 113 | yvt: Integer; 114 | begin 115 | yvt := Memo1.Lines.Count-HeightScr-1; 116 | Memo1.Lines[yvt+fIni] := grilla[fIni]; 117 | end; 118 | 119 | procedure TForm1.procRefreshLines(const grilla: TtsGrid; fIni, fFin, 120 | HeightScr: integer); 121 | var 122 | yvt: Integer; 123 | f: Integer; 124 | begin 125 | yvt := Memo1.Lines.Count-HeightScr-1; //Calculate equivalent row to start of VT100 screen 126 | for f:=fIni to fFin do Memo1.Lines[yvt+ f] := grilla[f]; 127 | end; 128 | 129 | end. 130 | 131 | -------------------------------------------------------------------------------- /Example2/project1.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/Example2/project1.ico -------------------------------------------------------------------------------- /Example2/project1.lpi: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectOptions> 4 | <Version Value="12"/> 5 | <PathDelim Value="\"/> 6 | <General> 7 | <Flags> 8 | <CompatibilityMode Value="True"/> 9 | </Flags> 10 | <SessionStorage Value="InProjectDir"/> 11 | <Title Value="project1"/> 12 | <ResourceType Value="res"/> 13 | <UseXPManifest Value="True"/> 14 | <Icon Value="0"/> 15 | </General> 16 | <i18n> 17 | <EnableI18N LFM="False"/> 18 | </i18n> 19 | <BuildModes Count="1"> 20 | <Item1 Name="Default" Default="True"/> 21 | </BuildModes> 22 | <PublishOptions> 23 | <Version Value="2"/> 24 | </PublishOptions> 25 | <RunParams> 26 | <FormatVersion Value="2"/> 27 | <Modes Count="1"> 28 | <Mode0 Name="default"/> 29 | </Modes> 30 | </RunParams> 31 | <RequiredPackages Count="1"> 32 | <Item1> 33 | <PackageName Value="LCL"/> 34 | </Item1> 35 | </RequiredPackages> 36 | <Units Count="2"> 37 | <Unit0> 38 | <Filename Value="project1.lpr"/> 39 | <IsPartOfProject Value="True"/> 40 | </Unit0> 41 | <Unit1> 42 | <Filename Value="unit1.pas"/> 43 | <IsPartOfProject Value="True"/> 44 | <ComponentName Value="Form1"/> 45 | <HasResources Value="True"/> 46 | <ResourceBaseClass Value="Form"/> 47 | <UnitName Value="Unit1"/> 48 | </Unit1> 49 | </Units> 50 | </ProjectOptions> 51 | <CompilerOptions> 52 | <Version Value="11"/> 53 | <PathDelim Value="\"/> 54 | <Target> 55 | <Filename Value="project1"/> 56 | </Target> 57 | <SearchPaths> 58 | <IncludeFiles Value="$(ProjOutDir)"/> 59 | <OtherUnitFiles Value=".."/> 60 | <UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/> 61 | </SearchPaths> 62 | <Linking> 63 | <Debugging> 64 | <DebugInfoType Value="dsDwarf3"/> 65 | </Debugging> 66 | <Options> 67 | <Win32> 68 | <GraphicApplication Value="True"/> 69 | </Win32> 70 | </Options> 71 | </Linking> 72 | </CompilerOptions> 73 | <Debugging> 74 | <Exceptions Count="3"> 75 | <Item1> 76 | <Name Value="EAbort"/> 77 | </Item1> 78 | <Item2> 79 | <Name Value="ECodetoolError"/> 80 | </Item2> 81 | <Item3> 82 | <Name Value="EFOpenError"/> 83 | </Item3> 84 | </Exceptions> 85 | </Debugging> 86 | </CONFIG> 87 | -------------------------------------------------------------------------------- /Example2/project1.lpr: -------------------------------------------------------------------------------- 1 | program project1; 2 | 3 | {$mode objfpc}{$H+} 4 | 5 | uses 6 | {$IFDEF UNIX}{$IFDEF UseCThreads} 7 | cthreads, 8 | {$ENDIF}{$ENDIF} 9 | Interfaces, // this includes the LCL widgetset 10 | Forms, Unit1; 11 | 12 | {$R *.res} 13 | 14 | begin 15 | RequireDerivedFormResource := True; 16 | Application.Initialize; 17 | Application.CreateForm(TForm1, Form1); 18 | Application.Run; 19 | end. 20 | 21 | -------------------------------------------------------------------------------- /Example2/project1.lps: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectSession> 4 | <PathDelim Value="\"/> 5 | <Version Value="12"/> 6 | <BuildModes Active="Default"/> 7 | <Units Count="8"> 8 | <Unit0> 9 | <Filename Value="project1.lpr"/> 10 | <IsPartOfProject Value="True"/> 11 | <CursorPos Y="20"/> 12 | <UsageCount Value="33"/> 13 | </Unit0> 14 | <Unit1> 15 | <Filename Value="unit1.pas"/> 16 | <IsPartOfProject Value="True"/> 17 | <ComponentName Value="Form1"/> 18 | <HasResources Value="True"/> 19 | <ResourceBaseClass Value="Form"/> 20 | <UnitName Value="Unit1"/> 21 | <CursorPos X="26" Y="9"/> 22 | <UsageCount Value="33"/> 23 | <Loaded Value="True"/> 24 | <LoadedDesigner Value="True"/> 25 | </Unit1> 26 | <Unit2> 27 | <Filename Value="termVT.pas"/> 28 | <UsageCount Value="33"/> 29 | </Unit2> 30 | <Unit3> 31 | <Filename Value="unterminal.pas"/> 32 | <UnitName Value="UnTerminal"/> 33 | <TopLine Value="233"/> 34 | <CursorPos X="39" Y="241"/> 35 | <UsageCount Value="33"/> 36 | </Unit3> 37 | <Unit4> 38 | <Filename Value="..\UnTerminal.pas"/> 39 | <IsVisibleTab Value="True"/> 40 | <EditorIndex Value="1"/> 41 | <TopLine Value="64"/> 42 | <CursorPos X="17" Y="68"/> 43 | <UsageCount Value="15"/> 44 | <Loaded Value="True"/> 45 | </Unit4> 46 | <Unit5> 47 | <Filename Value="C:\lazarus\lcl\include\control.inc"/> 48 | <TopLine Value="3242"/> 49 | <CursorPos Y="3260"/> 50 | <UsageCount Value="10"/> 51 | </Unit5> 52 | <Unit6> 53 | <Filename Value="..\TermVT.pas"/> 54 | <EditorIndex Value="-1"/> 55 | <TopLine Value="286"/> 56 | <CursorPos X="22" Y="290"/> 57 | <UsageCount Value="10"/> 58 | </Unit6> 59 | <Unit7> 60 | <Filename Value="C:\lazarus\fpc\3.2.0\source\packages\chm\src\chmreader.pas"/> 61 | <EditorIndex Value="-1"/> 62 | <TopLine Value="70"/> 63 | <CursorPos X="12" Y="81"/> 64 | <UsageCount Value="10"/> 65 | </Unit7> 66 | </Units> 67 | <JumpHistory Count="10" HistoryIndex="9"> 68 | <Position1> 69 | <Filename Value="unit1.pas"/> 70 | <Caret Line="76" Column="14" TopLine="56"/> 71 | </Position1> 72 | <Position2> 73 | <Filename Value="unit1.pas"/> 74 | <Caret Line="103" Column="40" TopLine="76"/> 75 | </Position2> 76 | <Position3> 77 | <Filename Value="unit1.pas"/> 78 | <Caret Line="32" Column="37" TopLine="13"/> 79 | </Position3> 80 | <Position4> 81 | <Filename Value="unit1.pas"/> 82 | <Caret Line="69" Column="5" TopLine="50"/> 83 | </Position4> 84 | <Position5> 85 | <Filename Value="unit1.pas"/> 86 | <Caret Line="74" Column="9" TopLine="56"/> 87 | </Position5> 88 | <Position6> 89 | <Filename Value="unit1.pas"/> 90 | <Caret Line="73" Column="7" TopLine="56"/> 91 | </Position6> 92 | <Position7> 93 | <Filename Value="unit1.pas"/> 94 | </Position7> 95 | <Position8> 96 | <Filename Value="unit1.pas"/> 97 | <Caret Line="79" Column="29" TopLine="65"/> 98 | </Position8> 99 | <Position9> 100 | <Filename Value="unit1.pas"/> 101 | <Caret Line="84" Column="54" TopLine="83"/> 102 | </Position9> 103 | <Position10> 104 | <Filename Value="unit1.pas"/> 105 | <Caret Line="9" Column="26"/> 106 | </Position10> 107 | </JumpHistory> 108 | <RunParams> 109 | <FormatVersion Value="2"/> 110 | <Modes ActiveMode="default"/> 111 | </RunParams> 112 | </ProjectSession> 113 | </CONFIG> 114 | -------------------------------------------------------------------------------- /Example2/project1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/Example2/project1.res -------------------------------------------------------------------------------- /Example2/unit1.lfm: -------------------------------------------------------------------------------- 1 | object Form1: TForm1 2 | Left = 248 3 | Height = 396 4 | Top = 180 5 | Width = 457 6 | Caption = 'Form1' 7 | ClientHeight = 396 8 | ClientWidth = 457 9 | OnCreate = FormCreate 10 | OnDestroy = FormDestroy 11 | LCLVersion = '1.8.4.0' 12 | object Memo1: TMemo 13 | Left = 8 14 | Height = 248 15 | Top = 112 16 | Width = 440 17 | ScrollBars = ssAutoBoth 18 | TabOrder = 0 19 | end 20 | object label1: TLabel 21 | Left = 10 22 | Height = 17 23 | Top = 10 24 | Width = 57 25 | Caption = 'Process:' 26 | ParentColor = False 27 | end 28 | object txtProcess: TEdit 29 | Left = 64 30 | Height = 27 31 | Top = 10 32 | Width = 216 33 | TabOrder = 1 34 | Text = 'CMD' 35 | end 36 | object Button1: TButton 37 | Left = 288 38 | Height = 25 39 | Top = 8 40 | Width = 75 41 | Caption = 'S&tart' 42 | OnClick = Button1Click 43 | TabOrder = 2 44 | end 45 | object Button2: TButton 46 | Left = 373 47 | Height = 25 48 | Top = 8 49 | Width = 75 50 | Caption = 'St&op' 51 | OnClick = Button2Click 52 | TabOrder = 3 53 | end 54 | object StatusBar1: TStatusBar 55 | Left = 0 56 | Height = 21 57 | Top = 375 58 | Width = 457 59 | Panels = < 60 | item 61 | Width = 50 62 | end> 63 | SimplePanel = False 64 | end 65 | object label2: TLabel 66 | Left = 8 67 | Height = 17 68 | Top = 40 69 | Width = 74 70 | Caption = 'Command:' 71 | ParentColor = False 72 | end 73 | object txtCommand: TEdit 74 | Left = 72 75 | Height = 27 76 | Top = 40 77 | Width = 208 78 | TabOrder = 5 79 | Text = 'dir' 80 | end 81 | object Button3: TButton 82 | Left = 288 83 | Height = 25 84 | Top = 38 85 | Width = 75 86 | Caption = '&Send' 87 | OnClick = Button3Click 88 | TabOrder = 6 89 | end 90 | object Button4: TButton 91 | Left = 8 92 | Height = 25 93 | Top = 72 94 | Width = 104 95 | Caption = 'Detect Prompt' 96 | OnClick = Button4Click 97 | TabOrder = 7 98 | end 99 | end 100 | -------------------------------------------------------------------------------- /Example2/unit1.pas: -------------------------------------------------------------------------------- 1 | {Sample of code implementing a Terminal, using the unit "UnTerminal". 2 | The output is captured using the Line by Line detection} 3 | unit Unit1; 4 | {$mode objfpc}{$H+} 5 | 6 | interface 7 | uses 8 | Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, 9 | ExtCtrls, ComCtrls, UnTerminal; 10 | 11 | type 12 | 13 | { TForm1 } 14 | 15 | TForm1 = class(TForm) 16 | Button1: TButton; 17 | Button2: TButton; 18 | Button3: TButton; 19 | Button4: TButton; 20 | label2: TLabel; 21 | StatusBar1: TStatusBar; 22 | txtProcess: TEdit; 23 | label1: TLabel; 24 | Memo1: TMemo; 25 | txtCommand: TEdit; 26 | procedure Button1Click(Sender: TObject); 27 | procedure Button2Click(Sender: TObject); 28 | procedure Button3Click(Sender: TObject); 29 | procedure Button4Click(Sender: TObject); 30 | procedure FormCreate(Sender: TObject); 31 | procedure FormDestroy(Sender: TObject); 32 | procedure procChangeState(State: string; pFinal: TPoint); 33 | procedure procLineCompleted(const lin: string); 34 | procedure procReadData(nDat: integer; const lastLin: string); 35 | private 36 | { private declarations } 37 | public 38 | LinPartial: boolean; 39 | end; 40 | 41 | var 42 | Form1: TForm1; 43 | proc: TConsoleProc; 44 | 45 | implementation 46 | 47 | {$R *.lfm} 48 | 49 | { TForm1 } 50 | 51 | procedure TForm1.Button1Click(Sender: TObject); 52 | begin 53 | proc.Open(txtProcess.Text,''); 54 | end; 55 | 56 | procedure TForm1.Button2Click(Sender: TObject); 57 | begin 58 | proc.Close; 59 | end; 60 | 61 | procedure TForm1.Button3Click(Sender: TObject); 62 | begin 63 | proc.SendLn(txtCommand.Text); 64 | end; 65 | 66 | procedure TForm1.Button4Click(Sender: TObject); 67 | begin 68 | proc.AutoConfigPrompt; 69 | end; 70 | 71 | procedure TForm1.FormCreate(Sender: TObject); 72 | begin 73 | proc:= TConsoleProc.Create(nil); 74 | proc.LineDelimSend := LDS_CRLF; 75 | proc.OnLineCompleted:=@procLineCompleted; 76 | proc.OnReadData:=@procReadData; 77 | proc.OnChangeState:=@procChangeState; 78 | {$ifdef linux} 79 | txtProcess.Text:= 'bash'; 80 | txtCommand.Text := 'ls'; 81 | proc.LineDelimSend := LDS_LF; 82 | {$endif} 83 | end; 84 | 85 | procedure TForm1.FormDestroy(Sender: TObject); 86 | begin 87 | proc.Destroy; 88 | end; 89 | 90 | procedure TForm1.procChangeState(State: string; pFinal: TPoint); 91 | begin 92 | StatusBar1.Panels[0].Text:=State; 93 | end; 94 | 95 | procedure TForm1.procLineCompleted(const lin: string); 96 | begin 97 | if LinPartial then begin 98 | //Estamos en la línea del prompt 99 | Memo1.Lines[Memo1.Lines.Count-1] := lin; //reemplaza última línea 100 | LinPartial := false; 101 | end else begin //caso común 102 | Memo1.Lines.Add(lin); 103 | end; 104 | end; 105 | 106 | procedure TForm1.procReadData(nDat: integer; const lastLin: string); 107 | begin 108 | LinPartial := true; //marca bandera 109 | Memo1.Lines.Add(lastLin); //agrega la línea que contiene al prompt 110 | end; 111 | 112 | 113 | end. 114 | 115 | -------------------------------------------------------------------------------- /Example3/project1.lpi: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectOptions> 4 | <Version Value="12"/> 5 | <PathDelim Value="\"/> 6 | <General> 7 | <Flags> 8 | <MainUnitHasCreateFormStatements Value="False"/> 9 | <MainUnitHasTitleStatement Value="False"/> 10 | <MainUnitHasScaledStatement Value="False"/> 11 | <CompatibilityMode Value="True"/> 12 | </Flags> 13 | <SessionStorage Value="InProjectDir"/> 14 | <Title Value="project1"/> 15 | <UseAppBundle Value="False"/> 16 | <ResourceType Value="res"/> 17 | </General> 18 | <BuildModes Count="1"> 19 | <Item1 Name="Default" Default="True"/> 20 | </BuildModes> 21 | <PublishOptions> 22 | <Version Value="2"/> 23 | <UseFileFilters Value="True"/> 24 | </PublishOptions> 25 | <RunParams> 26 | <FormatVersion Value="2"/> 27 | </RunParams> 28 | <RequiredPackages Count="1"> 29 | <Item1> 30 | <PackageName Value="LCL"/> 31 | </Item1> 32 | </RequiredPackages> 33 | <Units Count="1"> 34 | <Unit0> 35 | <Filename Value="project1.lpr"/> 36 | <IsPartOfProject Value="True"/> 37 | </Unit0> 38 | </Units> 39 | </ProjectOptions> 40 | <CompilerOptions> 41 | <Version Value="11"/> 42 | <PathDelim Value="\"/> 43 | <Target> 44 | <Filename Value="project1"/> 45 | </Target> 46 | <SearchPaths> 47 | <IncludeFiles Value="$(ProjOutDir)"/> 48 | <OtherUnitFiles Value=".."/> 49 | <UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/> 50 | </SearchPaths> 51 | </CompilerOptions> 52 | <Debugging> 53 | <Exceptions Count="3"> 54 | <Item1> 55 | <Name Value="EAbort"/> 56 | </Item1> 57 | <Item2> 58 | <Name Value="ECodetoolError"/> 59 | </Item2> 60 | <Item3> 61 | <Name Value="EFOpenError"/> 62 | </Item3> 63 | </Exceptions> 64 | </Debugging> 65 | </CONFIG> 66 | -------------------------------------------------------------------------------- /Example3/project1.lpr: -------------------------------------------------------------------------------- 1 | {Sample of code for "UnTerminal", in a console program. 2 | This a very basic sample test. No interaction, no processing, no response. 3 | Just opening a CMD command.} 4 | 5 | program project1; 6 | uses Interfaces, UnTerminal, SysUtils; 7 | type 8 | TProc=class 9 | proc: TConsoleProc; 10 | procedure procLineCompleted(const lin: string); 11 | constructor Create; 12 | destructor Destroy; override; 13 | end; 14 | constructor TProc.Create; 15 | begin 16 | proc := TConsoleProc.Create(nil); 17 | proc.LineDelimSend := LDS_CRLF; 18 | proc.OnLineCompleted:=@procLineCompleted; 19 | end; 20 | 21 | destructor TProc.Destroy; 22 | begin 23 | proc.Destroy; 24 | end; 25 | 26 | procedure TProc.procLineCompleted(const lin: string); 27 | begin 28 | //Line received 29 | writeln('--'+lin); 30 | //To respond, do something like: proc.SendLn('dir'); 31 | end; 32 | 33 | var 34 | p: TProc; 35 | i: Integer; 36 | begin 37 | writeln('Executing process'); 38 | p := TProc.Create; 39 | {$ifdef linux} 40 | p.proc.Open('bash',''); 41 | {$endif} 42 | {$ifdef WINDOWS} 43 | p.proc.Open('cmd',''); 44 | {$endif} 45 | p.proc.Loop(3); //Execute process until finished or pass 3 seconds 46 | p.proc.Close; 47 | writeln('Finished'); 48 | p.Destroy; 49 | end. 50 | 51 | -------------------------------------------------------------------------------- /Example3/project1.lps: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectSession> 4 | <PathDelim Value="\"/> 5 | <Version Value="12"/> 6 | <BuildModes Active="Default"/> 7 | <Units Count="3"> 8 | <Unit0> 9 | <Filename Value="project1.lpr"/> 10 | <IsPartOfProject Value="True"/> 11 | <IsVisibleTab Value="True"/> 12 | <CursorPos X="32" Y="37"/> 13 | <UsageCount Value="21"/> 14 | <Loaded Value="True"/> 15 | </Unit0> 16 | <Unit1> 17 | <Filename Value="..\UnTerminal.pas"/> 18 | <EditorIndex Value="1"/> 19 | <TopLine Value="673"/> 20 | <CursorPos Y="690"/> 21 | <UsageCount Value="10"/> 22 | <Loaded Value="True"/> 23 | </Unit1> 24 | <Unit2> 25 | <Filename Value="..\TermVT.pas"/> 26 | <EditorIndex Value="-1"/> 27 | <UsageCount Value="10"/> 28 | </Unit2> 29 | </Units> 30 | <JumpHistory Count="30" HistoryIndex="29"> 31 | <Position1> 32 | <Filename Value="project1.lpr"/> 33 | <Caret Line="47" Column="21" TopLine="25"/> 34 | </Position1> 35 | <Position2> 36 | <Filename Value="project1.lpr"/> 37 | <Caret Line="48" TopLine="30"/> 38 | </Position2> 39 | <Position3> 40 | <Filename Value="project1.lpr"/> 41 | <Caret Line="12" Column="42"/> 42 | </Position3> 43 | <Position4> 44 | <Filename Value="project1.lpr"/> 45 | <Caret Line="48" Column="7" TopLine="32"/> 46 | </Position4> 47 | <Position5> 48 | <Filename Value="project1.lpr"/> 49 | <Caret Line="49" Column="5" TopLine="33"/> 50 | </Position5> 51 | <Position6> 52 | <Filename Value="project1.lpr"/> 53 | <Caret Line="2"/> 54 | </Position6> 55 | <Position7> 56 | <Filename Value="project1.lpr"/> 57 | <Caret Line="51" Column="5" TopLine="33"/> 58 | </Position7> 59 | <Position8> 60 | <Filename Value="project1.lpr"/> 61 | <Caret Line="50" Column="32" TopLine="32"/> 62 | </Position8> 63 | <Position9> 64 | <Filename Value="project1.lpr"/> 65 | <Caret Line="2" Column="18"/> 66 | </Position9> 67 | <Position10> 68 | <Filename Value="..\UnTerminal.pas"/> 69 | <Caret Line="27" Column="24" TopLine="10"/> 70 | </Position10> 71 | <Position11> 72 | <Filename Value="..\UnTerminal.pas"/> 73 | <Caret Line="917" Column="5" TopLine="917"/> 74 | </Position11> 75 | <Position12> 76 | <Filename Value="..\UnTerminal.pas"/> 77 | </Position12> 78 | <Position13> 79 | <Filename Value="..\UnTerminal.pas"/> 80 | <Caret Line="89" Column="55" TopLine="69"/> 81 | </Position13> 82 | <Position14> 83 | <Filename Value="..\UnTerminal.pas"/> 84 | <Caret Line="90" Column="67" TopLine="70"/> 85 | </Position14> 86 | <Position15> 87 | <Filename Value="..\UnTerminal.pas"/> 88 | <Caret Line="91" Column="67" TopLine="71"/> 89 | </Position15> 90 | <Position16> 91 | <Filename Value="..\UnTerminal.pas"/> 92 | <Caret Line="169" Column="15" TopLine="150"/> 93 | </Position16> 94 | <Position17> 95 | <Filename Value="..\UnTerminal.pas"/> 96 | <Caret Line="689" Column="16" TopLine="675"/> 97 | </Position17> 98 | <Position18> 99 | <Filename Value="..\UnTerminal.pas"/> 100 | <Caret Line="168" Column="12" TopLine="157"/> 101 | </Position18> 102 | <Position19> 103 | <Filename Value="project1.lpr"/> 104 | <Caret Line="48" Column="26" TopLine="29"/> 105 | </Position19> 106 | <Position20> 107 | <Filename Value="project1.lpr"/> 108 | <Caret Line="35" Column="33" TopLine="28"/> 109 | </Position20> 110 | <Position21> 111 | <Filename Value="project1.lpr"/> 112 | <Caret Line="2" Column="16"/> 113 | </Position21> 114 | <Position22> 115 | <Filename Value="project1.lpr"/> 116 | </Position22> 117 | <Position23> 118 | <Filename Value="project1.lpr"/> 119 | <Caret Line="28" TopLine="17"/> 120 | </Position23> 121 | <Position24> 122 | <Filename Value="project1.lpr"/> 123 | <Caret Line="11"/> 124 | </Position24> 125 | <Position25> 126 | <Filename Value="project1.lpr"/> 127 | <Caret Line="5"/> 128 | </Position25> 129 | <Position26> 130 | <Filename Value="project1.lpr"/> 131 | <Caret Line="42" TopLine="19"/> 132 | </Position26> 133 | <Position27> 134 | <Filename Value="project1.lpr"/> 135 | <Caret Line="4"/> 136 | </Position27> 137 | <Position28> 138 | <Filename Value="project1.lpr"/> 139 | </Position28> 140 | <Position29> 141 | <Filename Value="project1.lpr"/> 142 | <Caret Line="31" Column="62" TopLine="18"/> 143 | </Position29> 144 | <Position30> 145 | <Filename Value="project1.lpr"/> 146 | <Caret Line="3" Column="50"/> 147 | </Position30> 148 | </JumpHistory> 149 | <RunParams> 150 | <FormatVersion Value="2"/> 151 | <Modes ActiveMode=""/> 152 | </RunParams> 153 | </ProjectSession> 154 | </CONFIG> 155 | -------------------------------------------------------------------------------- /Example4/project1.lpi: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectOptions> 4 | <Version Value="12"/> 5 | <PathDelim Value="\"/> 6 | <General> 7 | <Flags> 8 | <MainUnitHasCreateFormStatements Value="False"/> 9 | <MainUnitHasTitleStatement Value="False"/> 10 | <MainUnitHasScaledStatement Value="False"/> 11 | <CompatibilityMode Value="True"/> 12 | </Flags> 13 | <SessionStorage Value="InProjectDir"/> 14 | <Title Value="project1"/> 15 | <UseAppBundle Value="False"/> 16 | <ResourceType Value="res"/> 17 | </General> 18 | <BuildModes Count="1"> 19 | <Item1 Name="Default" Default="True"/> 20 | </BuildModes> 21 | <PublishOptions> 22 | <Version Value="2"/> 23 | <UseFileFilters Value="True"/> 24 | </PublishOptions> 25 | <RunParams> 26 | <FormatVersion Value="2"/> 27 | </RunParams> 28 | <RequiredPackages Count="1"> 29 | <Item1> 30 | <PackageName Value="LCL"/> 31 | </Item1> 32 | </RequiredPackages> 33 | <Units Count="1"> 34 | <Unit0> 35 | <Filename Value="project1.lpr"/> 36 | <IsPartOfProject Value="True"/> 37 | </Unit0> 38 | </Units> 39 | </ProjectOptions> 40 | <CompilerOptions> 41 | <Version Value="11"/> 42 | <PathDelim Value="\"/> 43 | <Target> 44 | <Filename Value="project1"/> 45 | </Target> 46 | <SearchPaths> 47 | <IncludeFiles Value="$(ProjOutDir)"/> 48 | <OtherUnitFiles Value=".."/> 49 | <UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/> 50 | </SearchPaths> 51 | </CompilerOptions> 52 | <Debugging> 53 | <Exceptions Count="3"> 54 | <Item1> 55 | <Name Value="EAbort"/> 56 | </Item1> 57 | <Item2> 58 | <Name Value="ECodetoolError"/> 59 | </Item2> 60 | <Item3> 61 | <Name Value="EFOpenError"/> 62 | </Item3> 63 | </Exceptions> 64 | </Debugging> 65 | </CONFIG> 66 | -------------------------------------------------------------------------------- /Example4/project1.lpr: -------------------------------------------------------------------------------- 1 | {Sample of code for "UnTerminal", in a console program. 2 | This a very basic sample test. 3 | Just opening a CMD command.} 4 | 5 | program project1; 6 | uses Interfaces, UnTerminal,TermVT,SysUtils; 7 | type 8 | TProc=class 9 | proc: TConsoleProc; 10 | procedure procLineCompleted(const lin: string); 11 | procedure procLineInit(const grilla: TtsGrid; fIni, fFin: integer); 12 | procedure procReadData(nDat: integer; const lastLin: string); 13 | constructor Create; 14 | destructor Destroy; override; 15 | end; 16 | constructor TProc.Create; 17 | begin 18 | proc := TConsoleProc.Create(nil); 19 | proc.LineDelimSend := LDS_CRLF; 20 | proc.OnInitScreen:= @procLineInit; 21 | proc.OnLineCompleted:=@procLineCompleted; 22 | proc.OnReadData:=@procReadData; 23 | end; 24 | 25 | destructor TProc.Destroy; 26 | begin 27 | proc.Destroy; 28 | end; 29 | 30 | procedure TProc.procLineInit(const grilla: TtsGrid; fIni, fFin: integer); 31 | var 32 | i: Integer; 33 | begin 34 | for i:=fIni to fFin do write((grilla[i])); 35 | end; 36 | 37 | procedure TProc.procReadData(nDat: integer; const lastLin: string); 38 | begin 39 | Write(lastLin); 40 | end; 41 | 42 | procedure TProc.procLineCompleted(const lin: string); 43 | begin 44 | //Line received 45 | writeln('--'+lin); 46 | //To respond, do something like: proc.SendLn('dir'); 47 | end; 48 | 49 | var 50 | p: TProc; 51 | i: Integer; 52 | input: string; 53 | begin 54 | writeln('Executing process'); 55 | writeln('Type quit to leave'); 56 | p := TProc.Create; 57 | {$ifdef linux} 58 | p.proc.Open('bash',''); 59 | {$endif} 60 | {$ifdef WINDOWS} 61 | p.proc.Open('cmd',''); 62 | {$endif} 63 | repeat 64 | Readln(input); 65 | writeln('You input '+ input); 66 | if input = 'quit' then 67 | break; 68 | p.proc.SendLn(input); 69 | p.proc.Loop(1); 70 | until p.proc.State = ECO_STOPPED; 71 | writeln('Finished'); 72 | p.proc.Close; 73 | p.Destroy; 74 | end. 75 | -------------------------------------------------------------------------------- /Example4/project1.lps: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectSession> 4 | <PathDelim Value="\"/> 5 | <Version Value="12"/> 6 | <BuildModes Active="Default"/> 7 | <Units Count="3"> 8 | <Unit0> 9 | <Filename Value="project1.lpr"/> 10 | <IsPartOfProject Value="True"/> 11 | <IsVisibleTab Value="True"/> 12 | <CursorPos X="32"/> 13 | <UsageCount Value="21"/> 14 | <Loaded Value="True"/> 15 | </Unit0> 16 | <Unit1> 17 | <Filename Value="..\UnTerminal.pas"/> 18 | <EditorIndex Value="1"/> 19 | <TopLine Value="416"/> 20 | <CursorPos Y="434"/> 21 | <UsageCount Value="10"/> 22 | <Loaded Value="True"/> 23 | </Unit1> 24 | <Unit2> 25 | <Filename Value="..\TermVT.pas"/> 26 | <EditorIndex Value="-1"/> 27 | <TopLine Value="37"/> 28 | <CursorPos Y="37"/> 29 | <UsageCount Value="10"/> 30 | </Unit2> 31 | </Units> 32 | <JumpHistory Count="30" HistoryIndex="29"> 33 | <Position1> 34 | <Filename Value="project1.lpr"/> 35 | <Caret Line="2" Column="18"/> 36 | </Position1> 37 | <Position2> 38 | <Filename Value="..\UnTerminal.pas"/> 39 | <Caret Line="27" Column="24" TopLine="10"/> 40 | </Position2> 41 | <Position3> 42 | <Filename Value="..\UnTerminal.pas"/> 43 | <Caret Line="917" Column="5" TopLine="917"/> 44 | </Position3> 45 | <Position4> 46 | <Filename Value="..\UnTerminal.pas"/> 47 | </Position4> 48 | <Position5> 49 | <Filename Value="..\UnTerminal.pas"/> 50 | <Caret Line="89" Column="55" TopLine="69"/> 51 | </Position5> 52 | <Position6> 53 | <Filename Value="..\UnTerminal.pas"/> 54 | <Caret Line="90" Column="67" TopLine="70"/> 55 | </Position6> 56 | <Position7> 57 | <Filename Value="..\UnTerminal.pas"/> 58 | <Caret Line="91" Column="67" TopLine="71"/> 59 | </Position7> 60 | <Position8> 61 | <Filename Value="..\UnTerminal.pas"/> 62 | <Caret Line="169" Column="15" TopLine="150"/> 63 | </Position8> 64 | <Position9> 65 | <Filename Value="..\UnTerminal.pas"/> 66 | <Caret Line="689" Column="16" TopLine="675"/> 67 | </Position9> 68 | <Position10> 69 | <Filename Value="..\UnTerminal.pas"/> 70 | <Caret Line="168" Column="12" TopLine="157"/> 71 | </Position10> 72 | <Position11> 73 | <Filename Value="project1.lpr"/> 74 | <Caret Line="48" Column="26" TopLine="29"/> 75 | </Position11> 76 | <Position12> 77 | <Filename Value="project1.lpr"/> 78 | <Caret Line="35" Column="33" TopLine="28"/> 79 | </Position12> 80 | <Position13> 81 | <Filename Value="project1.lpr"/> 82 | <Caret Line="2" Column="16"/> 83 | </Position13> 84 | <Position14> 85 | <Filename Value="project1.lpr"/> 86 | </Position14> 87 | <Position15> 88 | <Filename Value="project1.lpr"/> 89 | <Caret Line="28" TopLine="17"/> 90 | </Position15> 91 | <Position16> 92 | <Filename Value="project1.lpr"/> 93 | <Caret Line="11"/> 94 | </Position16> 95 | <Position17> 96 | <Filename Value="project1.lpr"/> 97 | <Caret Line="5"/> 98 | </Position17> 99 | <Position18> 100 | <Filename Value="project1.lpr"/> 101 | <Caret Line="42" TopLine="19"/> 102 | </Position18> 103 | <Position19> 104 | <Filename Value="project1.lpr"/> 105 | <Caret Line="4"/> 106 | </Position19> 107 | <Position20> 108 | <Filename Value="project1.lpr"/> 109 | </Position20> 110 | <Position21> 111 | <Filename Value="project1.lpr"/> 112 | <Caret Line="31" Column="62" TopLine="18"/> 113 | </Position21> 114 | <Position22> 115 | <Filename Value="project1.lpr"/> 116 | <Caret Line="3" Column="50"/> 117 | </Position22> 118 | <Position23> 119 | <Filename Value="project1.lpr"/> 120 | <Caret Line="24" Column="5"/> 121 | </Position23> 122 | <Position24> 123 | <Filename Value="project1.lpr"/> 124 | </Position24> 125 | <Position25> 126 | <Filename Value="project1.lpr"/> 127 | <Caret Line="72" Column="5" TopLine="35"/> 128 | </Position25> 129 | <Position26> 130 | <Filename Value="project1.lpr"/> 131 | <Caret Line="58" Column="18" TopLine="35"/> 132 | </Position26> 133 | <Position27> 134 | <Filename Value="project1.lpr"/> 135 | <Caret Line="50" TopLine="26"/> 136 | </Position27> 137 | <Position28> 138 | <Filename Value="project1.lpr"/> 139 | <Caret Line="68" Column="9" TopLine="37"/> 140 | </Position28> 141 | <Position29> 142 | <Filename Value="project1.lpr"/> 143 | <Caret Line="61" Column="5" TopLine="37"/> 144 | </Position29> 145 | <Position30> 146 | <Filename Value="project1.lpr"/> 147 | <Caret Line="6" Column="32"/> 148 | </Position30> 149 | </JumpHistory> 150 | <RunParams> 151 | <FormatVersion Value="2"/> 152 | <Modes ActiveMode=""/> 153 | </RunParams> 154 | </ProjectSession> 155 | </CONFIG> 156 | -------------------------------------------------------------------------------- /HelloWorld/project1.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/HelloWorld/project1.ico -------------------------------------------------------------------------------- /HelloWorld/project1.lpi: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectOptions> 4 | <Version Value="11"/> 5 | <PathDelim Value="\"/> 6 | <General> 7 | <SessionStorage Value="InProjectDir"/> 8 | <MainUnit Value="0"/> 9 | <Title Value="project1"/> 10 | <ResourceType Value="res"/> 11 | <UseXPManifest Value="True"/> 12 | <Icon Value="0"/> 13 | </General> 14 | <i18n> 15 | <EnableI18N LFM="False"/> 16 | </i18n> 17 | <BuildModes Count="1"> 18 | <Item1 Name="Default" Default="True"/> 19 | </BuildModes> 20 | <PublishOptions> 21 | <Version Value="2"/> 22 | </PublishOptions> 23 | <RunParams> 24 | <FormatVersion Value="2"/> 25 | <Modes Count="1"> 26 | <Mode0 Name="default"/> 27 | </Modes> 28 | </RunParams> 29 | <RequiredPackages Count="1"> 30 | <Item1> 31 | <PackageName Value="LCL"/> 32 | </Item1> 33 | </RequiredPackages> 34 | <Units Count="2"> 35 | <Unit0> 36 | <Filename Value="project1.lpr"/> 37 | <IsPartOfProject Value="True"/> 38 | </Unit0> 39 | <Unit1> 40 | <Filename Value="unit1.pas"/> 41 | <IsPartOfProject Value="True"/> 42 | <ComponentName Value="Form1"/> 43 | <HasResources Value="True"/> 44 | <ResourceBaseClass Value="Form"/> 45 | <UnitName Value="Unit1"/> 46 | </Unit1> 47 | </Units> 48 | </ProjectOptions> 49 | <CompilerOptions> 50 | <Version Value="11"/> 51 | <PathDelim Value="\"/> 52 | <Target> 53 | <Filename Value="project1"/> 54 | </Target> 55 | <SearchPaths> 56 | <IncludeFiles Value="$(ProjOutDir)"/> 57 | <OtherUnitFiles Value=".."/> 58 | <UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/> 59 | </SearchPaths> 60 | <Linking> 61 | <Options> 62 | <Win32> 63 | <GraphicApplication Value="True"/> 64 | </Win32> 65 | </Options> 66 | </Linking> 67 | </CompilerOptions> 68 | <Debugging> 69 | <Exceptions Count="3"> 70 | <Item1> 71 | <Name Value="EAbort"/> 72 | </Item1> 73 | <Item2> 74 | <Name Value="ECodetoolError"/> 75 | </Item2> 76 | <Item3> 77 | <Name Value="EFOpenError"/> 78 | </Item3> 79 | </Exceptions> 80 | </Debugging> 81 | </CONFIG> 82 | -------------------------------------------------------------------------------- /HelloWorld/project1.lpr: -------------------------------------------------------------------------------- 1 | program project1; 2 | 3 | {$mode objfpc}{$H+} 4 | 5 | uses 6 | {$IFDEF UNIX}{$IFDEF UseCThreads} 7 | cthreads, 8 | {$ENDIF}{$ENDIF} 9 | Interfaces, // this includes the LCL widgetset 10 | Forms, Unit1; 11 | 12 | {$R *.res} 13 | 14 | begin 15 | RequireDerivedFormResource := True; 16 | Application.Initialize; 17 | Application.CreateForm(TForm1, Form1); 18 | Application.Run; 19 | end. 20 | 21 | -------------------------------------------------------------------------------- /HelloWorld/project1.lps: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <CONFIG> 3 | <ProjectSession> 4 | <PathDelim Value="\"/> 5 | <Version Value="12"/> 6 | <BuildModes Active="Default"/> 7 | <Units Count="7"> 8 | <Unit0> 9 | <Filename Value="project1.lpr"/> 10 | <IsPartOfProject Value="True"/> 11 | <CursorPos Y="20"/> 12 | <UsageCount Value="68"/> 13 | </Unit0> 14 | <Unit1> 15 | <Filename Value="unit1.pas"/> 16 | <IsPartOfProject Value="True"/> 17 | <ComponentName Value="Form1"/> 18 | <HasResources Value="True"/> 19 | <ResourceBaseClass Value="Form"/> 20 | <UnitName Value="Unit1"/> 21 | <IsVisibleTab Value="True"/> 22 | <TopLine Value="13"/> 23 | <CursorPos X="4" Y="31"/> 24 | <UsageCount Value="68"/> 25 | <Loaded Value="True"/> 26 | <LoadedDesigner Value="True"/> 27 | </Unit1> 28 | <Unit2> 29 | <Filename Value="termVT.pas"/> 30 | <UsageCount Value="38"/> 31 | </Unit2> 32 | <Unit3> 33 | <Filename Value="unterminal.pas"/> 34 | <UnitName Value="UnTerminal"/> 35 | <TopLine Value="233"/> 36 | <CursorPos X="39" Y="241"/> 37 | <UsageCount Value="38"/> 38 | </Unit3> 39 | <Unit4> 40 | <Filename Value="..\UnTerminal.pas"/> 41 | <EditorIndex Value="-1"/> 42 | <TopLine Value="710"/> 43 | <CursorPos X="10" Y="710"/> 44 | <FoldState Value=" T3lW0I6 pj3jS0I414 T6lX01A T0lcH8A piZkPS5D]9ajeOIM6C TMn401081715151111161B2F"/> 45 | <UsageCount Value="33"/> 46 | </Unit4> 47 | <Unit5> 48 | <Filename Value="C:\lazarus\lcl\include\control.inc"/> 49 | <EditorIndex Value="-1"/> 50 | <TopLine Value="3927"/> 51 | <CursorPos Y="3945"/> 52 | <UsageCount Value="7"/> 53 | </Unit5> 54 | <Unit6> 55 | <Filename Value="..\TermVT.pas"/> 56 | <EditorIndex Value="-1"/> 57 | <TopLine Value="286"/> 58 | <CursorPos X="22" Y="315"/> 59 | <UsageCount Value="9"/> 60 | </Unit6> 61 | </Units> 62 | <JumpHistory HistoryIndex="-1"/> 63 | <RunParams> 64 | <FormatVersion Value="2"/> 65 | <Modes ActiveMode="default"/> 66 | </RunParams> 67 | </ProjectSession> 68 | </CONFIG> 69 | -------------------------------------------------------------------------------- /HelloWorld/project1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/HelloWorld/project1.res -------------------------------------------------------------------------------- /HelloWorld/unit1.lfm: -------------------------------------------------------------------------------- 1 | object Form1: TForm1 2 | Left = 248 3 | Height = 499 4 | Top = 180 5 | Width = 714 6 | Caption = 'Form1' 7 | ClientHeight = 499 8 | ClientWidth = 714 9 | DesignTimePPI = 120 10 | OnCreate = FormCreate 11 | LCLVersion = '2.0.10.0' 12 | object Memo1: TMemo 13 | Left = 12 14 | Height = 388 15 | Top = 80 16 | Width = 688 17 | ParentFont = False 18 | ScrollBars = ssAutoBoth 19 | TabOrder = 0 20 | end 21 | object label1: TLabel 22 | Left = 15 23 | Height = 20 24 | Top = 15 25 | Width = 52 26 | Caption = 'Process:' 27 | ParentColor = False 28 | ParentFont = False 29 | end 30 | object txtProcess: TEdit 31 | Left = 100 32 | Height = 28 33 | Top = 15 34 | Width = 338 35 | ParentFont = False 36 | TabOrder = 1 37 | Text = 'cmd /c dir' 38 | end 39 | object Button1: TButton 40 | Left = 450 41 | Height = 39 42 | Top = 12 43 | Width = 118 44 | Caption = 'S&tart' 45 | OnClick = Button1Click 46 | ParentFont = False 47 | TabOrder = 2 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /HelloWorld/unit1.pas: -------------------------------------------------------------------------------- 1 | {Basic code to launch and capture the output of a process using the unit "UnTerminal".} 2 | unit Unit1; 3 | {$mode objfpc}{$H+} 4 | interface 5 | uses 6 | SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,UnTerminal, Classes; 7 | 8 | type 9 | 10 | { TForm1 } 11 | 12 | TForm1 = class(TForm) 13 | Button1: TButton; 14 | txtProcess: TEdit; 15 | label1: TLabel; 16 | Memo1: TMemo; 17 | procedure Button1Click(Sender: TObject); 18 | procedure FormCreate(Sender: TObject); 19 | end; 20 | 21 | var 22 | Form1: TForm1; 23 | 24 | implementation 25 | 26 | {$R *.lfm} 27 | 28 | { TForm1 } 29 | 30 | procedure TForm1.Button1Click(Sender: TObject); 31 | var 32 | outText: String; 33 | proc: TConsoleProc; 34 | begin 35 | proc:= TConsoleProc.Create(nil); 36 | proc.RunInLoop(txtProcess.Text,'', -1, outText); 37 | 38 | Memo1.Text := outText; 39 | proc.Destroy; 40 | end; 41 | 42 | procedure TForm1.FormCreate(Sender: TObject); 43 | begin 44 | {$ifdef linux} 45 | txtProcess.Text:= 'bash -c "ls"'; 46 | {$endif} 47 | end; 48 | 49 | end. 50 | 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | UnTerminal 1.0 2 | ============== 3 | 4 | By Tito Hinostroza 5 | 6 | Lazarus unit for control external programs or console processes, with prompt detection. Tested in Linux and DOS consoles. 7 | 8 | This unit allows to launch a process and interact with it trough the standard input and output. 9 | 10 | Features: 11 | 12 | * Works as a wrapper for TProcess. 13 | * Includes detection of prompt. 14 | * Assigns states for a process, like "Ready" or "Busy". 15 | * Is event driven. 16 | * Recognize some VT100 sequences. 17 | 18 | Programs to be controled with this unit should comply: 19 | 20 | 1. That can be launched as a console command. 21 | 2. That input and output are text format. 22 | 23 | Optionally they can: 24 | 25 | 3. Have a prompt. 26 | 4. Be controled by commands (If we want to send data to the process). 27 | 28 | The processes that can be controlled with this unit are diverse, such as telnet clients, ftp, or the operating system shell itself, as shown in the included example. 29 | 30 | In the current version, the error output stream cannot be read independently. Only two flows are controlled: 31 | 32 | 1. Input 33 | 2. Output (stdout and stderr). 34 | 35 | ![Tito's Terminal](https://github.com/t-edson/UnTerminal/blob/1.0/screen1.png "Título de la imagen") 36 | 37 | ## Hello world 38 | 39 | The simplest code to launch a command/process/program and capture the output can be: 40 | 41 | ``` 42 | var outputText: string; 43 | 44 | proc:= TConsoleProc.Create(nil); 45 | proc.RunInLoop('bash -c "ls" ','', -1, outputText); 46 | ``` 47 | 48 | This code executes the command 'bash -c "ls" ' and captures the output (and the errors) in the variable "outputText". 49 | 50 | This code works for linux but can be used in windows too, usign DOS commands. 51 | 52 | 53 | ## Executing commands 54 | 55 | To execute a command, first you need to create an instance of the class TConsoleProc: 56 | 57 | ``` 58 | p := TConsoleProc.Create(nil); //Create conecction 59 | ... 60 | 61 | ``` 62 | 63 | Then you need to execute the command, choosing the appropriate way. 64 | 65 | There are several ways to execute commands using UnTerminal. They can be clasified in two types: 66 | 67 | A) Running in a finite loop (or until the process finishes). 68 | 69 | B) Running in a infinite loop (or until the program finishes). 70 | 71 | Both methods can use events to work. 72 | 73 | The option A, is implemented using the method RunInLoop(). There are several versions of this method: 74 | 75 | ``` 76 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer = -1): boolean; 77 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer; 78 | var progOut: TStringList): boolean; 79 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer; out 80 | outText: String): boolean; 81 | ``` 82 | 83 | The idea of this way is to send a command and get the output/error text in a variable, generally without interacting with the process. 84 | 85 | The parameter "progPath" is the name of the program or commnand to be executed. Consider that popular commands of DOS or Linux, are not programs, so we cannot launch "dir" or "ls" in "progPath". Instead we need to call the corresponding command processor and pass the commands, like "cmd /c dir" or 'bash -c "ls"'. 86 | 87 | The parameter "progParam" is a string containing the paremeters of the program or commnand to be executed. They can be included in "progPath" too, but it's advisable to include them separately. 88 | 89 | As an example the next commands are similar: 90 | 91 | ``` 92 | proc.RunInLoop('cmd','/c dir', -1, outText); 93 | ``` 94 | 95 | ``` 96 | proc.RunInLoop('cmd /c dir','', -1, outText); 97 | ``` 98 | 99 | If the program or command doesn't exist, the instruction RunInLoop() will raise an exception in runtime. 100 | 101 | The parameters "TimeoutSegs" is the numbers of seconds to wait the command finishes, before continue executing the next instructions. The value -1 indicates, the instruction will wait until the command finishes. 102 | 103 | The option B is described in the next sections of this document. 104 | 105 | ## States of the process 106 | 107 | The connection is managed by states. The possible states of the process are: 108 | 109 | * ECO_STOPPED .- The Process has not started. This condition always occurs after creating the connection, or after closing an open connection. There may be data pending in the "buffer" 110 | 111 | * ECO_CONNECTING .- This condition occurs after opening the connection with the indicated process. Terminates when the prompt is detected. If the prompt is not detected (whether it does not arrive, or it has not been configured correctly), the process will always remain in this state. 112 | 113 | * ECO_ERROR_CON .- Occurs when after trying to open the process, an error occurs, for example, when referring to a file that does not exist. 114 | 115 | * ECO_READY .- This process starts when the prompt is detected (if prompt detection is used). Indicates that the process is ready to accept commands. It remains in this state until a command is received to send to the process. 116 | 117 | * ECO_BUSY .- This state starts after sending a command, when the process was in ECO_READY state. It remains in this state, until the prompt is detected and the ECO_READY state is fired. 118 | 119 | The process can only be in one of these states at a time. The transition between states has a logical sequence, but can have changes. 120 | 121 | A typical sequence of states when initiating a successful connection is: 122 | 123 | ECO_STOPPED -> ECO_CONNECTING -> ECO_READY 124 | 125 | The ECO_READY status indicates that the process is ready to receive commands and is detected when the prompt is received. Therefore, for a process to be considered as ECO_READY, it must have a prompt and that the terminal is configured to detect it. 126 | 127 | The sequence of a failed connection would be: 128 | 129 | ECO_STOPPED -> ECO_CONNECTING -> ... 130 | 131 | That is, the prompt is not detected, but the process probably stops with an error message. Error messages detection is not done on this unit, because they can be very diverse. It is recommended to implement them in another unit or by deriving an additional class. 132 | 133 | Once the process is available. Any command would have the following flow: 134 | 135 | ECO_READY -> ECO_BUSY -> ECO_READY 136 | 137 | This unit is thought to be used in slow connections, and with long data responses, therefore the arrival of data is handled completely by events. 138 | 139 | To operate the display, use a simple VT100 terminal from the TermVT unit. However, this unit has been designed to be able to receive the text from the VT100, in a TStringList, and to be able to permanently record the content. 140 | 141 | The process to be launched starts with the Open() method and ends with the Close() method. 142 | 143 | ## Setting an Editor to show the output 144 | 145 | The objective of using UnTerminal is to be able to display the output in a comfortable way for the user. 146 | 147 | "UnTerminal", has beed designed to handle slow processes with massive data output. Therefore the data output is handled entirely by events. In addition, it is assumed that it is required to keep a record on the screen information while appearing. For this reason, the events are oriented to handle a "TStrings" object, which allows adding new lines and saving the previous lines (output register). 148 | 149 | There are several groups of events to handle the data output. 150 | 151 | Four methods are defined to control the data output:: 152 | 153 | 1. Output line by line. 154 | 2. Output line by line with partial line. 155 | 3. Output line by line with partial line in prompt. 156 | 4. Output as a VT100 terminal. 157 | 158 | Each of these methods has its advantages and disadvantages. And you should use the one that best suits the needs of the application. Thus, to implement a Telnet client, method 4 (the most complete) should be used, but for other processes it will suffice to use simpler methods. 159 | 160 | An additional method could be implemented which consists of directly intercepting the terminal events (property term: TTermVT100) of TConsoleProc, to display the information on the screen. However, this working method is of a lower level, but it can be used to capture the complete content of the VT100 terminal, every time there is a change (which would not be very efficient, of course). 161 | 162 | Implementing data output does not affect prompt detection. The detection routines work directly on the data blocks that are arriving from the process, without the need for this data to be displayed. 163 | 164 | ### Output line by line 165 | 166 | With respect to the other methods, this method is the simplest, and although it has certain limitations, it may be sufficient for some cases, like when our process will not handle ANSI sequences, but will simply send plain text without delete commands or cursor handling. 167 | 168 | To do a line-by-line capture, we need to use a single event: 169 | 170 | OnLineCompleted:TEvLinCompleted; 171 | 172 | That is generated every time a line break is detected in the arrival of data. So we could use this method to add lines to our output editor, without worrying about starting the screen, or about the previous information it may contain. 173 | 174 | Our code would be something like this: 175 | 176 | ``` 177 | proc := TConsoleProc.Create(nil); 178 | proc.OnLineCompleted:=@procOnLineCompleted; 179 | proc.Open('cmd /c dir',''); 180 | 181 | ... 182 | 183 | procedure TForm1.procOnLineCompleted(const lin: string); 184 | begin 185 | Memo.Lines.Add(lin); 186 | end; 187 | ``` 188 | 189 | This minimalistic form will work fine, displaying the arrival data, but with an apparent delay, because for a line to be displayed, it must be complete. So when the prompt (or an incomplete line) arrives, this line won't show up in the editor (even though the process might go into ECO_READY state). 190 | 191 | The fact that the last line is not displayed does not imply that it will no longer be displayed. This will be visible when the corresponding line break is received, unless the connection is closed before. 192 | 193 | This method of capturing output is useful when it is required to capture massive data output without the correct display of the prompt or intermediate lines being very important. 194 | 195 | To determine when the data is finished receiving, prompt detection can be used, if the process allows it. 196 | 197 | ### Output line by line with partial line 198 | 199 | The line-by-line method is simple and secure. But it doesn't always update the last line. For the last complete line to be displayed, the corresponding line break must be received. Thus we can say that in this working mode, the last line received will never be shown (unless of course, that the last character received is the line break and we consider that the last line is the one before the jump). 200 | 201 | To overcome this inconvenience, you can use the combination of events: 202 | 203 | OnLineCompleted: TEvLinCompleted; 204 | OnReadData : TEvReadData; 205 | 206 | The OnReadData() event is generated when a block of data is finished reading and usually ends with a final line without a jump (it can be the prompt). So what we should do is complete replace this line, if we then receive the OnLineCompleted () event. 207 | 208 | The working code will look like this: 209 | 210 | ``` 211 | var LinPartial: boolean = false; 212 | 213 | proc.OnLineCompleted:=@procLineCompleted; 214 | proc.OnReadData:=@procReadData; 215 | ... 216 | 217 | procedure TForm1.procLineCompleted(const lin: string); 218 | begin 219 | if LinPartial then begin 220 | //We are in the prompt line 221 | Memo1.Lines[Memo1.Lines.Count-1] := lin; //Replace last line 222 | LinPartial := false; 223 | end else begin //Common case 224 | Memo1.Lines.Add(lin); 225 | end; 226 | end; 227 | 228 | procedure TForm1.procReadData(nDat: integer; const lastLin: string); 229 | begin 230 | LinPartial := true; //Set flag 231 | Memo1.Lines.Add(lastLin); //Add line containing the prompt 232 | end; 233 | ``` 234 | 235 | The variable 'LinPartial' helps us to know when a partial line has been received. 236 | 237 | This working method will work quite well and is simple, but it could be the case (rare) where the OnReadData() event is received twice in a row, causing an additional line to be generated in the editor. This case could occur when a very long line is generated that arrives in more than one block, or in very slow connections. 238 | 239 | To avoid this effect, an additional protection routine could be included to verify that the OnReadData() event is occurring twice in a row and, if so, avoid adding one more line. 240 | 241 | The use of OnLineCompleted()-OnReadData() events is a simple way to receive data "line by line", but we must not forget that it should only be applied to processes with simple text output without cursor control or text deletion. Most processes fall into this category (like FTP clients or even the DOS shell itself), but processes like a Telnet or SSH client use escape sequences that may require positioning the cursor to overwrite blocks. 242 | 243 | In these cases you should not implement this output capture method; but even if it were implemented here, we could work fine, as long as cursor jumps or text deletion is not generated. Escape sequences that change text attributes do not affect the output of the text, because they are processed (or better said ignored) by TConsoleProc, so that the text output events do not contain ANSI sequences of any kind, in their parameters. 244 | 245 | ### Output Line-by-line with partial line at Prompt 246 | 247 | As a variation of the previous method, this method is very similar, but with the difference that the detection of partial lines is done only for when the promtp is detected. 248 | 249 | In this way, it is avoided to generate many overwriting of lines, since it will only be done in the prompt line. This method is more efficient when you have multiple data packets between prompt and prompt. 250 | 251 | A disadvantage of this method is that the prompt must be configured, and it always muts appears at the end of a data block, so that the last line is refreshed, otherwise it will not be refreshed in any way. 252 | 253 | Therefore it is only recommended for processes that always show the prompt. It is not recommended, for example, in a process that at some point will show a message such as "Please enter a value:", waiting for user input. Therefore you have to be cautious when using this output capture method. 254 | 255 | The implementation of the capture is the same as the previous case, only another pair of events is used: 256 | 257 | ``` 258 | OnLineCompleted: TEvLinCompleted; 259 | OnLinePrompt: TEvLinCompleted; 260 | ``` 261 | 262 | The OnLinePrompt() event is generated when the line containing the prompt is received, even if it is not complete. So what we should do is complete replace this line, if we then receive the OnLineCompleted() event. 263 | 264 | The working code will look like this: 265 | 266 | ``` 267 | var LinPrompt: boolean = false; 268 | 269 | proc.OnLineCompleted := @procLineCompleted; 270 | proc.OnLinePrompt := @procLinePrompt; 271 | ... 272 | 273 | procedure TForm1.procLineCompleted(const lin: string); 274 | begin 275 | if LinPrompt then begin 276 | //We are in the prompt line 277 | SynEdit1.Lines[SynEdit1.Lines.Count-1] := lin; //Replace last line 278 | LinPrompt := false; 279 | end else begin //Common case 280 | SynEdit1.Lines.Add(lin); 281 | end; 282 | end; 283 | 284 | procedure TForm1.procLinePrompt(const lin: string); 285 | begin 286 | LinPrompt := true; //Set flag 287 | SynEdit1.Lines.Add(lin); //Add line containing the prompt 288 | end; 289 | ``` 290 | 291 | The variable 'LinPrompt', helps us to detect when the prompt has been received on a line. 292 | 293 | This working method can also suffer from the problem of the previous method if, it is that a long line is received (where the prompt is detected) that comes in more than one block. The solution to apply is the same. 294 | 295 | The effect of this extreme case may not be very critical, as it will only generate an additional line with the prompt in the output editor. This additional line will not remove the readability of the code but it is a lack of fidelity in the output of the process anyway. 296 | 297 | ### Output as VT100 Terminal 298 | 299 | This is the most complete method of handling the terminal output. It allows to recognize the escape sequences that control the cursor, or manipulate the text of the terminal. 300 | 301 | It can be said that this is the formal method for handling any process, even if it generates ANSI escape sequences. However, managing processes using this way of working can be difficult when managing the cursor position or when you want to switch from one output editor to another. 302 | 303 | To set an editor in this way, you must use the events: OnInitScreen(), OnRefreshLine(), OnRefreshLines() and OnAddLine(). 304 | 305 | In the following code, a SynEdit editor is used as the output for any process. 306 | 307 | ``` 308 | proc.OnInitScreen := @procInitScreen; 309 | proc.OnRefreshLine := @procRefreshLine; 310 | proc.OnRefreshLines:= @procRefreshLines; 311 | proc.OnAddLine := @procAddLine; 312 | ... 313 | 314 | procedure TfrmPrincipal.procInitScreen(const grid: TtsGrid; fIni, fFin: integer); 315 | begin 316 | for i:=fIni to fFin do SynEdit1.Lines.Add(grid[i]); 317 | end; 318 | 319 | procedure TfrmPrincipal.procRefreshLine(const grid: TtsGrid; fIni, HeightScr: integer); 320 | begin 321 | yvt := SynEdit1.Lines.Count-HeightScr-1; 322 | SynEdit1.Lines[yvt+fIni] := grid[fIni]; 323 | end; 324 | 325 | procedure TfrmPrincipal.procRefreshLines(const grid: TtsGrid; fIni, fFin, HeightScr: integer); 326 | begin 327 | yvt := SynEdit1.Lines.Count-HeightScr-1; //Calculate row equivalent to start of VT100 328 | for f:=fIni to fFin do SynEdit1.Lines[yvt+ f] := grid[f]; 329 | end; 330 | 331 | procedure TfrmPrincipal.procAddLine; 332 | begin 333 | SynEdit1.Lines.Add(''); 334 | end; 335 | ``` 336 | 337 | The OnInitScreen() event is called only once at startup to size the StringList, so that it can contain all the lines of the VT100 terminal. The output editor must have at least the number of lines that the VT100 terminal has (25 by default), otherwise an error will be generated at runtime. This condition is compressible, if we consider that it is about "fitting" a virtual screen of a termninal (which can be 80x25 lines) in a TString container. 338 | 339 | To position the virtual cursor of the terminal on any line of the TString, the calculation [1] must first be done: 340 | 341 | yvt := SynEdit1.Lines.Count-HeightScr-1; 342 | 343 | where 'HeightScr' is the current height of the VT100 terminal, which is provided by the TConsoleProc events. 344 | 345 | [1] Of course, if we did not want to save the record of the previous lines, it would not be necessary to complicate ourselves with the calculations and we would only need to have a TString with the same number of lines from the VT100, and we would avoid calculating the vertical position because it would be the same in the terminal and on the TString. 346 | 347 | To clean the content of the terminal, you must call the ClearTerminal() method, which also resets the cursor position, setting it to (1,1). 348 | 349 | Calling ClearTerminal() will have no effect on the status of the connection or the process in progress, but only on the content of the terminal. 350 | 351 | 352 | ## Terminal use 353 | 354 | ### Sending commands 355 | 356 | The commands (or any string in general), are sent to the process with the Send(), SendLn() or SendFile() methods. 357 | 358 | SendLn() is similar to Send(), but additionally sends a newline character(s) at the end. The newline character(s) is necessary, in most processes, so that the sent string is recognized, as a command. 359 | 360 | The SendFile() method sends the complete content of a file to the program. 361 | 362 | The newline character(s) to send depends on the value of "LineDelimSend". 363 | 364 | To send control characters, the SendVT100Key() method must be used, because control characters must first be converted into escape sequences, at least for applications that recognize escape sequences. For example, if the right directional key is sent, with SendVT100Key(), it will first be transformed into the sequence: ESC + \[C. 365 | 366 | To send simple commands (which are printable character sequences), just use SenLn(). 367 | 368 | In principle, only a single command should be sent by SendLn() because, sending more than one command could make the process go through the phases repeatedly: 369 | 370 | ECO_BUSY -> ECO_READY -> ECO_BUSY ... -> ECO_READY. 371 | 372 | Making it go from a free to busy state automatically, and being able to complicate a routine that is programmed to send more commands when it detects that the process is ready. 373 | 374 | The output data that comes from the process are not completely saved in the class. Only the working lines of a VT100 terminal are kept in the "term" object. This saves memory, because generally the output text is intended to be stored in some other control such as a text editor or grid. 375 | 376 | It is the responsibility of the programmer to limit the size of the stored data. 377 | 378 | The process output data, arriving through the terminal, is retrieved by polling the output stream. By default, the output is scanned in intervals of 50 milliseconds (20 times per second), and using an internal 2048-byte "buffer". 379 | 380 | To change the polling period of the process output, you must change the value of the 'clock.interval' property (in milliseconds). You can work well with periods of 100 msec or even more, if the amount of information is low. But it is not recommended to go below 50 msec, because an additional CPU load is generated (even when no data arrives). This period should only be lowered when it is required to process the arrival data, immediately. 381 | 382 | ### Line-ending in sending 383 | 384 | Inside UnTerminal, you can configure the line break characters that will be used, both for sending and receiving. 385 | 386 | To set the line-ending characters in sending, the "LineDelimSend" property must be used, which can take the following values: 387 | 388 | * LDS_CRLF //Sends CR and LF characters 389 | * LDS_CR //Send only CR (character #13) 390 | * LDS_LF //Send only LF (character #10) 391 | 392 | Setting the line-ending for sending implies that the configured characters will be added, each time the TConsoleProc.SendLn() or TConsoleProc.SendFile() methods are used, regardless of the type of delimiter that has been included in the string. The following examples will illustrate the behavior of SendLn(), when "LineDelimSend" is set. 393 | 394 | If LineDelimSend has been defined in LDS_LF, then: 395 | 396 | SendLn('aaa'); //Will actually send 'aaa'#10 397 | SendLn('aaa'#10); //Will actually send 'aaa'#10 398 | SendLn('aaa'#13); //Will actually send 'aaa'#10 399 | SendLn('aaa'#13#10); //Will actually send 'aaa'#10 400 | SendLn('aaa'#13#10'bbb'); //Will actually send 'aaa'#10'bbb'#10 401 | 402 | As you can see, when a newline character is set, all the newlines are changed so that only the configured newline is used. 403 | 404 | In general, "LineDelimSend" should be set to LDS_LF, for Linux / UNIX processes, and should be left at LDS_CRLF, for Windows processes. 405 | 406 | The "LineDelimSend" property has no effect on the TConsoleProc.Send() method, which will always send the indicated characters. 407 | 408 | ### Line-ending in receiving 409 | 410 | To set the line-ending characters, at the reception, you must use the "LineDelimRecv" property, which can take the following values: 411 | 412 | * LDR_CRLF //The line break is CR-LF (or LF-CR). 413 | * LDR_CR //The line break is this character. LF is ignored. 414 | * LDR_LF //The line break is this character. CR is ignored. 415 | * LDR_CR_LF //The line break is CR or LF 416 | 417 | When "LineDelimRecv" is set, the reception routines are being told how they should interpret the CR and LF characters. If for example "LineDelimRecv" is configured in LDR_LF, then every time the LF character is received, it will be interpreted as a line break, ignoring the CR character. 418 | 419 | In general, "LineDelimRecv" should be set to LDR_LF, for Linux / UNIX processes, and it should be left at LDR_CRLF, for Windows processes. 420 | 421 | The TTermVT100.OnLineCompleted() event is generated when the arrival of the line-ending character (or characters) is detected. This event will contain the current line as parameter. 422 | 423 | ## Prompt Detection 424 | 425 | Prompt detection is done by exploring the text strings that are arriving from the process, to see if they match the detection parameters. This method may not be very reliable if the Prompt of the process changes too much. 426 | 427 | The output data generated by the process is received in blocks that can have a variable size, but that do not exceed the constant UBLOCK_SIZE. The search for the prompt is always done on the last line of each block of data that is received from the process (in the ReadData() method). If the process must send too much information, it usually arrives in several blocks, but the prompt (at least the final part) is always expected to arrive in the last block received. Not every line received is scanned, to reduce the processing load. 428 | 429 | To configure the detection of the Prompt, set the 'detecPrompt' property to TRUE and set values ​​for 'promptIni' and 'promptFin'. These strings determine the beginning and ending part of the prompt. 430 | 431 | If the prompt does not change, you can put its value directly in 'promptIni' and leave 'promptFin' empty. But if the prompt is variable, you can put the initial part in 'promptIni' and the final part in 'promptFin', but choosing values ​​that do not lead to confusion with data lines. 432 | 433 | So, for example to detect a prompt of type: 434 | 435 | ```[usuario@localhost ~]$ ``` 436 | 437 | It can be set: promptIni = '\[' and promptFin = '$ '. Spaces are also part of the text that must be configured. 438 | 439 | By default, the prompt found is expected to be exactly the same as the last line of the text that arrives from the terminal. But there are additional options. The type of match can be configured in the variable 'promptMatch'. It can have the following values: 440 | 441 | * prmExactly, //prompt is the whole line. 442 | * prmAtBegin, //prompt appears at the beginning of the line 443 | * prmAtEnd, //prompt appears at the end of the line 444 | * prmAtAnyPos //prompt appears anywhere on the line 445 | 446 | By default, 'promptMatch' is set to 'prmExactly'. 447 | 448 | You can also use the automatic prompt configuration function, which is executed by calling the AutoConfigPrompt() method. But this method must be called when the Pprompt is visible in the last line of the terminal. 449 | 450 | 'AutoConfigPrompt' reads the last line assuming it is the prompt and automatically sets values for 'promptIni' and 'promptFin'. 451 | 452 | You can also use a custom routine for prompt detection. This must be hooked to the OnChkForPrompt() event that has the form: 453 | 454 | function (lin: string): boolean; 455 | 456 | The event receives the line to be scanned and must return TRUE, if it is determined that the current line contains the prompt. Activating this event disables the internal detection of the unit. 457 | 458 | ## Using a Status bar 459 | 460 | Optionally, when creating the process, you can pass the reference to a panel of a Statusbar, so animated icons are displayed to indicates the states of the connection. In this case, the OnDrawPanel () event of the Statusbar must be handled. 461 | 462 | The next code use the Statusbar StatusBar1 to show animated icons representing the states of the connection. 463 | 464 | ``` 465 | p := TConsoleProc.Create(StatusBar1.Panels[1]); //Crea conexión 466 | StatusBar1.OnDrawPanel:=@SBDrawPanel; 467 | 468 | ... 469 | 470 | procedure Form1.SBDrawPanel(StatusBar:TStatusBar; Panel:TStatusPanel; const Rect:TRect); 471 | begin 472 | if panel.Index = 1 then p.DrawStatePanel(StatusBar.Canvas, Rect); 473 | end; 474 | 475 | ``` 476 | -------------------------------------------------------------------------------- /README_es.md: -------------------------------------------------------------------------------- 1 | UnTerminal 1.0 2 | ============== 3 | 4 | Por Tito Hinostroza 5 | 6 | Unidad en Lazarus, para el control de procesos tipo consola, con detección de "prompt". 7 | 8 | Esta unidad permite procesar la entrada y salida de procesos que manejen entrada y salida estándar de texto. Permite además detectar el prompt y el estado de "ocupado" y "listo". 9 | 10 | Los procesos a controlar con esta unidad deben cumplir las siguientes condiciones: 11 | 12 | 1. Que se puedan lanzar como procesos de tipo consola. 13 | 2. Que su entrada y salida estándar sea de tipo texto. 14 | 3. Que tengan prompt. (No necesario si no importa detectar el prompt). 15 | 4. Que acepten comandos (Si se quiere enviar información al proceso). 16 | 17 | Los procesos que se pueden controlar con esta unidad son diversos, como clientes de telnet, ftp, o el mismo shell del sistema operativo, como se muestra en el ejemplo incluido. 18 | 19 | En la versión actual no se puede leer el flujo de salida de errores independientemente. Solo se controlan dos flujos: 20 | 21 | 1. De entrada 22 | 2. De salida (salida estándar y de errores). 23 | 24 | Conexión 25 | -------- 26 | 27 | Para conectarse mediante un proceso, se debe crear una instancia de TConsoleProc, y seguir la secuencia de conexión: 28 | 29 | ``` 30 | p := TConsoleProc.Create(StatusBar1.Panels[1]); //Crea conexión 31 | ... 32 | p.Free; 33 | ``` 34 | 35 | Opcionalmente se le puede pasar la referencia a un panel de una barra de estado, para que se muestren íconos que indiquen el estado de la conexión (poner en NIL si no se usará). En este caso se debe manejar el evento OnDrawPanel() de la Barra de estado: 36 | 37 | ``` 38 | StatusBar1.OnDrawPanel:=@SBDrawPanel; 39 | ... 40 | procedure Form1.SBDrawPanel(StatusBar:TStatusBar; Panel:TStatusPanel; const Rect:TRect); 41 | begin 42 | if panel.Index = 1 then p.DrawStatePanel(StatusBar.Canvas, Rect); 43 | end; 44 | ``` 45 | 46 | La conexión se maneja por estados. Los estados posibles del proceso son: 47 | 48 | * ECO_STOPPED .- El Proceso no se ha iniciado. Esta condición se da siempre después de crer la conexión, o después de cerrrar una conexión abierta. Puede que haya datos pendientes en el "buffer". 49 | * ECO_CONNECTING .- Esta condición se da después de abrir la conexión con el proceso indicado. Termina cuando se detecta el prompt. Si no se detecta el prompt, (sea que no llegue, o no se haya configruado correctamente), el proceso se mantendrá siempre en este estado. 50 | * ECO_ERROR_CON .- Se produce cuando después de intentar abrir el proceso, se produce un error, por ejemplo, cuando se referencia a un archivo que no existe. 51 | * ECO_READY .- Este proceso se inicia cuando se detecta el prompt (si es que se usa la detección de prompt). Indica que el proceso está listo para aceptar comandos. Se mantiene en este estado hasta que se reciba algún comando para enviar al proceso. 52 | * ECO_BUSY .- Este estado se inicia después de mandar un comando, cuando el proceso se encontraba en estado ECO_READY. Se mantiene en este estado, hasta que se detecte el prompt y se pase nuevamente al estado ECO_READY. 53 | 54 | El proceso solo puede estar en uno de estos estados a la vez. La transición entre estados tiene una secuencia lógica, pero puede tener cambios. 55 | 56 | Una secuencia típica de estados al iniciar una conexión exitosa es: 57 | 58 | ECO_STOPPED -> ECO_CONNECTING -> ECO_READY 59 | 60 | El estado de ECO_READY indica que el proceso está listo para recibir comandos y, se detecta cuando se recibe el prompt. Por lo tanto para que se pueda considerar a un proceso como ECO_READY, se debe cumplir que tenga un prompt y que el terminal esté configurado para detectarlo. 61 | 62 | La secuencia de una conexión con error sería: 63 | 64 | ECO_STOPPED -> ECO_CONNECTING -> ... 65 | 66 | Es decir, que no se detecta el prompt, sino que probablemente, el proceso se detiene con un mensaje de error. La detección de los mensajes de error, no se hace en esta unidad, porque pueden ser muy diversos. Se recomienda implementarlos en otra unidad o derivando una clase adicional. 67 | 68 | Una vez el proceso se encuentre disponible. Un comando cualquiera, tendría el siguiente flujo: 69 | 70 | ECO_READY -> ECO_BUSY -> ECO_READY 71 | 72 | Está unidad está pensada para ser usada en conexiones lentas, y con volúmenes 73 | considerables de datos, por ello se maneja la llegada de datos completamente por eventos. 74 | 75 | Para el manejo de la pantalla usa un terminal VT100 sencillo, de la unidad TermVT. Sin 76 | embargo, esta unidad ha sido diseñada para poder recibir el texto del VT100, en un 77 | TStringList, y poder registrar permanentemente el contenido. 78 | 79 | El proceso a lanzar, se inicia con el método Open() y se termina con el método Close(). 80 | 81 | Por defecto, los saltos de línea se enviarán al proceso como el caracter LF (que es usual en conexiones de tipo Telnet). Para cambiar a CR+LF (que es usual en el entorno Windows), se debe fijar la propiedad 'sendCRLF' en TRUE. 82 | 83 | Esta unidad solo ha sido probada en Windows, pero podría funcionar también en Linux. 84 | 85 | Configurando un Editor para mostrar la salida 86 | ============================================= 87 | 88 | El objetivo del uso de un terminal es poder mostrar la salida de forma cómoda para el usuario. 89 | 90 | "UnTerminal", ha sido diseñado para manejar procesos lentos y con salida masiva de datos. Por ello la salida de datos se maneja enteramente por eventos. Además se supone que se requiere guardar un registro en pantalla, de la información que se va campturando. Por ello los eventos están orientado a manejar un objeto "TStrings", que permite ir agregando líneas nuevas e ir guardando las líneas anteriores (registro de salida). 91 | 92 | Existen diversos grupos de eventos para manejar la salida de datos. Se definen 4 métodos para el control de la salida de datos: 93 | 94 | 1. Salida como terminal VT100. 95 | 2. Salida línea por línea. 96 | 3. Salida línea por línea con línea parcial. 97 | 4. Salida línea por línea con línea parcial en prompt. 98 | 99 | Cada uno de estos métodos tiene sus ventajas y desventajas. Y se debe usar el que se adecue mejor a las necesidades de la aplicación. Así para implementar un cliente de Telnet, se debería usar el método 1 (el más completo), pero para otros procesos bastará usar métodos más simples. 100 | 101 | Podría implementarse un método adicional que consiste en interceptar directamente los eventos del terminal (propiedad term: TTermVT100) de TConsoleProc, para mostrar la información en pantalla. Sin embargo este método de trabajo, es de nivel más bajo, pero puede servir para capturar el contenido completo del terminal VT100, cada vez que se produzca un cambio (lo cual no sería muy eficiente, desde luego). 102 | 103 | Implementar la salida de datos, no afecta en la detección del prompt. Las rutinas de detección trabajan directamente sobre los bloques de datos que van llegando del proceso, sin necesidad de que estos datos se muestren. 104 | 105 | Salida como Terminal VT100 106 | -------------------------- 107 | 108 | Este es el método más completo de manejo de salida del terminal. Permite reconocer las secuencias de escape que controlan el cursor, o manipulan el texto del terminal. 109 | 110 | Se puede decir que este es el método oficial para manejo de cualquier proceso, inclusive si genera secuencias de escape ANSI. 111 | 112 | Para configurar un editor en esta forma, se deben usar los eventos: OnInitScreen(), OnRefreshLine(), OnRefreshLines() y OnAddLine(). 113 | 114 | En el siguiente código, se usa un editor SynEdit, como salida para un proceso cualquiera. 115 | 116 | ``` 117 | proc.OnInitScreen:=@procInitScreen; 118 | proc.OnRefreshLine:=@procRefreshLine; 119 | proc.OnRefreshLines:=@procRefreshLines; 120 | proc.OnAddLine:=@procAddLine; 121 | ... 122 | 123 | procedure TfrmPrincipal.procInitScreen(const grilla: TtsGrid; fIni, fFin: integer); 124 | begin 125 | for i:=fIni to fFin do SynEdit1.Lines.Add(grilla[i]); 126 | end; 127 | 128 | procedure TfrmPrincipal.procRefreshLine(const grilla: TtsGrid; fIni, HeightScr: integer); 129 | begin 130 | yvt := SynEdit1.Lines.Count-HeightScr-1; 131 | SynEdit1.Lines[yvt+fIni] := grilla[fIni]; 132 | end; 133 | 134 | procedure TfrmPrincipal.procRefreshLines(const grilla: TtsGrid; fIni, fFin, HeightScr: integer); 135 | begin 136 | yvt := SynEdit1.Lines.Count-HeightScr-1; //calcula fila equivalente a inicio de VT100 137 | for f:=fIni to fFin do SynEdit1.Lines[yvt+ f] := grilla[f]; 138 | end; 139 | 140 | procedure TfrmPrincipal.procAddLine; 141 | begin 142 | SynEdit1.Lines.Add(''); 143 | end; 144 | ``` 145 | 146 | El evento OnInitScreen(), es llamado solo una vez al inicio para dimensionar el StringList, de modo que pueda contener a todas las líneas del terminal VT100. Es necesario que el editor de salida tenga al menos la cantidad de líneas que tiene el terminal VT100 (25 por defecto), de otra forma se geenrará un error en tiempo de ejecución. Esta condición es compresible, si tenemos en cuenta que se trata de "encajar" una pantalla virtual de un termninal (que puede ser de 80 * 25 líneas) en un contenedor TString. 147 | 148 | Para posicionar el cursor virtual del terminal en alguna línea del TString, se debe hace primero el cálculo[1]: 149 | 150 | yvt := SynEdit1.Lines.Count-HeightScr-1; 151 | 152 | donde 'HeightScr' es la altura actual del terminal VT100, que es porporcionado por loe eventos de TConsoleProc. 153 | 154 | [1] Desde luego si no se quisiera guardar el registro de las líneas anteriores, no sería necesario complicarnos con los cálculos y solamente necesitaríamos tener un TString con la misma cantidad de líneas del VT100, y evitaríamos calcular la posición vertical porque sería la misma en el terminal y en el TString. 155 | 156 | Para limpiar el contenido del terminal, se debe llamar al método ClearTerminal(), que además, reinicia la posición del cursor, poniéndolo en (1,1). 157 | 158 | Llamar a ClearTerminal(), no tendrá efecto, sobre el estado de la conexión o del proceso en curso, sino solamente en el contenido del terminal. 159 | 160 | Salida Línea por Línea 161 | ---------------------- 162 | 163 | El método descrito en la sección anterior (usando los eventos OnInitScreen(), OnRefreshLine(), OnRefreshLines() y OnAddLine()), es por así decirlo, la manera formal de controlar la salida. Este método considera que el proceso puede manejar secuencias ANSI de escape para el control de la pantalla del terminal virtual. 164 | 165 | Sin embargo, este método puede resultar complicado al momento de manejar la posición del cursor o cuando se quiere conmutar desde un editor de salida a otro. 166 | 167 | Si nuestro proceso a controlar, no manejará secuencias ANSI, sino que simplemente enviará texto plano sin comandos de borrado o manejo de cursor, entonces podemos usar formas alternativas más simples de mostrar la información en pantalla. 168 | 169 | El método más simple sería usar solamente el evento OnLineCompleted(): 170 | 171 | OnLineCompleted:TEvLinCompleted; 172 | 173 | Que se genera cada vez que se detecta un salto de línea en la llegada de datos. Así podríamos usar este método para ir agregando líneas a nuestro editor de salida, sin preocuparnos en iniciar la pantalla, o de la información anterior que pueda contener. 174 | 175 | Nuestro código sería algo como esto: 176 | 177 | ``` 178 | proc.OnLineCompleted:=@procOnLineCompleted; 179 | ... 180 | 181 | procedure TForm1.procOnLineCompleted(const lin: string); 182 | begin 183 | SynEdit1.Lines.Add(lin); 184 | end; 185 | ``` 186 | 187 | Esta forma minimalista funcionará bien, mostrando los datos de llegada, pero con un aparente retraso, porque para que se muestre una línea, esta debe estar completa. De modo que cuando llegue el prompt (o una línea incompleta), esta línea no se mostrará en el editor (a pesar de que el proceso podría pasar al estado ECO_READY). 188 | 189 | El hecho de que no se muestre la última línea, no implica que no se mostrará más. Esta se hará visible al recibir el salto de línea correpsondiente, a menos que se cierre la conexión antes. 190 | 191 | Este método de captura de salida es útil cuando se requiere capturar la salida masiva de datos sin que se amuy importante la correcta visualización del prompt o líneas intermedias. 192 | 193 | Para determinar cuando se termina de recibir los datos, se puede usar la detección del prompt, si es que el proceso lo permite. 194 | 195 | Salida línea por línea con línea parcial 196 | ---------------------------------------- 197 | 198 | El método de línea por línea es simple y seguro. Pero no muestra la última línea. Para que se muestre la última línea completa, es necesario que se reciba el salto de línea correspondiente. Así podemos decir que en este modo de trabajo, no se mostrará nunca la última línea recibida (a menos claro, que el último caracter recibido sea el salto de línea y consideremos que la última línea es la anterior al salto). 199 | 200 | Para salvar este inconveniente, se puede usar la conbinación de eventos: 201 | 202 | OnLineCompleted: TEvLinCompleted; 203 | OnReadData : TEvReadData; 204 | 205 | El evento OnReadData(), se genera cuando se termina de leer un bloque de datos y por lo general, se termina con una línea final sin salto (puede ser el prompt). Entonces, lo que deberíamos hacer es completar reemplazar esta línea, si es que luego recibimos el evento OnLineCompleted(). 206 | 207 | El código de trabajo, se parecerá a este: 208 | 209 | ``` 210 | var LinPartial: boolean = false; 211 | 212 | proc.OnLineCompleted:=@procLineCompleted; 213 | proc.OnReadData:=@procReadData; 214 | ... 215 | 216 | procedure TForm1.procLineCompleted(const lin: string); 217 | begin 218 | if LinPartial then begin 219 | //Estamos en la línea del prompt 220 | Memo1.Lines[Memo1.Lines.Count-1] := lin; //reemplaza última línea 221 | LinPartial := false; 222 | end else begin //caso común 223 | Memo1.Lines.Add(lin); 224 | end; 225 | end; 226 | 227 | procedure TForm1.procReadData(nDat: integer; const lastLin: string); 228 | begin 229 | LinPartial := true; //marca bandera 230 | Memo1.Lines.Add(lastLin); //agrega la línea que contiene al prompt 231 | end; 232 | ``` 233 | 234 | La variable 'LinPartial' nos sirve para saber cuando se ha recibido una línea parcial. 235 | 236 | Este método de trabajo funcionará bastante bien y es simple, pero podría darse el caso (poco común), en el que se reciban dos veces seguidas el evento OnReadData(), haciendo que se genere una línea adicional en el editor. Este caso se podría dar cuando, se genera una línea muy larga que llegue en más de un bloque, o en conexiones muy lentas. 237 | 238 | Para evitar este efecto, se podría incluir una rutina de protección adicional que verificara que el evento OnReadData(), se está produciendo dos veces seguidas y de ser así, evitar agregar una línea más. 239 | 240 | El uso de los eventos OnLineCompleted()-OnReadData() es una forma sencilla de recbir los datos "linea por línea", pero no debemos olvidar que solo debe aplicarse a procesos con salida simple de texto sin saltos de línea o borrado de texto. La mayoría de procesos caen en esta categoría (como clientes de FTP o hasta el mismo shell de DOS), pero procesos como un cliente de Telnet o SSH, usan secuencias de escape que pueden requerir posicionar el cursor para sobreescribir bloques. 241 | 242 | En estos casos no se debería implementar este método de captura de salida; pero inclusive si se implementara aquí, podríamos tarbajar bien, mientras no se generen saltos del cursor o borrado de texto. Las secuencias de escape que cambian atributos del texto no afectan en la salida del texto, porque son procesadas (o mejor dicho ignoradas) por TConsoleProc, de modo que los eventos de salida de texto no contienen secuencias ANSI de ningún tipo, en sus parámetros. 243 | 244 | Salida línea por línea con línea parcial en Prompt 245 | -------------------------------------------------- 246 | 247 | Como una variación del método anterior, se presenta este método que es muy similar, pero con la diferencia que la detección de líneas parciales se hace solo para cuando se detecte el promtp. 248 | 249 | De esta forma, se evita generar muchas sobre-escrituras de líneas, ya que solo se hará en la línea del prompt. Este método es más eficiente cuando se tiene varios paquetes de datos entre prompt y prompt. 250 | 251 | Una desventaja de este método es que, es necesario que se tenga configurado el prompt, y este aparezca siempre al final de un bloque de datos, para que se refresque la última línea, en caso contrario no se refrescará de ninguna forma. 252 | 253 | Por lo tanto solo es recomendable para procesos que siempre muestran el prompt. No es recomendable por ejemplo, en un proceso que el algún momento mostrará un mensaje como "Ingrese un valor: ", esperando una entrada del usuario. Por lo tanto hay que ser cauteloso cuando se use este método de captura de salida. 254 | 255 | La implementación de la captura, es igual al caso anterior, solo que se usa otro par de eventos: 256 | 257 | OnLineCompleted: TEvLinCompleted; 258 | OnLinePrompt: TEvLinCompleted; 259 | 260 | El evento OnLinePrompt(), se genera cuando se recibe la línea que contiene al prompt, aunque no esté completa. Entonces, lo que deberíamos hacer es completar reemplazar esta línea, si es que luego recibimos el evento OnLineCompleted(). 261 | 262 | El código de trabajo, se parecerá a este: 263 | 264 | ``` 265 | var LinPrompt: boolean = false; 266 | 267 | proc.OnLineCompleted:=@procLineCompleted; 268 | proc.OnLinePrompt:=@procLinePrompt; 269 | ... 270 | 271 | procedure TForm1.procLineCompleted(const lin: string); 272 | begin 273 | if LinPrompt then begin 274 | //Estamos en la línea del prompt 275 | SynEdit1.Lines[SynEdit1.Lines.Count-1] := lin; //reemplaza última línea 276 | LinPrompt := false; 277 | end else begin //caso común 278 | SynEdit1.Lines.Add(lin); 279 | end; 280 | end; 281 | 282 | procedure TForm1.procLinePrompt(const lin: string); 283 | begin 284 | LinPrompt := true; //marca bandera 285 | SynEdit1.Lines.Add(lin); //agrega la línea que contiene al prompt 286 | end; 287 | ``` 288 | 289 | La variable 'LinPrompt', nos sirve para detectar cuando se ha recibido el prompt en una línea. 290 | 291 | Este método de trabajo también también puede sufrir del problema del método anterior si, es que se recibe una línea larga (donde se detecte el prompt) que viene en más de un bloque. La solución a aplicar es la misma. 292 | 293 | Aunque el efecto de este caso extremo puede no ser muy crítico, ya que solo generará una línea adicional con el prompt en el editor de salida. Esta línea adicional no quitará la legibilidad del código pero de todas formas, es una falta de fidelidad en la salida del proceso. 294 | 295 | Manejo del Terminal 296 | =================== 297 | 298 | ## Envío de comandos 299 | 300 | Los comandos (o cualquier cadena en general), se envían al proceso con los método Send(), SendLn() o SendFile(). SendLn() es similar a Send(), pero envía adicionalmente un salto de línea al final. El salto de línea es necesario, en la mayoría de procesos, para que se reconozca a la cadena enviada, como un comando. 301 | 302 | El método SendFile(), envía el contenido completo de un archivo al terminal. 303 | 304 | El salto de línea a enviar depende del valor de "LineDelimSend". 305 | 306 | Para enviar caracteres de control, se debe usar el método SendVT100Key(), porque los caracteres de control, deben convertirse primero en secuencias de escape, al menos para los aplicativos que reconozcan las secuencias de escape. Por ejemplo si se envía la tecla direccional derecha, con SendVT100Key(), primero se transformará en la secuencia ESC+[C. 307 | 308 | Para enviar simples comandos (que son secuencias de caracteres imprimibles), basta con usar SenLn(). 309 | 310 | En principio, solo debería mandarse un solo comando por SendLn() porque, enviar más de un comando podría hacer que el proceso pase repetidamente por las fases: 311 | 312 | ECO_BUSY -> ECO_READY -> ECO_BUSY ... -> ECO_READY. 313 | 314 | Haciendo que se pase de un estado de libre a ocupado de forma automática, y pudiendo complicar a alguna rutina que esté programada para enviar más comandos cuando detecte que el proceso se encuentre libre. 315 | 316 | Los datos de salida que van llegando del proceso, no se guardan completamente en la 317 | clase. Solo se mantienen las líneas de trabajo del terminal VT100 en el objeto "term". 318 | Así se ahorra memoria, porque por lo general, el texto de salida está destinado a ser almacenado en algún otro control como un editor de texto o una grilla. 319 | Es responsabilidad del programador, limitar el tamaño de los datos almacenados. 320 | 321 | Los datos de salida que llegan por el terminal, se recuperan por sondeo del flujo de salida. Por defecto, se explora la salida en intervalos de 50 milisegundos(20 veces por segundo), y usando un "buffer" interno de 2048 bytes. 322 | 323 | Para cambiar el periodo de sondeo de la salida del proceso, se debe cambiar el valor de la propiedad 'clock.interval' (en milisegundos). Se puede trabajar bien con periodos de 100 mseg o aún más, si la cantidad de información es baja. Pero no es recomendable bajar a menos de 50 mseg, porque se genera una carga adicional de CPU (aún cuando no llegen datos). Solo se debería bajar este periodo cuando se requiera procesar los datos de llegada, de forma inmediata. 324 | 325 | ## Saltos de línea al enviar 326 | 327 | Dentro de UnTerminal, se pueden configurar los caracteres de salto de línea que se usarán, tanto para el envío, como para la recepción. 328 | 329 | Para configurar los caracteres de salto de línea, en el envío, se debe usar la propiedad "LineDelimSend", que puede tomar los siguientes valores: 330 | 331 | * LDS_CRLF //Envía los caracteres CR y LF 332 | * LDS_CR //Envía solo CR (caracter #13) 333 | * LDS_LF //Envía solo LF (caracter #10) 334 | 335 | Configurar el salto de línea para envío, implica que se agregarán los caracteres configurados, cada vez que se usen los métodos TConsoleProc.SendLn o TConsoleProc.SendFile, independientemente del tipo de delimitador que se haya incluido en la cadena. Lso siguientes ejemplos, ilustrarán el conportamiento de SendLn, cuandos se configura "LineDelimSend". 336 | 337 | Si se ha definido LineDelimSend en LDS_LF, entonces: 338 | 339 | SendLn('aaa'); //Enviará realmente 'aaa'#10 340 | SendLn('aaa'#10); //Enviará realmente 'aaa'#10 341 | SendLn('aaa'#13); //Enviará realmente 'aaa'#10 342 | SendLn('aaa'#13#10); //Enviará realmente 'aaa'#10 343 | SendLn('aaa'#13#10'bbb'); //Enviará realmente 'aaa'#10'bbb'#10 344 | 345 | Como se ve, cuando se configura un caracter de salto de línea, se cambian todos los saltos de línea para que se use solo el salto de línea configurado. 346 | 347 | En general, se debe poner a "LineDelimSend" en LDS_LF, para los procesos en Linux/UNIX y se debe dejar en LDS_CRLF, para los procesos en Windows. 348 | 349 | La propiedad "LineDelimSend", no tiene efecto sobre el método TConsoleProc.Send(), que seguirá enviando siempre, los caracteres indicados. 350 | 351 | ## Saltos de línea al recibir 352 | 353 | Para configurar los caracteres de salto de línea, en la recepción, se debe usar la propiedad "LineDelimRecv", que puede tomar los siguientes valores: 354 | 355 | * LDR_CRLF //El salto de línea es CR-LF (o LF-CR) 356 | * LDR_CR //El salto de línea es este caracter. Se ignora LF 357 | * LDR_LF //El salto de línea es este caracter. Se ignora CR 358 | * LDR_CR_LF //El salto de línea es este CR o LF 359 | 360 | Cuando se configura "LineDelimRecv", se estará indicando a las rutinas de recepción, cómo es que deben interpretar los caracteres CR y LF. Si por ejemplo se configura a "LineDelimRecv" en LDR_LF, entonces cada vez que se reciba el caracter LF, se interpretará como un salto de línea, ignorando al caracter CR. 361 | 362 | En general, se debe poner a "LineDelimRecv" en LDR_LF, para los procesos en Linux/UNIX y se debe dejar en LDR_CRLF, para los procesos en Windows. 363 | 364 | El evento TTermVT100.OnLineCompleted(), se genera cuando se detecta la llegada del caracter (o caracteres) de salto de línea. Además se pasa como parámetro, a la línea actual. 365 | 366 | 367 | # Detección del Prompt 368 | 369 | La detección del Prompt se hace explorando las cadenas de texto que van llegando del proceso, para ver si coinciden con los parámetros de la detección. Esta forma puede no ser muy confiable si el Prompt del proceso es muy cambiante. 370 | 371 | Los datos de salida que van generando el proceso, se reciben en bloques que pueden tener tamaño variable, pero que no exceden a UBLOCK_SIZE. La búsqueda del prompt se hace siempre en la última línea de cada bloque de datos que se recibe del proceso (En el método ReadData()). Si el proceso debe enviar demasiada información, esta suele llegar en varios bloques, pero siempre se espera que el prompt (al menos la parte final), llegue en el último bloque recibido. No se explora cada línea recibida, para disminuir la carga de procesamiento. 372 | 373 | Para configurar la detección del Prompt se debe poner la propiedad 'detecPrompt' en TRUE y fijar valores para 'promptIni' y 'promptFin'. Estas cadenas determinan la parte inicial y final del prompt. 374 | 375 | Si el prompt es fijo y no cambia, se puede poner su valor directamente en 'promptIni' y se deja 'promptFin' vacío. Pero si el prompt es variable, se puede poner la parte inicial en 'promptIni' y la parte final en 'promptFin', pero eligiendo valores que no den lugar a confusión con líneas de datos. 376 | 377 | Así, por ejemplo para detectar un prompt de tipo: 378 | 379 | ```[usuario@localhost ~]$ ``` 380 | 381 | Se puede configurar: promptIni='[' y promptFin = '$ '. Los espacios son también parte del texto que se debe configurar. 382 | 383 | Por defecto se espera que el prompt encontrado sea exactamnente igual a la última línea del texto que llega por el terminal. Pero existen opciones adicionales. El tipo de coincidencia se puede configurar en la variable 'promptMatch'. Puede tener los siguientes valores: 384 | 385 | * prmExactly, //prompt es la línea entera 386 | * prmAtBegin, //prompt aparece al inicio de la línea 387 | * prmAtEnd, //prompt aparece al final de la línea 388 | * prmAtAnyPos //prompt aparece en cualquier parte de la línea 389 | 390 | Por defecto, 'promptMatch' está en 'prmExactly'. 391 | 392 | Tambíen se puede usar la función de configuración automática del prompt, que se ejecuta llamando al método AutoConfigPrompt. Pero este método debe ser llamado cuando se tenga el Pprompt visible en la última línea del terminal. 393 | 394 | 'AutoConfigPrompt' lee la última línea asumiendo que es el prompt y fija valores automáticamente para 'promptIni' y 'promptFin'. 395 | 396 | Se puede usar también una rutina personalizada para la detección del prompt. Esta se debe enganchar al evento OnChkForPrompt() que tiene la forma: 397 | 398 | function(lin: string): boolean; 399 | 400 | El evento recibe la línea a explorar y debe devolver TRUE, si es que se determina que la línea actual contiene al prompt. Al activar este evento, se desactiva la detección interna de la unidad. -------------------------------------------------------------------------------- /TermVT.pas: -------------------------------------------------------------------------------- 1 | { 2 | TernVT 0.6 3 | =============== 4 | Por Tito Hinostroza 09/09/2014 5 | * Se elimina el evento OnRefreshLine(). Se elimina el tipo TtsRefreshLine. 6 | * Se cambia nombre del evento OnAddLine 7 | * Se agrega el evento OnLineCompleted(), para detectar líneas agregadas completas. 8 | * Se elimina el evento OnRefreshAll(). 9 | * Se hace público "Busy", para poder controlar el estado de ocupado. 10 | 11 | Descripción 12 | ============ 13 | Define a un terminal tipo VT100, como una matriz de caracteres. Solo se implementan las 14 | secuencias de escape básicas. No se implementa opción de coloreado o atributos de texto. 15 | Los caracteres de pantalla se almacenan en el arreglo de cadenas buf[] y se trata como 16 | si fuera una matriz de cracteres. No se almacena más que la pantalla actual. 17 | 18 | El terminal se debe crear instanciando la clase TTermVT100. 19 | Los datos se esperan que lleguen en bloques, a través de AddData(). 20 | 21 | Para mostrar el contenido del terminal, se puede leer el arreglo buf[], de forma periódica, 22 | o cada vez que se genera el evento OnRefreshLines(). 23 | 24 | Pero la forma más eficiente de manejar el refresco de la pantalla es través de los 25 | eventos: OnRefreshLines() y OnScrollLines(). 26 | OnRefreshLines(), Sirven para refrescar lineas individuales o rangos de líneas, 27 | cuando hay cambios. El evento OnScrollLines(), se genera cuando hay un desplazamiento 28 | del contenido del terminal. 29 | 30 | Por Tito Hinostroza 27/06/2014 } 31 | unit TermVT; 32 | 33 | {$mode objfpc}{$H+} 34 | 35 | interface 36 | 37 | uses 38 | Classes, SysUtils, LCLProc; 39 | const 40 | MAX_HEIGHT_TS = 100; //cantidad máxima de filas 41 | MAX_WIDTH_TS = 32767; //cantidad máxima de columnas 42 | 43 | type 44 | Ttslin = string; //línea 45 | TtsGrid = array[1..MAX_HEIGHT_TS] of Ttslin; 46 | 47 | //Tipo de secuencia de escape actual 48 | tEscSequence = (EscSeqOpenBrk, //secuencia ESC[ 49 | EscSeqCharSet, //secuencias ESC( ESC) ESC* ESC+ 50 | EscSeqCommand //secuencia ESC] 51 | ); 52 | //Define el comportamiento de los caracteres de salto de línea (CR y LF) 53 | TBehaveChar = (tbcNone, //sin función, se ignora 54 | tbcNewLine, //es caracter de salto 55 | tbcNormal //es caracter normal (CR o LF) 56 | ); 57 | 58 | //tipos para eventos 59 | TtsRefreshLines = procedure(fIni, fFin: integer) of object; 60 | TtsScrollLines = procedure of object; 61 | TtsRecSysComm = procedure(info: string) of object; 62 | TtsLineCompleted= procedure(const lineCompleted: string) of object; 63 | // TCursorEvent = procedure(x,y: integer); 64 | 65 | { TTermVT100 } 66 | 67 | TTermVT100 = class 68 | public 69 | height : integer; //alto real de pantalla 70 | width : integer; //ancho real de pantalla 71 | buf : TtsGrid; //grilla de pantalla 72 | linesAdded: Integer; //líneas agregadas, después de cada llamada a AddData() 73 | Busy : boolean; //bandera de ocupado 74 | //eventos para refrescar pantalla 75 | OnRefreshLines : TtsRefreshLines; //Solicita refrescar un rango de líneas 76 | OnScrollLines : TtsScrollLines; //Indica que se ha agregado una línea al terminal 77 | //eventos adicionales 78 | OnRecSysComm : TtsRecSysComm; //Se ha recibido imformación del sistema 79 | OnLineCompleted: TtsLineCompleted; //Indica que se acaba de agregar una línea completa 80 | // OnChangeCursor: TCursorEvent; //Cambia posición del cursor 81 | ProcEscape : boolean; //Indica si se debe reconocer las secuencias de escape 82 | bhvCR : TBehaveChar; //Comportamiento de CR 83 | bhvLF : TBehaveChar; //Comportamiento de LF 84 | procedure SetCurX(AValue: integer); 85 | procedure SetCurY(AValue: integer); 86 | procedure SetCursor(x, y: integer); 87 | procedure Clear; //Limpia pantalla actual 88 | procedure AddData(const cad: PChar); 89 | private 90 | fCurX, fCurY : integer; //posición del cursor 91 | SavecurX, SavecurY: integer; //para guardar el cursor 92 | EscString : string; //para almacenar la secuencia de escape 93 | //banderas de estado 94 | InEscape : boolean; //en una secuencia de escape 95 | CurEscSeq : tEscSequence; //tipo de secuencia de escape actual 96 | minModified: Integer; //CurY mínimo que se modifica 97 | maxModified: Integer; //CurY máximo que se modifica 98 | procedure eraseChar(const n: integer); 99 | procedure eraseBack; 100 | procedure eraseBOL; 101 | procedure eraseBOS; 102 | procedure eraseEOL; 103 | procedure eraseEOS; 104 | procedure eraseLINE; 105 | procedure ExecSeqCharSet(c: char); 106 | procedure ExecSeqCommand(c: char); 107 | procedure ExecSeqOpenBrk(c: char); 108 | procedure escapeProcess(c: char); 109 | procedure Scroll; //Desplaza la pantalla, dejando la última línea en blanco 110 | procedure CursorRet; 111 | procedure CursorDown; 112 | procedure CursorRight; 113 | public 114 | function CurXY: TPoint; 115 | property CurX: integer read FCurX; 116 | property CurY: integer read FCurY; 117 | public 118 | constructor Create; //Constructor 119 | destructor Destroy; override; //Limpia los buffers 120 | end; 121 | 122 | implementation 123 | 124 | { TTermVT100 } 125 | 126 | function TTermVT100.CurXY: TPoint; 127 | //Devuelve las coordenadas del cursor. 128 | begin 129 | Result.x:=CurX; 130 | Result.y:=CurY; 131 | end; 132 | procedure TTermVT100.SetCurX(AValue: integer); 133 | begin 134 | if Avalue<1 then Avalue:=1; //protección 135 | if fCurX=AValue then Exit; //sin cambio 136 | fCurX:=AValue; 137 | //dispara evento 138 | // if OnChangeCursor<>nil then OnChangeCursor(CurX,CurY); 139 | end; 140 | procedure TTermVT100.SetCurY(AValue: integer); 141 | begin 142 | if Avalue<1 then Avalue:=1; //protección 143 | if fCurY=AValue then Exit; //sin cambio 144 | fCurY:=AValue; 145 | //dispara evento 146 | // if OnChangeCursor<>nil then OnChangeCursor(CurX,CurY); 147 | end; 148 | procedure TTermVT100.SetCursor(x,y:integer); 149 | //Fija las coordenadas del cursor 150 | begin 151 | if x<1 then x:=1; //protección 152 | if y<1 then y:=1; //protección 153 | if (CurX = x) and (CurY = y) then exit; 154 | //hubo cambio 155 | fCurX := x; 156 | fCurY := y; 157 | //dispara evento 158 | // if OnChangeCursor<>nil then OnChangeCursor(CurX,CurY); 159 | end; 160 | procedure TTermVT100.eraseLINE; 161 | //Borra la línea actual 162 | begin 163 | buf[CurY] := ''; 164 | End; 165 | procedure TTermVT100.Clear; 166 | //Llena las celdas con espacios en blanco 167 | var 168 | i: Integer; 169 | begin 170 | for i := 1 to height do 171 | buf[i] := ''; 172 | SetCursor(1,1); //Fija cursor 173 | end; 174 | procedure TTermVT100.eraseBOL; 175 | //Borra desde el inicio de la línea hasta la posición actual del cursor 176 | var 177 | i: Integer; 178 | begin 179 | //llena con espacios 180 | for i:=1 to fCurX do 181 | buf[CurY][i] := ' '; 182 | End; 183 | procedure TTermVT100.eraseEOL; 184 | //Borra desde el cursor hasta el fin de la línea 185 | begin 186 | //llena con espacios 187 | setlength(buf[CurY],CurX-1); //trunca 188 | End; 189 | procedure TTermVT100.eraseBack; 190 | //Borra desde el cursor un carcteres hacia atrás. 191 | begin 192 | if fCurX<2 then exit; //no se puede eliminar 193 | dec(fCurX); 194 | delete(buf[CurY],fCurX, 1); 195 | End; 196 | procedure TTermVT100.eraseChar(const n: integer); 197 | //Borra desde el cursor un "n" hacia adelante. 198 | begin 199 | if fCurX<2 then exit; //no se puede eliminar 200 | delete(buf[CurY],fCurX, n); 201 | End; 202 | procedure TTermVT100.eraseBOS; 203 | //Borra desde el inicio de la pantalla hasta la posición actual del cursor. 204 | var i: Integer; 205 | begin 206 | eraseBOL; //borra en línea actual 207 | If (CurY > 1) Then begin 208 | For i := 1 To CurY do 209 | buf[i] := ''; 210 | End; 211 | End; 212 | procedure TTermVT100.eraseEOS; 213 | //Borra desde el cursor hasta el fin de la pantalla 214 | var i : Integer; 215 | begin 216 | //caso especial 217 | If (curX = 1) And (curY = 1) Then begin 218 | Clear; exit; 219 | end; 220 | //caso normal 221 | eraseEOL; //borra en línea actual 222 | If (CurY <> height) Then begin 223 | For i := CurY + 1 To height do 224 | buf[i] := ''; 225 | End; 226 | End; 227 | procedure TTermVT100.Scroll; 228 | var 229 | i: Integer; 230 | begin 231 | if minModified = 1 then begin 232 | //Este es un caso extremo porque se va a perder la línea 1, que ha sido modificada. 233 | //Primero deberíamos actualizarla en la salida, por si la desea registrar. 234 | OnRefreshLines(1,1); 235 | linesAdded := -1; //para que pase a 0, cuando se incremente 236 | //ahora ya podemos desplazar 237 | end; 238 | //mueve las líneas 239 | for i := 1 to height-1 do 240 | buf[i] := buf[i+1]; 241 | //Mueve cursor 242 | // Dec(CurY); 243 | //limpia la línea final 244 | buf[height] := ''; 245 | inc(linesAdded); 246 | //dispara evento 247 | // if OnChangeCursor<>nil then OnChangeCursor(CurX,CurY); 248 | if OnScrollLines <> nil then begin 249 | OnScrollLines; //para que se agregue una línea 250 | end; 251 | //actualiza las variables de modificación 252 | dec(minModified); 253 | if minModified<1 then begin //protección 254 | minModified := 1; 255 | end; 256 | maxModified := height; //para que considere la línea agregada 257 | end; 258 | procedure TTermVT100.CursorRet; 259 | //Salta a la siguiente línea 260 | begin 261 | if CurY>=height then begin 262 | //está en la línea final 263 | Scroll; 264 | SetCursor(1,height) 265 | end else begin 266 | SetCursor(1,CurY+1) 267 | end; 268 | end; 269 | procedure TTermVT100.CursorDown; 270 | //Desplaza el cursor abajo 271 | begin 272 | if CurY>=height then begin 273 | //Está en la línea final 274 | Scroll; 275 | SetCurY(height); 276 | end else begin 277 | //caso normal 278 | SetCurY(CurY+1); 279 | end; 280 | end; 281 | procedure TTermVT100.CursorRight; 282 | //Desplaza el cursor abajo 283 | begin 284 | if CurX>=width then begin 285 | CursorRet; 286 | end else begin 287 | SetCurX(CurX+1); 288 | end; 289 | end; 290 | procedure TTermVT100.AddData(const cad: PChar); 291 | {Recibe una serie de caracteres y los agrega a la pantalla en la posición actual 292 | del terminal hasta encontrar el caracter #0. Reconoce algunas secuencias de escape, 293 | pero ignora las que cambian la apariencia del texto.} 294 | procedure CurReturn; 295 | {Ejecuta un salto de línea} 296 | var 297 | tmp: Ttslin; 298 | begin 299 | if OnLineCompleted <> nil then begin //hay evento que generar 300 | tmp := buf[CurY]; //guarda cadena que se termina de editar 301 | CursorRet; 302 | OnLineCompleted(tmp); //dispara evento 303 | end else begin //sin evento 304 | CursorRet; 305 | end; 306 | end; 307 | procedure CurMovDown; 308 | {Mueve el cursor una posición} 309 | var 310 | tmp: Ttslin; 311 | begin 312 | if OnLineCompleted <> nil then begin //hay evento que generar 313 | tmp := buf[CurY]; //guarda cadena que se termina de editar 314 | CursorDown; 315 | OnLineCompleted(tmp); //dispara evento 316 | end else begin //sin evento 317 | CursorDown; 318 | end; 319 | end; 320 | var 321 | i: Integer; 322 | largo: Integer; 323 | begin 324 | i:=0; 325 | Busy := true; 326 | linesAdded := 0; //iniica bandera 327 | minModified := CurY; //inicia 328 | maxModified := CurY; //inicia 329 | while cad[i]<>#0 do begin 330 | if ProcEscape and InEscape then begin //en modo escape 331 | escapeProcess(cad[i]); 332 | inc(i); 333 | end else begin 334 | case cad[i] of 335 | #13:begin //salto de línea CR 336 | case bhvCR of 337 | tbcNone : ; //sin acción 338 | tbcNewLine: CurReturn; 339 | tbcNormal : SetCurX(1); //retorno de carro 340 | end; 341 | inc(i); 342 | end; 343 | #10: begin //salto LF 344 | case bhvLF of 345 | tbcNone : ; //sin acción 346 | tbcNewLine: CurReturn; 347 | tbcNormal : begin //siguiente línea 348 | CurMovDown; 349 | end; 350 | end; 351 | inc(i); //ignora 352 | end; 353 | #7: begin //bell 354 | beep; 355 | inc(i); 356 | end; 357 | #8: begin //bacspace 358 | eraseBack; 359 | inc(i); 360 | end; 361 | #27: begin //secuencia de escape 362 | InEscape := true; 363 | inc(i); //pasa al siguiente caracter 364 | end; 365 | else //caracter normal 366 | //debugln(cad[i]); 367 | //procesa 368 | if CurX = length(buf[CurY])+1 then begin 369 | //este es el caso más común, escribir en siguiente caracter 370 | setlength(buf[CurY],curX); //hace crecer la cadena 371 | buf[CurY][CurX] := cad[i]; //escribe caracter 372 | end else if CurX <= length(buf[CurY]) then begin 373 | //esta antes del final de la cadena 374 | buf[CurY][CurX] := cad[i]; //escribe caracter sin temor 375 | end else begin 376 | //está más allá del final de la cadena + 1 377 | largo := length(buf[CurY]); 378 | buf[CurY]+= space(CurX-largo-1); //agrega espacios 379 | setlength(buf[CurY],curX); //hace crecer la cadena 380 | buf[CurY][CurX] := cad[i]; //escribe caracter 381 | end; 382 | // CursorRight; //mueve cursor 383 | if CurX>=width then begin //salto por límite horizontal 384 | CursorRet; 385 | end else begin 386 | SetCurX(CurX+1); 387 | end; 388 | 389 | inc(i); 390 | //actualiza la primera y última fila modificada 391 | if CurY<minModified then minModified := CurY; 392 | if CurY>maxModified then maxModified := CurY; 393 | end; 394 | end; 395 | end; 396 | //Llama a evento selectivo de refresco de pantalla 397 | if OnRefreshLines<>nil then OnRefreshLines(minModified, maxModified); 398 | Busy := false; 399 | end; 400 | procedure TTermVT100.escapeProcess(c: char); 401 | begin 402 | If EscString = '' Then begin 403 | //Es el primer caracter (después de ESC). Se ejecuta solo una vez por secuencia. 404 | CurEscSeq := EscSeqOpenBrk; //por defecto termina en alfabético 405 | Case c of 406 | //Verifica si es una secuencia de escape corta (de dos caracteres) 407 | #8: begin //embedded backspace 408 | SetCurX(curX - 1); 409 | InEscape := False; 410 | end; 411 | '7': begin //save cursor 412 | SavecurX := CurX; 413 | SavecurY := CurY; 414 | InEscape := False; 415 | end; 416 | '8': begin //restore cursor 417 | SetCursor(SavecurX, SavecurY); 418 | InEscape := False; 419 | end; 420 | 'c':; //look at VSIreset() 421 | 'D': begin //cursor down 422 | SetCurY(CurY+1); 423 | InEscape := False; 424 | end; 425 | 'E': begin //next line 426 | SetCursor(1, curY + 1); 427 | InEscape := False; 428 | end; 429 | 'H': begin //set tab 430 | Debugln('Secuencia no soportada ESC-H'); 431 | InEscape := False; 432 | end; 433 | 'I': begin //look at bp_ESC_I() 434 | InEscape := False; 435 | end; 436 | 'M': begin //cursor up 437 | SetCurY(CurY-1); 438 | InEscape := False; 439 | end; 440 | 'Z': begin //send ident 441 | InEscape := False; 442 | end; 443 | //Secuencias que terminan con otros caracteres 444 | '[':begin 445 | CurEscSeq := EscSeqOpenBrk; //termina en alfabético 446 | end; 447 | '(',')','*','+': begin 448 | CurEscSeq := EscSeqCharSet; //termina con cualquier caracter alfanumérico 449 | end; 450 | ']':begin 451 | CurEscSeq := EscSeqCommand; //termina con #7 452 | end; 453 | Else 454 | //Invalid start of escape sequence 455 | Debugln('Secuencia desconocida: ' + c); 456 | InEscape := False; 457 | Exit; 458 | End; 459 | End; 460 | 461 | //Verifica si la secuencia de escape actual temina 462 | If (CurEscSeq = EscSeqOpenBrk) and (c in ['a'..'z','A'..'Z']) Then begin //termina en alfabético 463 | //Se completó la secuencia de escape. 464 | ExecSeqOpenBrk(c); 465 | InEscape := False; 466 | EscString := ''; 467 | end else If (CurEscSeq = EscSeqCharSet) and (c in ['a'..'z','A'..'Z','0'..'9']) Then begin 468 | //Se completó la secuencia de escape. 469 | ExecSeqCharSet(c); 470 | InEscape := False; 471 | EscString := ''; 472 | end else If (CurEscSeq = EscSeqCommand) and (c = #7) Then begin //termina con #7 473 | //Se completó la secuencia de escape. 474 | ExecSeqCommand(c); 475 | InEscape := False; 476 | EscString := ''; 477 | end else begin //no termina la secuencia aún 478 | EscString += c; //acumula secuencia 479 | exit; 480 | End; 481 | end; 482 | procedure TTermVT100.ExecSeqCharSet(c: char); 483 | //Ejecuta las secuencias de escape ESC( ESC) ESC* ESC+. 484 | //"c" es el último caracter capturado. 485 | begin 486 | //Debugln('ESC:' + EscString + c); 487 | 488 | end; 489 | procedure TTermVT100.ExecSeqCommand(c: char); 490 | //Ejecuta las secuencias de escape ESC]. 491 | //"c" es el último caracter capturado. 492 | var 493 | EscString0: String; 494 | begin 495 | //Debugln('ESC:' + EscString + c); 496 | EscString0 := copy(EscString,2,length(EscString)); //quita primer caracter 497 | if copy(EscString0,1,2) = '0;' then begin //ESC ] 0; 498 | if OnRecSysComm<> nil then OnRecSysComm(copy(EscString0,3,100)); 499 | end; 500 | end; 501 | procedure TTermVT100.ExecSeqOpenBrk(c: char); 502 | //Ejecuta la secuencia de escape ESC[. "c" es el último caracter capturado. 503 | var 504 | EscString0: string; //para almacenar la secuencia de escape 505 | yDiff: Integer; 506 | xDiff: Integer; 507 | cY: Integer; 508 | cX: Integer; 509 | 510 | function GetParamN(var s: string): integer; 511 | //Extrae un parámetro numérico de la cadena 512 | var 513 | i: SizeInt; 514 | begin 515 | if s='' then exit(0); //caso cadena nula 516 | i := Pos(';', s); 517 | if i = 0 then begin 518 | Result := StrToInt(s); 519 | s := ''; 520 | end else begin 521 | Result := StrToInt(copy(s, 1, i - 1)); 522 | s := copy(s, i + 1, length(s)); 523 | end; 524 | end; 525 | 526 | begin 527 | //Debugln('ESC:' + EscString + c); 528 | EscString0 := copy(EscString,2,length(EscString)); //quita primer caracter 529 | //El último caracter, indicará el tipo de comando. 530 | Case c of 531 | 'A': begin // A ==> move cursor up 532 | yDiff := GetParamN(EscString0); 533 | If yDiff = 0 Then yDiff := 1; 534 | SetCurY(curY - yDiff); 535 | end; 536 | 'B': begin // B ==> move cursor down 537 | yDiff := GetParamN(EscString0); 538 | If yDiff = 0 Then yDiff := 1; 539 | SetCurY(curY + yDiff); 540 | end; 541 | 'C': begin // C ==> move cursor right 542 | xDiff := GetParamN(EscString0); 543 | If xDiff = 0 Then xDiff := 1; 544 | SetCurX(curX + xDiff); 545 | end; 546 | 'D': begin // D ==> move cursor left 547 | xDiff := GetParamN(EscString0); 548 | If xDiff = 0 Then xDiff := 1; 549 | SetCurX(curX - xDiff); 550 | end; 551 | 'H','f': begin //Goto cursor position indicated by escape sequence 552 | if (EscString0='') or (EscString0=';') then begin 553 | SetCursor(1, 1); 554 | end else begin //coordinates indicated 555 | cY := GetParamN(EscString0); 556 | cX := StrToInt(EscString0); 557 | SetCursor(cX, cY); 558 | end; 559 | end; 560 | 'J': begin //Erase screen 561 | if EscString0='' then begin 562 | eraseEOS; 563 | end else begin 564 | Case StrToInt(EscString0) of 565 | 0: eraseEOS; //Borrar hasta el final de la pantalla 566 | 1: eraseBOS; //Borra pantalla antes del cursor 567 | 2: Clear; 568 | End; 569 | end; 570 | end; 571 | 'K': begin //Erase line 572 | if EscString0='' then begin 573 | eraseEOL; 574 | end else begin 575 | Case STrToInt(EscString0) of 576 | 0: eraseEOL; //borra hasta el final de la línea 577 | 1: eraseBOL; //borra hasta el cursor 578 | 2: eraseLINE; 579 | End; 580 | end; 581 | end; 582 | 'P': begin //ESC[ Pn P Delete Pn characters, to left 583 | //Debugln(EscString+c); 584 | yDiff := GetParamN(EscString0); 585 | eraseChar(yDiff); 586 | end; 587 | 'g': begin //clear tabs 588 | // Dim tY As Integer 589 | Debugln('Secuencia no soportada ESC-g'); 590 | // For tY = 0 To 19 591 | // tab_table(tY) = 0 592 | // Next tY 593 | end; 594 | 'h': begin //Set mode 595 | end; 596 | 'i': begin // print mode 597 | end; 598 | 'l': begin //Reset mode 599 | end; 600 | 'm': begin //text attributes sequence 601 | end; 602 | 'r': begin //scrolling region 603 | Debugln('Secuencia no soportada ESC-r'); 604 | end; 605 | 's': begin //Save cursor position 606 | SavecurX := CurX; 607 | SavecurY := CurY; 608 | end; 609 | 'u': begin //restore cursor position 610 | SetCursor(SavecurX, SavecurY); 611 | end; 612 | Else 613 | Debugln(EscString+c); 614 | End; 615 | end; 616 | constructor TTermVT100.Create; 617 | var 618 | i: Integer; 619 | begin 620 | //limpia las líneas 621 | for i := 1 to MAX_HEIGHT_TS do 622 | buf[i] := ''; 623 | SetCursor(1,1); 624 | EscString := ''; 625 | //tamaño por defecto 626 | width := 120; 627 | height := 25; 628 | Clear; //limpia 629 | ProcEscape := true; //para que reconozca (no necesariamente ejecutarlas) las secuencias de escape 630 | bhvCR := tbcNewLine; 631 | bhvLF := tbcNone; 632 | //inicia bandera de ocupado 633 | Busy := false; 634 | end; 635 | destructor TTermVT100.Destroy; 636 | begin 637 | inherited Destroy; 638 | end; 639 | 640 | end. 641 | 642 | -------------------------------------------------------------------------------- /UnTerminal.pas: -------------------------------------------------------------------------------- 1 | { 2 | UnTerminal 1.0 3 | =============== 4 | Por Tito Hinostroza 02/10/2020 5 | 6 | Description 7 | =========== 8 | Lazarus Unit for controlling console process, with Prompt Detection. 9 | 10 | This unit can process the standard input/output of console process, and support ANSI 11 | escape sequences, using a virtual VT100 terminal. It includes 12 | routines for detect the prompt, and consequently the states of BUSY and READY. 13 | 14 | In the current version it's not supported to read the standard error stream. 15 | 16 | For to start a process it's necessary to create an object TConsoleProc: 17 | 18 | p := TConsoleProc.Create(StatusBar1.Panels[1]); 19 | ... 20 | p.Free; 21 | } 22 | unit UnTerminal; 23 | 24 | {$mode objfpc}{$H+} 25 | interface 26 | uses Classes, SysUtils, Process, ExtCtrls, Dialogs, Graphics, ComCtrls, 27 | LCLProc, LCLType, TermVT, types, Strutils; 28 | const 29 | UBLOCK_SIZE = 2048; //Tamaño de bloque de lectura de salida de proceso 30 | 31 | type 32 | //Posibles estados de la conexión 33 | TEstadoCon = ( 34 | ECO_CONNECTING, //Iniciado y Conectando 35 | ECO_ERROR_CON, //Iniciado y Con error de conexión 36 | ECO_BUSY, //Iniciado y conectado, pero ejecutando algún proceso 37 | ECO_READY, //Iniciado y conectado, libre para aceptar comandos. 38 | ECO_STOPPED //Proceso no iniciado. Puede que haya datos pendientes en el "buffer" 39 | ); 40 | //Tipos de reconocimiento del prompt en una línea 41 | TPrompMatch = ( 42 | prmExactly, //prompt es la línea entera 43 | prmAtBegin, //prompt aparece al inicio de la línea 44 | prmAtEnd, //prompt aparece al final de la línea 45 | prmAtAnyPos //prompt aparece en cualquier parte de la línea 46 | ); 47 | 48 | //Tipo de delimitador de línea a enviar 49 | TUtLineDelSend = ( 50 | LDS_CRLF, //Envía los caracteres CR y LF 51 | LDS_CR, //Envía solo CR 52 | LDS_LF //Envía solo LF 53 | ); 54 | //Tipo de delimitador de línea a recibir 55 | TUtLineDelRecv = ( 56 | LDR_CRLF, //El salto de línea es CR-LF (o LF-CR) 57 | LDR_CR, //El salto de línea es este caracter. Se ignora LF 58 | LDR_LF, //El salto de línea es este caracter. Se ignora CR 59 | LDR_CR_LF //El salto de línea es este CR o LF 60 | ); 61 | 62 | {Evento. Pasa la cantidad de bytes que llegan y la columna y fila final de la matriz Lin[] } 63 | TEvProcState = procedure(nDat: integer; pFinal: TPoint) of object; 64 | TEvReadData = procedure(nDat: integer; const lastLine: string) of object; 65 | TEvGetPrompt = procedure(prmLine: string; pIni: TPoint; HeightScr: integer) of object; 66 | TEvChkForPrompt = function(const lin: string): boolean of object; 67 | TEvLinCompleted = procedure(const lin: string) of object; 68 | TEvRecSysComm = procedure(info: string; pIni: TPoint) of object; 69 | 70 | TEvRefreshAll = procedure(const grilla: TtsGrid) of object; 71 | TEvInitScreen = procedure(const grilla: TtsGrid; fIni, fFin: integer) of object; 72 | TEvRefreshLine = procedure(const grilla: TtsGrid; fIni, HeightScr: integer) of object; 73 | TEvRefreshLines= procedure(const grilla: TtsGrid; fIni, fFin, HeightScr: integer) of object; 74 | TEvAddNewLine = procedure(HeightScr: integer) of object; 75 | 76 | { TConsoleProc } 77 | //Clase que define un proceso 78 | TConsoleProc = class 79 | private 80 | bolsa : array[0..UBLOCK_SIZE] of char; //buffer para almacenar salidas(tiene un caracter más) 81 | nLeidos : LongInt; 82 | lstTmp : TStringList; 83 | 84 | cAnim : integer; //Contador para animación de ícono de estado 85 | angA : integer; //Contador para animación de ícono de estado 86 | procedure SetLineDelimRecv(AValue: TUtLineDelRecv); 87 | procedure RefreshConnection(Sender: TObject); //Refresca la conexión 88 | function ChangeState(estado0: TEstadoCon): boolean; //Cambia el State actual 89 | private //Auxiliar variables and methods, used by RunInLoop 90 | LoopList: TStringList; //Lista de salida para cuando se usa RunInLoop(). 91 | outList: TStringList; //Lista de salida para cuando se usa RunInLoop(). 92 | LinPartial: boolean; //Bandar 93 | procedure ProcLoop(const lin: string); 94 | procedure DoLineCompleted(const lin: string); 95 | procedure DoReadData(nDat: integer; const lastLine: string); 96 | protected 97 | panel : TStatusPanel; //referencia a panel para nostrar estado 98 | curPanel : TStatusPanel; //para nostrar posición de cursor de editor de salida 99 | lastState : TEstadoCon; //Estado anterior 100 | txtState : string; //Cadena que describe el estado actual de la conexión 101 | clock : TTimer; //temporizador para leer salida del proceso 102 | FLineDelimSend: TUtLineDelSend; 103 | FLineDelimRecv: TUtLineDelRecv; 104 | function ContainsPrompt(const linAct: string; var pos1, pos2: integer; 105 | posIni: integer=1): boolean; 106 | function ContainsPromptL(const linAct: string; var pos1, pos2: integer 107 | ): boolean; 108 | function EsPrompt(const cad: string): boolean; 109 | function GetTerminalWidth: integer; 110 | procedure SetTerminalWidth(AValue: integer); 111 | function DoReadData: boolean; 112 | //respuesta a eventos de term 113 | procedure termAddLine; 114 | procedure termRefreshLines(fIni, fFin: integer); 115 | procedure termRecSysComm(info: string); 116 | procedure termLineCompleted(const lineCompleted: string); 117 | public //Events 118 | //Change state events. 119 | OnConnecting : TEvProcState; //indica que se inicia el proceso y trata de conectar 120 | OnBusy : TEvProcState; //indica que está esperando prompt 121 | OnStopped : TEvProcState; //indica que se terminó el proceso 122 | OnGetPrompt : TEvGetPrompt; //indica que llegó el prompt 123 | OnChangeState: TEvRecSysComm; //cambia de estado 124 | //Arriving data events. 125 | OnRefreshAll : TEvRefreshAll; //Para refrescar todo el contenido del terminal. No recomendable. 126 | OnInitScreen : TEvInitScreen; //indica que se debe agregar líneas de texto 127 | OnRefreshLine : TEvRefreshLine; //indica que se deben refrescar una línea 128 | OnRefreshLines: TEvRefreshLines; //indica que se deben refrescar un grupo de líneas 129 | OnAddLine : TEvAddNewLine; //inidca que se debe agregar una línea a la salida 130 | //Optional arriving data events. 131 | OnLineCompleted:TEvLinCompleted; {Cuando se ha terminado de escribir una línea en el terminal. 132 | No funcionará si es que se producen saltos en el cursor} 133 | OnLinePrompt : TEvLinCompleted; //Cuando llega la línea del prompt 134 | //Aditional events. 135 | OnChkForPrompt: TEvChkForPrompt; //Permite incluir una rutina externa para verificación de prompt. 136 | OnFirstReady : TEvGetPrompt; //La primera vez que de detcta el prompt 137 | OnReadData : TEvReadData; //Cuando llega una trama de datos por el terminal 138 | OnRecSysComm : TEvRecSysComm; {indica que llegó información del sistema remoto (usuario, 139 | directorio actual, etc) Solo para conex. Telnet} 140 | public 141 | //datos del proceso 142 | State : TEstadoCon; //Estado de la conexión 143 | ClearOnOpen : boolean; //Para limpiar pantalla al llamar a Open() 144 | p : TProcess; //el proceso a manejar 145 | //manejo del prompt 146 | detecPrompt: boolean; //activa la detección de prompt. 147 | promptIni : string; //cadena inicial del prompt 148 | promptFin : string; //cadena final del prompt 149 | promptMatch: TPrompMatch; //tipo de coincidencia 150 | HayPrompt : boolean; //bandera, indica si se detectó el prompt en la última línea 151 | 152 | msjError : string; //guarda el mensaje de error 153 | term : TTermVT100; //Terminal 154 | property LineDelimSend: TUtLineDelSend read FLineDelimSend write FLineDelimSend; //Tipo de delimitador de línea 155 | property LineDelimRecv: TUtLineDelRecv read FLineDelimRecv write SetLineDelimRecv; //Tipo de delimitador de línea para recibir 156 | procedure Start; //inicia proceso 157 | procedure Open(progPath, progParam: string); //Inicia conexión 158 | function Close: boolean; //Termina la conexión 159 | procedure ClearTerminal; 160 | property TerminalWidth: integer read GetTerminalWidth write SetTerminalWidth; 161 | procedure Send(const txt: string); 162 | procedure SendLn(txt: string); //Envía datos por el "stdin" 163 | procedure SendFile(name: string); //Envía el contenido de un archivo 164 | procedure SendVT100Key(var Key: Word; Shift: TShiftState); //Envía una tecla con secuencia de escape 165 | function LastLine: string; inline; //devuelve la última línea 166 | procedure AutoConfigPrompt; virtual; 167 | public //Execution without TTimer. 168 | function Loop(TimeoutSegs: integer = - 1; ldelay: integer = 50): boolean; 169 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer = -1): boolean; 170 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer; 171 | var progOut: TStringList): boolean; 172 | function RunInLoop(progPath, progParam: string; TimeoutSegs: integer; out 173 | outText: String): boolean; 174 | public //Statusbar control 175 | procedure RefStatePanel; 176 | procedure DrawStatePanel(c: TCanvas; const Rect: TRect); virtual; 177 | public //Initialization 178 | constructor Create(PanControl: TStatusPanel); virtual; //Constructor 179 | destructor Destroy; override; //Limpia los buffers 180 | end; 181 | 182 | implementation 183 | //uses FormConfig; //se necesita acceder a las propiedades de prompt 184 | const 185 | STA_NAME_CONNEC = 'Connecting'; 186 | STA_NAME_ERR_CON = 'Connection Error'; 187 | STA_NAME_BUSY = 'Busy'; 188 | STA_NAME_READY = 'Ready'; 189 | STA_NAME_STOPPED = 'Stopped'; 190 | MSG_ERR_NO_APP_DEF = 'No Application specified for connection.'; 191 | MSG_FAIL_START_APP = 'Fail Starting Application: '; 192 | MSG_NO_PRMP_FOUND = 'Prompt Not Found for to configure in Terminal.'; 193 | MSG_ERR_TIMEOUT = 'Timeout in process.'; 194 | { 195 | STA_NAME_CONNEC = 'Conectando'; 196 | STA_NAME_ERR_CON = 'Error en conexión'; 197 | STA_NAME_BUSY = 'Ocupado'; 198 | STA_NAME_READY = 'Disponible'; 199 | STA_NAME_STOPPED = 'Detenido'; 200 | MSG_ERR_NO_APP_DEF = 'No se especificó aplicativo para conexión.'; 201 | MSG_FAIL_START_APP = 'Fallo al iniciar aplicativo: '; 202 | MSG_NO_PRMP_FOUND = 'No se encuentra un prompt en el terminal para configurarlo.'; 203 | //} 204 | 205 | function Explode(delimiter:string; str:string):TStringDynArray; 206 | var 207 | p,cc,dsize:integer; 208 | begin 209 | cc := 0; 210 | dsize := length(delimiter); 211 | while true do begin 212 | p := pos(delimiter,str); 213 | if p > 0 then begin 214 | inc(cc); 215 | setlength(result,cc); 216 | result[cc-1] := copy(str,1,p-1); 217 | delete(str,1,p+dsize-1); 218 | end else break; 219 | end; 220 | inc(cc); 221 | setlength(result,cc); 222 | result[cc-1] := str; 223 | end; 224 | function TConsoleProc.ChangeState(estado0: TEstadoCon): boolean; 225 | {Cambia el estado de la conexión y actualiza un panel con información sobre el estado} 226 | begin 227 | lastState := State; //pasa State actual a anterior 228 | State := estado0; //fija State actual 229 | if lastState <> State then begin //indica si hubo cambio 230 | //hubo cambio de State 231 | Result := true; 232 | case State of 233 | ECO_CONNECTING: begin 234 | txtState := STA_NAME_CONNEC; 235 | RefStatePanel; //fuerza a redibujar panel con el nuevo State 236 | if OnConnecting<>nil then OnConnecting(0,term.CurXY); 237 | end; 238 | ECO_ERROR_CON: begin 239 | txtState := STA_NAME_ERR_CON; 240 | RefStatePanel; //fuerza a redibujar panel con el nuevo State 241 | // if OnErrorConex <> nil then OnErrorConex(nLeidos, pErr); 242 | end; 243 | ECO_BUSY: begin 244 | txtState := STA_NAME_BUSY; 245 | RefStatePanel; //fuerza a redibujar panel con el nuevo State 246 | if OnBusy <> nil then OnBusy(nLeidos, term.CurXY); 247 | end; 248 | ECO_READY: begin 249 | txtState := STA_NAME_READY; 250 | RefStatePanel; //fuerza a redibujar panel con el nuevo State 251 | if OnGetPrompt <> nil then OnGetPrompt(LastLine, term.CurXY, term.height); 252 | end; 253 | ECO_STOPPED: begin 254 | txtState := STA_NAME_STOPPED; 255 | RefStatePanel; //fuerza a redibujar panel con el nuevo State 256 | if OnStopped <> nil then OnStopped(nLeidos, term.CurXY); 257 | end; 258 | end; 259 | if OnChangeState<>nil then OnChangeState(txtState, term.CurXY); 260 | end; 261 | end; 262 | function TConsoleProc.LastLine: string; inline; 263 | //Devuelve la línea donde se encuentra el cursor. Salvo que haya, saltos en el cursor, 264 | //devolverá siempre los últimos caracteres recibidos. 265 | begin 266 | Result := term.buf[term.CurY]; 267 | end; 268 | function TConsoleProc.GetTerminalWidth: integer; 269 | //Devuelve el ancho del terminal 270 | begin 271 | Result := term.width; 272 | end; 273 | procedure TConsoleProc.SetTerminalWidth(AValue: integer); 274 | //Fija el ancho del terminal 275 | begin 276 | if term.width=AValue then Exit; 277 | term.width := AValue; 278 | end; 279 | procedure TConsoleProc.Start; 280 | {Inicia el proceso y verifica si hubo error al lanzar el proceso. Los parámetros del 281 | proceso, deben haberse fijado antes en el proceso.} 282 | begin 283 | //ejecutamos 284 | ChangeState(ECO_CONNECTING); //importante para 285 | try 286 | p.Execute; 287 | if not p.Running then begin 288 | //Falló al iniciar 289 | ChangeState(ECO_STOPPED); 290 | Exit; 291 | end; 292 | //Se inició, y esperamos a que RefreshConnection() procese los datos recibidos 293 | except 294 | if trim(p.Executable) = '' then 295 | msjError := MSG_ERR_NO_APP_DEF 296 | else 297 | msjError := MSG_FAIL_START_APP + p.Executable; 298 | ChangeState(ECO_ERROR_CON); //genera evento 299 | end; 300 | end; 301 | procedure TConsoleProc.Open(progPath, progParam: string); 302 | //Rutina principal para iniciar un programa. 303 | begin 304 | term.Clear; 305 | if trim(progPath) = '' then exit; //protección 306 | //Inicia la salida de texto, refrescando todo el terminal 307 | if ClearOnOpen then ClearTerminal; 308 | if p.Running then p.Terminate(0); 309 | // Vamos a lanzar el proceso 310 | p.CommandLine := progPath + ' ' + progParam; 311 | // p.Executable := progPath; 312 | // p.Parameters.Clear; 313 | // p.Parameters.Add(progParam); 314 | 315 | // Definimos comportamiento de 'TProccess'. Es importante direccionar los errores. 316 | p.Options := [poUsePipes, poStderrToOutPut, poNoConsole]; 317 | Start; //puede dar error 318 | end; 319 | function TConsoleProc.Close: boolean; 320 | //Cierra la conexión actual. Si hay error devuelve False. 321 | var c: integer; 322 | begin 323 | Result := true; 324 | //verifica el proceso 325 | if p.Running then p.Terminate(0); 326 | //espera hasta 100 mseg 327 | c := 0; 328 | while p.Running and (c<20) do begin 329 | sleep(5); 330 | inc(c); 331 | end; 332 | if c>= 20 then exit(false); //sale con error 333 | //Pasa de Runnig a Not Running 334 | ChangeState(ECO_STOPPED); 335 | //Puede que quede datos en el "stdout" 336 | DoReadData; //lee lo que queda 337 | end; 338 | procedure TConsoleProc.ClearTerminal; 339 | {Reinicia el terminal iniciando en (1,1) y limpiando la grilla} 340 | begin 341 | term.Clear; //limpia grilla y reinicia cursor 342 | //genera evento para reiniciar salida 343 | if OnInitScreen<>nil then OnInitScreen(term.buf, 1, term.height); 344 | end; 345 | function TConsoleProc.ContainsPrompt(const linAct: string; var pos1, pos2: integer; 346 | posIni: integer = 1): boolean; 347 | //Verifica si una cadena de texto contiene al prompt, usando los valores actuales 348 | //de promptIni y promptFin. 349 | //Si la cadena contiene al prompt, devuelve TRUE y actualiza los valores pos1 y pos2 350 | //que son los límites inicial y final del prompt, dentro de la cadema. 351 | //posIni, es la posición inicial (inclusivo) desde donde se buscará. 352 | //Si la salida del proceso va a ir a un editor con resaltador de sintaxis, esta rutina debe 353 | //ser similar a la del resaltador para que haya sincronía en lo que se ve. No se separra esta 354 | //rutina en otra unidad para que esta unidad no tenga dependencias y se pueda usar como 355 | //librería. Además la detección del prompt para el proceso, es diferente de la deteción 356 | //para un resaltador de sintaxis. 357 | var 358 | lar: Integer; 359 | begin 360 | Result := FALSE; //valor por defecto 361 | lar := length(promptIni); 362 | pos1 := posEx(promptIni, linAct, posIni); 363 | if (lar>0) and (pos1>0) then begin 364 | //puede ser 365 | if promptFin = '' then begin 366 | //no hace falta validar más 367 | pos2:=pos1+lar-1; //límite final 368 | Result := true; 369 | exit; //no hace falta explorar más 370 | end; 371 | //hay que validar la existencia del fin del prompt 372 | pos2 :=posEx(promptFin,linAct, posIni); 373 | if pos2>0 then begin //encontró 374 | pos2 := pos2 + length(promptFin)-1; 375 | Result := true; 376 | exit; 377 | end; 378 | end; 379 | end; 380 | function TConsoleProc.ContainsPromptL(const linAct: string; var pos1, pos2: integer): boolean; 381 | //Similar a ContainsPrompt(), pero devuelve la última ocurrencia. 382 | var 383 | p1,p2: Integer; 384 | hay: Boolean; 385 | begin 386 | hay := ContainsPrompt(linAct, p1, p2, 1); 387 | if not hay then exit(false); //no existe 388 | //existe el prompt, busca otro más adelante 389 | repeat 390 | pos1 := p1; pos2 := p2; //guarda valores 391 | hay := ContainsPrompt(linAct, p1, p2, p1+1); 392 | until not hay; 393 | exit(true); //hay valores 394 | end; 395 | function TConsoleProc.EsPrompt(const cad: string): boolean; 396 | //Indica si la línea dada, es el prompt, de acuerdo a los parámetros dados. Esta función 397 | //se pone aquí, porque aquí se tiene fácil acceso a las configuraciones del prompt. 398 | var 399 | pos2: integer; 400 | pos1: integer; 401 | begin 402 | if detecPrompt then begin //si hay detección activa 403 | Result := false; 404 | //contiene al prompt, pero hay que ver la posición 405 | case promptMatch of 406 | prmExactly : begin 407 | if not ContainsPrompt(cad, pos1, pos2) then exit; 408 | if (pos1 = 1) and (pos2=length(cad)) then exit(true); 409 | end; 410 | prmAtBegin : begin 411 | if not ContainsPrompt(cad, pos1, pos2) then exit; 412 | if (pos1 = 1) then exit(true); 413 | end; 414 | prmAtEnd : begin 415 | if not ContainsPromptL(cad, pos1, pos2) then exit; 416 | if (pos2=length(cad)) then exit(true); 417 | end; 418 | prmAtAnyPos: begin 419 | if not ContainsPrompt(cad, pos1, pos2) then exit; 420 | exit(true); 421 | end; 422 | end; 423 | end else begin 424 | Result := false; 425 | end; 426 | end; 427 | function TConsoleProc.DoReadData: boolean; 428 | {Verifica la salida del proceso. Si llegan datos los pasa a "term" y devuelve TRUE. 429 | Lee en un solo bloque si el tamaño de los datos, es menor que UBLOCK_SIZE, en caso 430 | contrario lee varios bloques. Actualiza "nLeidos", "HayPrompt". } 431 | var nDis : longint; 432 | nBytes : LongInt; 433 | begin 434 | // pIni := LeePosFin; 435 | Result := false; //valor por defecto 436 | nLeidos := 0; 437 | HayPrompt := false; 438 | if P.Output = nil then exit; //no hay cola 439 | repeat 440 | //vemos cuantos bytes hay "en este momento" 441 | nDis := P.Output.NumBytesAvailable; 442 | if nDis = 0 then break; //sale del lazo 443 | if nDis < UBLOCK_SIZE then begin 444 | //leemos solo los que hay, sino se queda esperando 445 | nBytes := P.Output.Read(bolsa, nDis); 446 | bolsa[nBytes] := #0; //marca fin de cadena 447 | term.AddData(@bolsa); //puede generar eventos 448 | nLeidos += nBytes; 449 | end else begin 450 | {Leemos bloque de UBLOCK_SIZE bytes. bolsa[] tiene en realidad un tamaño de 451 | UBLOCK_SIZE+1, así que dejará al menos un byte libre, para poner 0x00} 452 | nBytes := P.Output.Read(bolsa, UBLOCK_SIZE); 453 | bolsa[nBytes] := #0; //marca fin de cadena 454 | term.AddData(@bolsa); //puede generar eventos 455 | nLeidos += nBytes; 456 | end; 457 | {aquí también se puede detetar el prompt, con más posibilidad de detectar los 458 | posibles "Prompt" intermedios} 459 | Result := true; //hay datos 460 | until not P.Running or (nBytes = 0); 461 | if not Result then exit; 462 | {Terminó de leer, aquí detectamos el prompt, porque es casi seguro que llegue 463 | al final de la trama. 464 | Ver si la línea actual, es realmente el prompt, es la forma más segura. Se probó 465 | viendo si la línea actual empezaba con el prompt, pero daba casos (sobretodo en 466 | conexiones lentas) en que llegaba una trama con pocos caracteres, de modo que se 467 | generaba el evento de llegada de prompt dos veces (tal vez más) en una misma línea} 468 | if OnChkForPrompt <> nil then begin 469 | //Hay rutina de verificación externa 470 | HayPrompt := OnChkForPrompt(LastLine); 471 | end else begin 472 | if EsPrompt(LastLine) then 473 | HayPrompt:=true; 474 | end; 475 | if OnReadData<>nil then OnReadData(nLeidos, LastLine); 476 | if HayPrompt then begin 477 | //Genera el evento. Este evento se generará siempre que se detecte el prompt en la 478 | //última línea sin ver el estado: El cambio de estado es otro procesamiento. 479 | if OnLinePrompt<>nil then OnLinePrompt(LastLine); 480 | end; 481 | end; 482 | procedure TConsoleProc.RefreshConnection(Sender: TObject); 483 | {Refresca el estado de la conexión. Verifica si hay datos de salida del proceso, para 484 | generar los eventos respectivos que capturan la salida. Es llamado autométicamente 485 | por un Timer, cuando está disponible, pero en aplicaciones de consola, puede que sea 486 | necesario llamarlo manualmente, o usar el método } 487 | begin 488 | if State = ECO_STOPPED then Exit; //No está corriendo el proceso. 489 | if p.Running then begin 490 | //Se está ejecutando 491 | if DoReadData then begin //actualiza "HayPrompt" 492 | if State in [ECO_READY, ECO_BUSY] then begin 493 | if HayPrompt then begin 494 | ChangeState(ECO_READY); 495 | end else begin 496 | ChangeState(ECO_BUSY); 497 | end; 498 | end else begin 499 | //Se está esperando conseguir la conexión (State = ECO_CONNECTING) 500 | //Puede que se detenga aquí con un mensaje de error en lugar del prompt 501 | if HayPrompt then begin 502 | //se consiguió conectar por primera vez 503 | if OnFirstReady<>nil then OnFirstReady('',term.CurXY, term.height); 504 | // State := ECO_READY; //para que pase a ECO_BUSY 505 | // SendLn(COMAN_INIC); //envía comandos iniciales (lanza evento Ocupado) 506 | ChangeState(ECO_READY); 507 | end; 508 | end; 509 | end; 510 | end else begin //terminó 511 | ChangeState(ECO_STOPPED); 512 | DoReadData; //lee por si quedaban datos en el buffer 513 | end; 514 | //actualiza animación 515 | inc(cAnim); 516 | if (cAnim mod 4) = 0 then begin 517 | if State in [ECO_CONNECTING, ECO_BUSY] then begin //estados de espera 518 | inc(angA);if angA>7 then angA:=0; 519 | RefStatePanel; 520 | end; 521 | cAnim := 0; 522 | end; 523 | end; 524 | procedure TConsoleProc.Send(const txt: string); 525 | {Envía una cadena como como flujo de entrada al proceso. 526 | Es importante agregar el caracter #13#10 al final. De otra forma no se leerá el "stdin"} 527 | begin 528 | if p = NIL then exit; 529 | if not p.Running then exit; 530 | p.PipeBufferSize:=20000; 531 | // p.Input.Size:=20000; 532 | p.Input.Write(txt[1], length(txt)); //pasa el origen de los datos 533 | 534 | //Para que se genere un cambio de State aunque el comando sea muy corto 535 | if State = ECO_READY then ChangeState(ECO_BUSY); 536 | end; 537 | procedure TConsoleProc.SendLn(txt: string); 538 | {Envía un comando al proceso. Incluye el salto de línea al final de la línea. 539 | También puede recibir cadneas de varias líneas} 540 | begin 541 | //reemplaza todos los saltos por #1 542 | txt := StringReplace(txt,#13#10,#1,[rfReplaceAll]); 543 | txt := StringReplace(txt,#13,#1,[rfReplaceAll]); 544 | txt := StringReplace(txt,#10,#1,[rfReplaceAll]); 545 | //incluye el salto final 546 | txt += #1; 547 | //Aplica el salto configurado 548 | case FLineDelimSend of 549 | LDS_CRLF: txt := StringReplace(txt,#1,#13#10,[rfReplaceAll]); //envía CRLF 550 | LDS_CR : txt := StringReplace(txt,#1,#13,[rfReplaceAll]); //envía CR 551 | LDS_LF : txt := StringReplace(txt,#1,#10,[rfReplaceAll]); //envía LF 552 | end; 553 | Send(txt); 554 | end; 555 | procedure TConsoleProc.SendFile(name: string); 556 | //Envía el contendio completo de un archivo 557 | var lins: TstringList; 558 | lin: String; 559 | begin 560 | lins:= TstringList.Create; 561 | if not FileExists(name) then exit; 562 | lins.LoadFromFile(name); 563 | for lin in lins do 564 | SendLn(lin); 565 | lins.Free; 566 | end; 567 | procedure TConsoleProc.SendVT100Key(var Key: Word; Shift: TShiftState); 568 | //Envía una tecla de control (obtenida del evento KeyDown), realizando primero 569 | //la transformación a secuencias de escapa. 570 | begin 571 | case Key of 572 | VK_END : begin 573 | if Shift = [] then Send(#27'[K'); 574 | end; 575 | VK_HOME : begin 576 | if Shift = [] then Send(#27'[H'); 577 | end; 578 | VK_LEFT : begin 579 | if Shift = [] then Send(#27'[D'); 580 | end; 581 | VK_RIGHT: begin 582 | if Shift = [] then Send(#27'[C'); 583 | end; 584 | VK_UP : begin 585 | if Shift = [] then Send(#27'[A'); 586 | end; 587 | VK_DOWN : begin 588 | if Shift = [] then Send(#27'[B'); 589 | end; 590 | VK_F1 : begin 591 | if Shift = [] then Send(#27'OP'); 592 | end; 593 | VK_F2 : begin 594 | if Shift = [] then Send(#27'OQ'); 595 | end; 596 | VK_F3 : begin 597 | if Shift = [] then Send(#27'OR'); 598 | end; 599 | VK_F4 : begin 600 | if Shift = [] then Send(#27'OS'); 601 | end; 602 | VK_BACK : begin 603 | if Shift = [] then Send(#8); //no transforma 604 | end; 605 | VK_TAB : begin 606 | if Shift = [] then Send(#9); //no transforma 607 | end; 608 | VK_A..VK_Z: begin 609 | if Shift = [ssCtrl] then begin //Ctrl+A, Ctrl+B, ... Ctrl+Z 610 | Send(chr(Key-VK_A+1)); 611 | end; 612 | end; 613 | end; 614 | end; 615 | procedure TConsoleProc.ProcLoop(const lin: string); 616 | {Método interno de respuesta al evento OnLineCompleted(), para usarse con RunInLoop()} 617 | begin 618 | if LoopList<>nil then begin 619 | LoopList.Add(lin); //solo acumula 620 | end; 621 | end; 622 | procedure TConsoleProc.DoLineCompleted(const lin: string); 623 | {Método interno de respuesta al evento OnLineCompleted(), para usarse con RunInLoop()} 624 | begin 625 | if LinPartial then begin 626 | //Estamos en la línea del prompt 627 | outList[outList.Count-1] := lin; //reemplaza última línea 628 | LinPartial := false; 629 | end else begin //caso común 630 | outList.Add(lin); 631 | end; 632 | end; 633 | procedure TConsoleProc.DoReadData(nDat: integer; const lastLine: string); 634 | {Método interno de respuesta al evento OnReadData(), para usarse con RunInLoop()} 635 | begin 636 | LinPartial := true; //marca bandera 637 | outList.Add(lastLine); //agrega la línea que contiene al prompt 638 | end; 639 | procedure TConsoleProc.SetLineDelimRecv(AValue: TUtLineDelRecv); 640 | begin 641 | FLineDelimRecv:=AValue; 642 | case FLineDelimRecv of 643 | LDR_CRLF : begin term.bhvCR := tbcNormal ; term.bhvLF := tbcNormal ; end; 644 | LDR_CR : begin term.bhvCR := tbcNewLine; term.bhvLF := tbcNone ; end; 645 | LDR_LF : begin term.bhvCR := tbcNone ; term.bhvLF := tbcNewLine; end; 646 | LDR_CR_LF: begin term.bhvCR := tbcNewLine; term.bhvLF := tbcNewLine; end; 647 | end; 648 | end; 649 | function TConsoleProc.Loop(TimeoutSegs: integer = -1; ldelay:integer = 50): boolean; 650 | {Ejecuta el proceso en un lazo, hasta que la aplicación termine o hasta que se 651 | cumpla el número de segundos indicados en "TimeoutSegs". Si se detiene por desborde 652 | devuelve TRUE, y un mensaje de error en "msjError". 653 | "ldelay" es la duración en milisegundos que se asigna al bucle. 654 | Se usa cuando no se puede usar el temporizador, como en las aplicaciones de consola.} 655 | var 656 | tic_proc: Integer; 657 | max_tics: integer; 658 | begin 659 | if TimeoutSegs=-1 then begin 660 | //ejecuta lazo hasta que termine el proceso 661 | repeat 662 | RefreshConnection(nil); 663 | sleep(ldelay); 664 | until State = ECO_STOPPED; 665 | exit(false); 666 | end else begin 667 | //ejecuta hasta que termine el proceso o haya desborde de tiempo 668 | tic_proc := 0; 669 | max_tics := TimeoutSegs * 20; 670 | repeat 671 | RefreshConnection(nil); //necesario porque no funciona el Timer del LCL 672 | sleep(ldelay); 673 | inc(tic_proc); 674 | until (State = ECO_STOPPED) or (tic_proc > max_tics); 675 | if tic_proc > max_tics then begin 676 | msjError := MSG_ERR_TIMEOUT; 677 | exit(true); 678 | end; 679 | exit(false); 680 | end; 681 | end; 682 | function TConsoleProc.RunInLoop(progPath, progParam: string; 683 | TimeoutSegs: integer = -1): boolean; 684 | {Ejecuta el proceso y el lazo de espera (Loop), a la vez. 685 | } 686 | begin 687 | Open(progPath, progParam); 688 | if msjError<>'' then exit; 689 | Result := Loop(TimeoutSegs); 690 | //puede generar error 691 | end; 692 | function TConsoleProc.RunInLoop(progPath, progParam: string; 693 | TimeoutSegs: integer; var progOut: TStringList): boolean; 694 | {Versión de RunInLoop(), que ejecuta captura la salida del proceso en un TString 695 | } 696 | begin 697 | OnLineCompleted:=@ProcLoop; 698 | LoopList := progOut; //aquí se acumulará la salida 699 | Result := RunInLoop(progPath, progParam, TimeoutSegs); 700 | OnLineCompleted:=nil; 701 | //puede generar error 702 | end; 703 | function TConsoleProc.RunInLoop(progPath, progParam: string; 704 | TimeoutSegs: integer; out outText: String): boolean; 705 | {Versión de RunInLoop(), que ejecuta captura la salida del proceso en una cadena 706 | } 707 | begin 708 | OnLineCompleted := @DoLineCompleted; 709 | OnReadData := @DoReadData; 710 | outList := TStringList.Create; //Aquí se acumulará la salida 711 | Result := RunInLoop(progPath, progParam, TimeoutSegs); 712 | outText := outList.Text; 713 | outList.Destroy; 714 | OnLineCompleted := nil; 715 | OnReadData := nil; 716 | //puede generar error 717 | end; 718 | //respuesta a eventos de term 719 | procedure TConsoleProc.termAddLine; 720 | //Se pide agregar líneas a la salida 721 | begin 722 | if OnAddLine<>nil then OnAddLine(term.height); 723 | end; 724 | procedure TConsoleProc.termRefreshLines(fIni, fFin: integer); 725 | //Se pide refrescar un rango de líneas 726 | begin 727 | if OnRefreshAll<>nil then OnRefreshAll(term.buf); //evento 728 | if fIni=fFin then begin //una sola línea 729 | if OnRefreshLine<> nil then OnRefreshLine(term.buf, fIni, term.height); 730 | end else begin 731 | if OnRefreshLines<> nil then OnRefreshLines(term.buf, fIni, fFin, term.height); 732 | end; 733 | end; 734 | procedure TConsoleProc.termRecSysComm(info: string); 735 | //Se ha recibido comando con información del sistema. 736 | begin 737 | //se indica que se recibe información del sistema 738 | if OnRecSysComm<>nil then OnRecSysComm(info, term.CurXY); 739 | //Se puede asumir que llega el prompt pero no siempre funciona 740 | // HayPrompt := true; //marca bandera 741 | // ChangeState(ECO_READY); //cambia el State 742 | end; 743 | procedure TConsoleProc.termLineCompleted(const lineCompleted: string); 744 | begin 745 | if OnLineCompleted<>nil then OnLineCompleted(lineCompleted); 746 | end; 747 | procedure TConsoleProc.AutoConfigPrompt; 748 | //Configura el prompt actual como el prompt por defecto. Esta configuración no es 749 | //para nada, precisa pero ahorrará tiempo en configurar casos sencillos 750 | var 751 | ultlin: String; 752 | function SimbolosIniciales(cad: string): string; 753 | //Toma uno o dos símbolos iniciales de la cadena. Se usan símbolos porque 754 | //suelen ser fijos, mientras que los caracteres alfabéticos suelen cambiar 755 | //en el prompt. 756 | begin 757 | Result := cad[1]; //el primer caracter se tomará siempre 758 | if length(cad)>3 then begin 759 | //agrega si es un símbolo. 760 | if not (cad[2] in ['a'..'z','A'..'Z']) then 761 | Result += cad[2]; 762 | end; 763 | end; 764 | function SimbolosFinales(cad: string): string; 765 | //Toma uno o dos o tres caracteres finales de la cadena. Se usan símbolos porque 766 | //suelen ser fijos, mientras que los caracteres alfabéticos suelen cambiar 767 | //en el prompt. 768 | var 769 | p: Integer; 770 | hayEsp: Boolean; 771 | begin 772 | p := length(cad); //apunta al final 773 | hayEsp := (cad[p] = ' '); 774 | cad := TrimRight(cad); //quita espacios 775 | if length(cad)<=2 then begin 776 | //hay muy pocos caracteres 777 | Result := cad[p-1]+cad[p]; //toma los últimos 778 | exit; 779 | end; 780 | //hay suficientes caracteres 781 | p := length(cad); //apunta al final (sin espacios) 782 | Result := cad[p]; 783 | //agrega si es un símbolo. 784 | if not (cad[p-1] in ['a'..'z','A'..'Z']) then 785 | Result := cad[p-1] + Result; 786 | //completa con espacio si hubiera 787 | if hayEsp then Result += ' '; 788 | end; 789 | begin 790 | //utiliza la línea actual del terminal 791 | promptIni := ''; 792 | promptFin := ''; 793 | ultlin := LastLine; 794 | if ultlin = '' then begin 795 | ShowMessage(MSG_NO_PRMP_FOUND); 796 | exit; 797 | end; 798 | //casos particulares 799 | If ultlin = '>>> ' Then begin //caso especial 800 | DetecPrompt := true; 801 | promptIni := '>>'; 802 | promptFin := ' '; 803 | SendLn(''); //para que detecte el prompt 804 | exit; 805 | end; 806 | If ultlin = 'SQL> ' Then begin //caso especial 807 | DetecPrompt := true; 808 | promptIni := 'SQL> '; 809 | promptFin := ''; 810 | SendLn(''); //para que detecte el prompt 811 | exit; 812 | end; 813 | If length(ultlin)<=3 Then begin //caso especial 814 | DetecPrompt := true; 815 | promptIni := ultlin; 816 | promptFin := ''; 817 | SendLn(''); //para que detecte el prompt 818 | exit; 819 | end; 820 | //caso general 821 | DetecPrompt := true; 822 | promptIni := SimbolosIniciales(ultlin); 823 | promptFin := SimbolosFinales(ultlin); 824 | SendLn(''); //para que detecte el prompt 825 | end; 826 | //Statusbar control 827 | procedure TConsoleProc.RefStatePanel; //Refresca el estado del panel del StatusBar asociado. 828 | begin 829 | if panel = nil then exit; //protección 830 | //fuerza a llamar al evento OnDrawPanel del StatusBar 831 | panel.StatusBar.InvalidatePanel(panel.Index,[ppText]); 832 | //y este a us vez debe llamar a DrawStatePanel() 833 | end; 834 | procedure TConsoleProc.DrawStatePanel(c: TCanvas; const Rect: TRect); 835 | {Dibuja un ícono y texto, de acuerdo al estado de la conexión. Este código está pensado 836 | para ser usado en el evento OnDrawPanel() de una barra de estado} 837 | var 838 | p1,p2: Tpoint; 839 | procedure Pie(c: Tcanvas; x1,y1,x2,y2: integer; a1,a2: double); //dibuja una torta 840 | var x3,y3,x4,y4: integer; 841 | xc, yc: integer; 842 | begin 843 | xc := (x1+x2) div 2; yc := (y1+y2) div 2; 844 | x3:=xc + round(1000*cos(a1)); 845 | y3:=yc + round(1000*sin(a1)); 846 | x4:=xc + round(1000*cos(a2)); 847 | y4:=yc + round(1000*sin(a2)); 848 | c.pie(x1,y1,x2,y2,x3,y3,x4,y4); 849 | end; 850 | procedure Circulo(c: Tcanvas; xc,yc: integer; n: integer); //dibuja un círculo 851 | const r = 2; 852 | begin 853 | case n of 854 | 5: c.Brush.Color:=$B0FFB0; 855 | 4: c.Brush.Color:=$40FF40; 856 | 3: c.Brush.Color:=$00E000; 857 | 2: c.Brush.Color:=$00CC00; 858 | 1: c.Brush.Color:=$00A000; 859 | 0: c.Brush.Color:=$008000; 860 | else 861 | c.Brush.Color:=clWhite; 862 | end; 863 | c.Pen.Color:=c.Brush.Color; 864 | c.Ellipse(xc-r, yc-r+1, xc+r, yc+r+1); 865 | end; 866 | begin 867 | if State in [ECO_CONNECTING, ECO_BUSY] then begin //estados de espera 868 | c.Pen.Width:=0; //restaura ancho 869 | Circulo(c,Rect.Left+5,Rect.Top+5, angA); 870 | inc(angA);if angA>7 then angA:=0; 871 | Circulo(c,Rect.Left+9,Rect.Top+3, angA); 872 | inc(angA);if angA>7 then angA:=0; 873 | Circulo(c,Rect.Left+13,Rect.Top+5, angA); 874 | inc(angA);if angA>7 then angA:=0; 875 | Circulo(c,Rect.Left+15,Rect.Top+9, angA); 876 | inc(angA);if angA>7 then angA:=0; 877 | Circulo(c,Rect.Left+13,Rect.Top+13, angA); 878 | inc(angA);if angA>7 then angA:=0; 879 | Circulo(c,Rect.Left+9,Rect.Top+15, angA); 880 | inc(angA);if angA>7 then angA:=0; 881 | Circulo(c,Rect.Left+5,Rect.Top+13, angA); 882 | inc(angA);if angA>7 then angA:=0; 883 | Circulo(c,Rect.Left+3,Rect.Top+9, angA); 884 | inc(angA);if angA>7 then angA:=0; 885 | 886 | end else if State = ECO_ERROR_CON then begin //error de conexión 887 | //c´rculo rojo 888 | c.Brush.Color:=clRed; 889 | c.Pen.Color:=clRed; 890 | c.Ellipse(Rect.Left+2, Rect.Top+2, Rect.Left+16, Rect.Top+16); 891 | //aspa blanca 892 | c.Pen.Color:=clWhite; 893 | c.Pen.Width:=2; 894 | p1.x := Rect.Left+5; p1.y := Rect.Top+5; 895 | p2.x := Rect.Left+12; p2.y := Rect.Top+12; 896 | c.Line(p1,p2); 897 | p1.x := Rect.Left+5; p1.y := Rect.Top+12; 898 | p2.x := Rect.Left+12; p2.y := Rect.Top+5; 899 | c.Line(p1,p2); 900 | end else if State = ECO_READY then begin //disponible 901 | c.Brush.Color:=clGreen; 902 | c.Pen.Color:=clGreen; 903 | c.Ellipse(Rect.Left+2, Rect.Top+2,Rect.Left+16, Rect.Top+16); 904 | c.Pen.Color:=clWhite; 905 | c.Pen.Width:=2; 906 | p1.x := Rect.Left+6; p1.y := Rect.Top+7; 907 | p2.x := Rect.Left+8; p2.y := Rect.Top+12; 908 | c.Line(p1,p2); 909 | p1.x := Rect.Left+12; p1.y := Rect.Top+5; 910 | // p2.x := Rect.Left+12; p2.y := Rect.Top+5; 911 | c.Line(p2,p1); 912 | end else begin //estados detenido 913 | //círculo gris 914 | c.Brush.Color:=clGray; 915 | c.Pen.Color:=clGray; 916 | c.Ellipse(Rect.Left+2, Rect.Top+2, Rect.Left+16, Rect.Top+16); 917 | //aspa blanca 918 | c.Pen.Color:=clWhite; 919 | c.Pen.Width:=2; 920 | p1.x := Rect.Left+5; p1.y := Rect.Top+5; 921 | p2.x := Rect.Left+12; p2.y := Rect.Top+12; 922 | c.Line(p1,p2); 923 | p1.x := Rect.Left+5; p1.y := Rect.Top+12; 924 | p2.x := Rect.Left+12; p2.y := Rect.Top+5; 925 | c.Line(p1,p2); 926 | end; 927 | c.Font.Color:=clBlack; 928 | c.TextRect(Rect, 19 + Rect.Left, 2 + Rect.Top, txtState); 929 | end; 930 | //Initialization 931 | constructor TConsoleProc.Create(PanControl: TStatusPanel); 932 | //Constructor 933 | begin 934 | lstTmp := TStringList.Create; //crea lista temporal 935 | p := TProcess.Create(nil); //Crea proceso 936 | ChangeState(ECO_STOPPED); //State inicial. Genera el primer evento 937 | //configura temporizador 938 | clock := TTimer.Create(nil); 939 | clock.interval:=50; {100 es un buen valor, pero para mayor velocidad de recepción, se 940 | puede usar 50 milisegundos} 941 | clock.OnTimer := @RefreshConnection; 942 | panel := PanControl; //inicia referencia a panel 943 | if panel<> nil then 944 | panel.Style:=psOwnerDraw; //configura panel para dibujarse por evento 945 | detecPrompt := true; //activa detección de prompt por defecto 946 | promptMatch := prmExactly; //debe ser exacta 947 | ClearOnOpen := true; //por defecto se limpia la pantalla 948 | //Crea y configura terminal 949 | term := TTermVT100.Create; //terminal 950 | term.OnRefreshLines:=@termRefreshLines; 951 | term.OnScrollLines:=@termAddLine; 952 | term.OnLineCompleted:=@termLineCompleted; 953 | term.OnRecSysComm:=@termRecSysComm; {usaremos este evento para detectar la llegada 954 | del prompt} 955 | //Configura delimitadores de línea iniciales 956 | LineDelimSend := LDS_CRLF; 957 | LineDelimRecv := LDR_LF; 958 | end; 959 | destructor TConsoleProc.Destroy; 960 | //Destructor 961 | begin 962 | term.Free; 963 | clock.Free; //destruye temporizador 964 | //verifica el proceso 965 | if p.Running then p.Terminate(0); 966 | //libera objetos 967 | FreeAndNIL(p); 968 | lstTmp.Free; //limpia 969 | end; 970 | 971 | 972 | end. 973 | -------------------------------------------------------------------------------- /screen1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-edson/UnTerminal/cc39d54af7b16cd058ea4c619fcf30ad0d7e5ce2/screen1.png --------------------------------------------------------------------------------