text
stringlengths
14
6.51M
unit TaskPanelWords; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\TaskPanelWords.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TaskPanelWords" MUID: (5101345E0143) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3ImplUses {$If Defined(Nemesis)} , nscTasksPanelView {$IfEnd} // Defined(Nemesis) , tfwClassLike , tfwScriptingInterfaces , TypInfo , tfwPropertyLike , tfwTypeInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *5101345E0143impl_uses* //#UC END# *5101345E0143impl_uses* ; type TkwPopTaskPanelGetHideField = {final} class(TtfwClassLike) {* Слово скрипта pop:TaskPanel:GetHideField } private function GetHideField(const aCtx: TtfwContext; aTaskPanel: TnscTasksPanelView; anIndex: Integer): TnscTasksPanelHideField; {* Реализация слова скрипта pop:TaskPanel:GetHideField } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopTaskPanelGetHideField TkwPopTaskPanelCount = {final} class(TtfwPropertyLike) {* Слово скрипта pop:TaskPanel:Count } private function Count(const aCtx: TtfwContext; aTaskPanel: TnscTasksPanelView): Integer; {* Реализация слова скрипта pop:TaskPanel:Count } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopTaskPanelCount function TkwPopTaskPanelGetHideField.GetHideField(const aCtx: TtfwContext; aTaskPanel: TnscTasksPanelView; anIndex: Integer): TnscTasksPanelHideField; {* Реализация слова скрипта pop:TaskPanel:GetHideField } //#UC START# *552FCA800230_552FCA800230_4D3424C203C2_Word_var* //#UC END# *552FCA800230_552FCA800230_4D3424C203C2_Word_var* begin //#UC START# *552FCA800230_552FCA800230_4D3424C203C2_Word_impl* Result := aTaskPanel.HideField[anIndex]; //#UC END# *552FCA800230_552FCA800230_4D3424C203C2_Word_impl* end;//TkwPopTaskPanelGetHideField.GetHideField class function TkwPopTaskPanelGetHideField.GetWordNameForRegister: AnsiString; begin Result := 'pop:TaskPanel:GetHideField'; end;//TkwPopTaskPanelGetHideField.GetWordNameForRegister function TkwPopTaskPanelGetHideField.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTasksPanelHideField); end;//TkwPopTaskPanelGetHideField.GetResultTypeInfo function TkwPopTaskPanelGetHideField.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopTaskPanelGetHideField.GetAllParamsCount function TkwPopTaskPanelGetHideField.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TnscTasksPanelView), TypeInfo(Integer)]); end;//TkwPopTaskPanelGetHideField.ParamsTypes procedure TkwPopTaskPanelGetHideField.DoDoIt(const aCtx: TtfwContext); var l_aTaskPanel: TnscTasksPanelView; var l_anIndex: Integer; begin try l_aTaskPanel := TnscTasksPanelView(aCtx.rEngine.PopObjAs(TnscTasksPanelView)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aTaskPanel: TnscTasksPanelView : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetHideField(aCtx, l_aTaskPanel, l_anIndex)); end;//TkwPopTaskPanelGetHideField.DoDoIt function TkwPopTaskPanelCount.Count(const aCtx: TtfwContext; aTaskPanel: TnscTasksPanelView): Integer; {* Реализация слова скрипта pop:TaskPanel:Count } begin Result := aTaskPanel.Count; end;//TkwPopTaskPanelCount.Count class function TkwPopTaskPanelCount.GetWordNameForRegister: AnsiString; begin Result := 'pop:TaskPanel:Count'; end;//TkwPopTaskPanelCount.GetWordNameForRegister function TkwPopTaskPanelCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopTaskPanelCount.GetResultTypeInfo function TkwPopTaskPanelCount.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopTaskPanelCount.GetAllParamsCount function TkwPopTaskPanelCount.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TnscTasksPanelView)]); end;//TkwPopTaskPanelCount.ParamsTypes procedure TkwPopTaskPanelCount.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Count', aCtx); end;//TkwPopTaskPanelCount.SetValuePrim procedure TkwPopTaskPanelCount.DoDoIt(const aCtx: TtfwContext); var l_aTaskPanel: TnscTasksPanelView; begin try l_aTaskPanel := TnscTasksPanelView(aCtx.rEngine.PopObjAs(TnscTasksPanelView)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aTaskPanel: TnscTasksPanelView : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(Count(aCtx, l_aTaskPanel)); end;//TkwPopTaskPanelCount.DoDoIt initialization TkwPopTaskPanelGetHideField.RegisterInEngine; {* Регистрация pop_TaskPanel_GetHideField } TkwPopTaskPanelCount.RegisterInEngine; {* Регистрация pop_TaskPanel_Count } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTasksPanelView)); {* Регистрация типа TnscTasksPanelView } {$IfEnd} // Defined(Nemesis) {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTasksPanelHideField)); {* Регистрация типа TnscTasksPanelHideField } {$IfEnd} // Defined(Nemesis) TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) end.
{ Invokable interface IServidorBLL } unit uServidorBLLIntf; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc; type TRetorno = class(TRemotable) private FID: UnicodeString; FSucesso: UnicodeString; FMensagem: UnicodeString; published property id: UnicodeString read FID write FID; property sucesso: UnicodeString read FSucesso write FSucesso; property mensagem: UnicodeString read FMensagem write FMensagem; end; { Invokable interfaces must derive from IInvokable } IServidorBLL = interface(IInvokable) ['{B97FBB36-3194-4055-A5AF-791B416110EA}'] function mensagemBoasVindas: String; stdcall; function envioLaudoLoteBloqueado(const arquivo: WideString): WideString; stdcall; function envioEncerramentoLote(const arquivo: WideString): WideString; stdcall; function exibeMensagem(const msg: WideString): WideString; stdcall; function retornoImediato(const arquivo: WideString): String; stdcall; { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } end; implementation initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(IServidorBLL)); end.
unit uJadwal; interface uses uKata; const Nmax = 1000; type Tayang = record Nama, Jam : string; Tanggal, Bulan, Tahun, LamaTayang : integer; end; type dbTayang = record Tayang : array[1..Nmax] of Tayang; Neff : integer; end; procedure load (var f:text;p:string); {* procedure yang digunakan untuk meng-assign nama lojik ke nama fisik I.S : f terdefinisi F.S : p telah di-assign dengan variabel f *} procedure loadTayang(var dT: dbTayang); {* procedure yang digunakan untuk me-load data dari file eksternal jadwal.txt ke dalam variabel internal I.S : file eksternal jadwal.txt telah terdefinisi F.S : data di jadwal.txt telah ditampung ke dalam dT *} function idx ( f : string; T : dbTayang) : integer; {Fungsi yang digunakan untuk mencari index pertama dari suatu film} procedure TulisJam (idx : integer; f : string; T : dbTayang; tanggal : string); {* Procedure TulisJam digunakan untuk menuliskan Jam Tayang dari suatu Film pada tanggal tertentu I.S : idx, f, T, dd, mm, yy telah terdefinisi F.S : Menuliskan Jam Tayang kepada user *} procedure schedule( T : dbTayang); {* Procedure schedule digunakan untuk menampilkan Jam Tayang dari input user I.S : T terdefinisi F.S : Menuliskan Jam Tayang Film kepada user *} implementation procedure load (var f:text;p:string); begin assign(f,p); reset(f); end; procedure loadTayang(var dT: dbTayang); var dTayang: text; f:ansistring; pos1,l,i,j:integer; begin j:=1; load(dTayang,'database\jadwal.txt'); while not Eof(dTayang) do begin readln(dTayang,f); for i:=1 to 6 do begin pos1:=pos('|',f); l:=length(copy(f,1,pos1+1)); case i of 1:dT.Tayang[j].Nama:=copy(f,1,pos1-2); 2:dT.Tayang[j].Jam:=copy(f,1,pos1-2); 3:val(copy(f,1,pos1-2),dT.Tayang[j].Tanggal); 4:val(copy(f,1,pos1-2),dT.Tayang[j].Bulan); 5:val(copy(f,1,pos1-2),dT.Tayang[j].Tahun); 6:val(copy(f,1,pos1-2),dT.Tayang[j].LamaTayang); end; delete(f,1,l); end; j:=j+1; end; dT.Neff:=j-1; close(dTayang); end; function idx ( f : string; T : dbTayang) : integer; {Kamus} var i : integer; cek : boolean; {Algoritma} begin i := 1; cek := False; while (cek=False) and (i<=T.Neff) do begin if (lowAll(T.Tayang[i].Nama)=lowAll(f)) then cek := True; i := i + 1; end; if (cek=True) then idx := i - 1 else idx := 0; end; procedure TulisJam (idx : integer; f : string; T : dbTayang; tanggal : string); {Kamus} var j, i, k, a : integer; h,b,y : integer; dd,mm,yy : integer; cek : boolean; {Algoritma} begin cek := False; repeat y := T.Tayang[idx].Tahun; b := T.Tayang[idx].Bulan; h := T.Tayang[idx].Tanggal; //Konversi input user dari String to Integer val(copy(tanggal,1,2), dd); val(copy(tanggal,4,2), mm); val(copy(tanggal,7,4), yy); if (mm<10) and (dd<10) then writeln('> Daftar Jam Tayang Film ',T.Tayang[idx].Nama,' pada tanggal 0',dd,'-0',mm,'-',yy,' :') else if (mm<10) then writeln('> Daftar Jam Tayang Film ',T.Tayang[idx].Nama,' pada tanggal ',dd,'-0',mm,'-',yy,' :') else if (dd<10) then writeln('> Daftar Jam Tayang Film ',T.Tayang[idx].Nama,' pada tanggal 0',dd,'-',mm,'-',yy,' :') else writeln('> Daftar Jam Tayang Film ',T.Tayang[idx].Nama,' pada tanggal ',dd,'-',mm,'-',yy,' :'); k := h + 6; if (k>tanggalMax(b,y)) then begin if (yy = y) and ((mm = b) or (mm = b+1)) then begin a := k - tanggalMax(b,y); for j := h to tanggalMax(b,y) do begin if ( j = dd ) then begin for i := idx to (idx+3) do begin cek := true; if (lowAll(T.Tayang[i].Nama)=lowAll(f)) then writeln('> ',T.Tayang[i].Jam); end; end; end; for j := 1 to a do begin if ( j = dd ) then begin for i := idx to (idx+3) do begin cek := true; if (lowAll(T.Tayang[i].Nama)=lowAll(f)) then writeln('> ',T.Tayang[i].Jam); end; end; end; end; end else begin if (yy = y) and (mm = b) then begin for j := h to (h+6) do begin if ( j = dd ) then begin for i := idx to (idx+3) do begin cek := true; if (lowAll(T.Tayang[i].Nama)=lowAll(f)) then writeln('> ',T.Tayang[i].Jam); end; end; end; end; end; if cek=false then begin writeln('> Jadwal tak tersedia '); writeln('> Ulangi input tanggal'); write('> Tanggal tayang : '); readln(tanggal); end; until cek = True; end; procedure schedule( T : dbTayang); {Kamus} var tanggal, f : string; index : integer; {Algoritma} begin repeat write('> Film : '); readln(f); write('> Tanggal tayang : '); readln(tanggal); //Pencarian Film dan Penampilan Jam index := idx(f,T); if(index=0) then begin writeln('> Masukkan nama film atau tanggal tayang salah'); writeln('> Silahkan ulang masukkan'); end else TulisJam(index,f,T,tanggal); until (index>0) end; end.
(* Random Number Generators DA, 23.01.2019 *) UNIT Random; INTERFACE PROCEDURE InitRandSeed(s: INTEGER); FUNCTION IntRand: INTEGER; FUNCTION RealRand: REAL; FUNCTION RangeIntRand1(n: INTEGER): INTEGER; FUNCTION RangeIntRand2(n: INTEGER): INTEGER; IMPLEMENTATION CONST (* m ... 2er Potenz - Wertebereich*) m = 32768; VAR x: LONGINT; PROCEDURE InitRandSeed(s: INTEGER); BEGIN x := s; END; (* IntRand liefert Zufallszahlen zwischen 0 und m - 1 *) FUNCTION IntRand: INTEGER; CONST (* a ... ganzeZahl und 21 dahinter; eine 10er Potenz < als m*) a = 3421; c = 1; BEGIN x := (a * x + c) MOD m; IntRand := x; END; (* RealRand liefert reelle Zahlen zwischen 0 und 1 zurück *) FUNCTION RealRand: REAL; BEGIN RealRand := IntRand / m; END; FUNCTION RangeIntRand1(n: INTEGER): INTEGER; BEGIN RangeIntRand1 := IntRand MOD n; (* nicht wirklich normalverteilt *) END; FUNCTION RangeIntRand2(n: INTEGER): INTEGER; VAR x: INTEGER; k: INTEGER; BEGIN k := m - (m MOD n); REPEAT x := IntRand; UNTIL x < k; RangeIntRand2 := x; END; BEGIN x := 1; END.
unit evButtonControl; {* Класс кнопки } // Модуль: "w:\common\components\gui\Garant\Everest\qf\evButtonControl.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevButtonControl" MUID: (48D230A600EE) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evControl , evQueryCardInt , nevTools , nevBase ; type TevButtonControl = class(TevControl, IevEditorControlButton, IevEditorStateButton) {* Класс кнопки } protected procedure IncButtonState; {* Изменяет состояние кнопки } function GetButtonType: TevButtonType; function Get_StateCount: Integer; function Get_CurrentIndex: Integer; procedure Set_CurrentIndex(aValue: Integer); function Get_ImageIndex: Integer; function GetStateIndex: Integer; {* Собственно возвращает состояние кнопки от 0 до максимального. } function DoLMouseBtnUp(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean): Boolean; override; function DoLMouseBtnDown(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean; const aMap: InevMap): Boolean; override; procedure DoUpperChange; override; public function DoKeyCommand(const aView: InevControlView; aCmd: Word; const aTextPara: InevPara): Boolean; override; end;//TevButtonControl implementation uses l3ImplUses , k2Tags , evQueryCardDropControlsInt , evQueryCardConst , l3String , OvcConst , SysUtils , l3Units , l3Base //#UC START# *48D230A600EEimpl_uses* //#UC END# *48D230A600EEimpl_uses* ; procedure TevButtonControl.IncButtonState; {* Изменяет состояние кнопки } //#UC START# *48D2334500E1_48D230A600EE_var* var l_CurrIndex: Integer; //#UC END# *48D2334500E1_48D230A600EE_var* begin //#UC START# *48D2334500E1_48D230A600EE_impl* l_CurrIndex := Get_CurrentIndex; if (Get_ImageIndex + Get_StateCount) > Get_CurrentIndex then Set_CurrentIndex(l_CurrIndex + 1) else Set_CurrentIndex(Get_ImageIndex); //#UC END# *48D2334500E1_48D230A600EE_impl* end;//TevButtonControl.IncButtonState function TevButtonControl.GetButtonType: TevButtonType; //#UC START# *47CD79C903AF_48D230A600EE_var* var l_Long: Integer; //#UC END# *47CD79C903AF_48D230A600EE_var* begin //#UC START# *47CD79C903AF_48D230A600EE_impl* Result := ev_btNone; if l3Same(Get_ControlName, csLogicBTN) then Result := ev_btLogical else if l3Same(Get_ControlName, csAddBTN) then Result := ev_btAdd else if l3Same(Get_ControlName, csDeleteBTN) then Result := ev_btDelete; //Bug fix: карточка может использовать другие названия кнопок - это заплатка! if Result = ev_btNone then begin if (Para.AsObject.IntA[k2_tiStateIndex] = -1) then if (Para.AsObject.IntA[k2_tiImageIndex] <> -1) then l_Long := Para.AsObject.IntA[k2_tiImageIndex] else l_Long := -1 else l_Long := Para.AsObject.IntA[k2_tiStateIndex]; if l_Long <> -1 then if l_Long = 5 then Result := ev_btDelete else if l_Long = 58 then Result := ev_btAdd else if (l_Long >= 37) and (l_Long <= 39) then Result := ev_btLogical; end; //#UC END# *47CD79C903AF_48D230A600EE_impl* end;//TevButtonControl.GetButtonType function TevButtonControl.Get_StateCount: Integer; //#UC START# *47CD79ED01CC_48D230A600EEget_var* //#UC END# *47CD79ED01CC_48D230A600EEget_var* begin //#UC START# *47CD79ED01CC_48D230A600EEget_impl* Result := Para.AsObject.IntA[k2_tiStateCount]; //#UC END# *47CD79ED01CC_48D230A600EEget_impl* end;//TevButtonControl.Get_StateCount function TevButtonControl.Get_CurrentIndex: Integer; //#UC START# *47CD79FA004E_48D230A600EEget_var* //#UC END# *47CD79FA004E_48D230A600EEget_var* begin //#UC START# *47CD79FA004E_48D230A600EEget_impl* Result := Para.AsObject.IntA[k2_tiStateIndex]; //#UC END# *47CD79FA004E_48D230A600EEget_impl* end;//TevButtonControl.Get_CurrentIndex procedure TevButtonControl.Set_CurrentIndex(aValue: Integer); //#UC START# *47CD79FA004E_48D230A600EEset_var* //#UC END# *47CD79FA004E_48D230A600EEset_var* begin //#UC START# *47CD79FA004E_48D230A600EEset_impl* Para.AsObject.IntW[k2_tiStateIndex, nil] := aValue; //#UC END# *47CD79FA004E_48D230A600EEset_impl* end;//TevButtonControl.Set_CurrentIndex function TevButtonControl.Get_ImageIndex: Integer; //#UC START# *47CD7A0A03DD_48D230A600EEget_var* //#UC END# *47CD7A0A03DD_48D230A600EEget_var* begin //#UC START# *47CD7A0A03DD_48D230A600EEget_impl* Result := Para.AsObject.IntA[k2_tiImageIndex]; //#UC END# *47CD7A0A03DD_48D230A600EEget_impl* end;//TevButtonControl.Get_ImageIndex function TevButtonControl.GetStateIndex: Integer; {* Собственно возвращает состояние кнопки от 0 до максимального. } //#UC START# *47CDA4CB026C_48D230A600EE_var* //#UC END# *47CDA4CB026C_48D230A600EE_var* begin //#UC START# *47CDA4CB026C_48D230A600EE_impl* Result := Get_CurrentIndex - Get_ImageIndex; //#UC END# *47CDA4CB026C_48D230A600EE_impl* end;//TevButtonControl.GetStateIndex function TevButtonControl.DoLMouseBtnUp(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean): Boolean; //#UC START# *48D1461101C6_48D230A600EE_var* var l_BtnType: TevButtonType; //#UC END# *48D1461101C6_48D230A600EE_var* begin //#UC START# *48D1461101C6_48D230A600EE_impl* if Get_Visible then begin l_BtnType := GetButtonType; case l_BtnType of ev_btLogical: if Get_Enabled then IncButtonState; ev_btAdd, ev_btDelete: Get_Req.ButtonPressed(aView, Self, l_BtnType); end;//case l_BtnType Result := True; end//Get_Visible else Result := False; //#UC END# *48D1461101C6_48D230A600EE_impl* end;//TevButtonControl.DoLMouseBtnUp function TevButtonControl.DoLMouseBtnDown(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean; const aMap: InevMap): Boolean; //#UC START# *48D1464501E8_48D230A600EE_var* var l_DropContainer: IevDropContainer; //#UC END# *48D1464501E8_48D230A600EE_var* begin //#UC START# *48D1464501E8_48D230A600EE_impl* if Supports(Get_Req.QueryCard, IevDropContainer, l_DropContainer) then l_DropContainer.HideControl(true); if anInPara and Get_Visible then begin SetChecked(True); Result := True; end else Result := False; //#UC END# *48D1464501E8_48D230A600EE_impl* end;//TevButtonControl.DoLMouseBtnDown function TevButtonControl.DoKeyCommand(const aView: InevControlView; aCmd: Word; const aTextPara: InevPara): Boolean; //#UC START# *48D145B8036A_48D230A600EE_var* var l_Pt: Tl3Point; l_Keys : TevMouseState; //#UC END# *48D145B8036A_48D230A600EE_var* begin //#UC START# *48D145B8036A_48D230A600EE_impl* if (aCmd = ccSelect) or (aCmd = ccActionItem) then begin Result := True;//Нам не нужно добавление нового параграфа (т.е. копирование виджета). l3FillChar(l_Keys, SizeOf(l_Keys), 0); l3FillChar(l_Pt, SizeOf(l_Pt), 0); LMouseBtnUp(aView, aTextPara, l_Pt, l_Keys, True) end else Result := False; //#UC END# *48D145B8036A_48D230A600EE_impl* end;//TevButtonControl.DoKeyCommand procedure TevButtonControl.DoUpperChange; //#UC START# *48D1489102C9_48D230A600EE_var* //#UC END# *48D1489102C9_48D230A600EE_var* begin //#UC START# *48D1489102C9_48D230A600EE_impl* Get_Req.QueryCard.UpperChange(Self); //#UC END# *48D1489102C9_48D230A600EE_impl* end;//TevButtonControl.DoUpperChange end.
unit uBaseCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ImgList, Vcl.Grids, Vcl.DBGrids, Data.DB, uGrade, Datasnap.DBClient, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uImagens, uFuncoesSIDomper; type TfrmBaseCadastro = class(TForm) pgControl: TPageControl; tsPesquisa: TTabSheet; tsEdicao: TTabSheet; tsFiltro: TTabSheet; Panel1: TPanel; Panel2: TPanel; btnNovo: TBitBtn; btnEditar: TBitBtn; btnExcluir: TBitBtn; btnFiltrar: TBitBtn; btnSair: TBitBtn; btnAnterior: TBitBtn; btnProximo: TBitBtn; Panel3: TPanel; Panel4: TPanel; btnSalvar: TBitBtn; btnCancelar: TBitBtn; Panel5: TPanel; Panel6: TPanel; btnFiltro: TBitBtn; btnImprimir: TBitBtn; btnFecharFiltro: TBitBtn; GroupBox1: TGroupBox; Label1: TLabel; cbbCampos: TComboBox; edtDescricao: TEdit; Label2: TLabel; dbDados: TDBGrid; dsPesquisa: TDataSource; dsCad: TDataSource; btnPrimeiro: TBitBtn; btnUltimo: TBitBtn; BalloonHint1: TBalloonHint; PageControl2: TPageControl; tsGeral: TTabSheet; pnlGeral: TPanel; Situação: TLabel; cbbSituacao: TComboBox; cbbPesquisa: TComboBox; Label3: TLabel; procedure btnNovoClick(Sender: TObject); procedure btnAnteriorClick(Sender: TObject); procedure btnProximoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnFiltrarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSalvarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnFiltroClick(Sender: TObject); procedure btnFecharFiltroClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnUltimoClick(Sender: TObject); procedure btnPrimeiroClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbDadosDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure dsCadStateChange(Sender: TObject); procedure dbDadosTitleClick(Column: TColumn); procedure cbbCamposClick(Sender: TObject); private FPesquisa: Boolean; FPosicaoGrade: Integer; { Private declarations } procedure TelaPesquisar; procedure TelaEdicao; procedure TelaFiltro; procedure Novo; procedure Editar; procedure Excluir; procedure Salvar; procedure Filtrar; procedure Filtro; procedure NavegarPrimeiroRegistro; procedure NavegarAnterior; procedure NavegarProximo; procedure NavegarUltimoRegistro; procedure NavegarRegistroAnterior; procedure NavegarProximoRegistro; procedure Imprimir; procedure Navegar; procedure Selecionar; procedure Ordenar; public { Public declarations } property Pesquisa: Boolean read FPesquisa write FPesquisa; end; var frmBaseCadastro: TfrmBaseCadastro; implementation {$R *.dfm} uses uDM, uPosicaoBotao; procedure TfrmBaseCadastro.btnFecharFiltroClick(Sender: TObject); begin TelaPesquisar; end; procedure TfrmBaseCadastro.btnPrimeiroClick(Sender: TObject); begin if dsPesquisa.DataSet.Active then dsPesquisa.DataSet.First; end; procedure TfrmBaseCadastro.btnProximoClick(Sender: TObject); begin if dsPesquisa.DataSet.Active then dsPesquisa.DataSet.Next; end; procedure TfrmBaseCadastro.btnEditarClick(Sender: TObject); begin TelaEdicao; end; procedure TfrmBaseCadastro.btnExcluirClick(Sender: TObject); begin try edtDescricao.SetFocus; except // nada end; end; procedure TfrmBaseCadastro.btnCancelarClick(Sender: TObject); begin TelaPesquisar; end; procedure TfrmBaseCadastro.btnFiltrarClick(Sender: TObject); begin TelaFiltro; end; procedure TfrmBaseCadastro.btnFiltroClick(Sender: TObject); begin TelaPesquisar; end; procedure TfrmBaseCadastro.btnNovoClick(Sender: TObject); begin TFuncoes.HabilitarCampo(Self, True); FPosicaoGrade := 0; TelaEdicao; end; procedure TfrmBaseCadastro.btnAnteriorClick(Sender: TObject); begin if dsPesquisa.DataSet.Active then dsPesquisa.DataSet.Prior; end; procedure TfrmBaseCadastro.btnSairClick(Sender: TObject); begin Close; end; procedure TfrmBaseCadastro.btnSalvarClick(Sender: TObject); begin TelaPesquisar; end; procedure TfrmBaseCadastro.btnUltimoClick(Sender: TObject); begin if dsPesquisa.DataSet.Active then dsPesquisa.DataSet.Last; end; procedure TfrmBaseCadastro.cbbCamposClick(Sender: TObject); begin Ordenar(); end; procedure TfrmBaseCadastro.dbDadosDblClick(Sender: TObject); begin if btnEditar.Visible then begin btnEditar.Click; TelaEdicao; end; end; procedure TfrmBaseCadastro.dbDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin TGrade.Zebrar(dsPesquisa.DataSet, dbDados, Sender, Rect, DataCol, Column, State); end; procedure TfrmBaseCadastro.dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then btnEditar.Click; end; procedure TfrmBaseCadastro.dbDadosTitleClick(Column: TColumn); var i: Integer; begin for I := 0 to cbbCampos.Items.Count-1 do begin if cbbCampos.Items[i] = Column.Title.Caption then begin cbbCampos.ItemIndex := i; Break; end; end; end; procedure TfrmBaseCadastro.dsCadStateChange(Sender: TObject); begin btnSalvar.Enabled := dsCad.DataSet.State in [dsEdit, dsInsert]; end; procedure TfrmBaseCadastro.Editar; begin if dsPesquisa.DataSet.RecordCount > 0 then FPosicaoGrade := dsPesquisa.DataSet.RecNo; if tsPesquisa.Showing then begin try if btnEditar.Visible then btnEditar.Click; except // nada end; end; end; procedure TfrmBaseCadastro.edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin cbbPesquisa.SetFocus; end; end; procedure TfrmBaseCadastro.Excluir; begin if tsPesquisa.Showing then begin if btnExcluir.Visible then begin btnExcluir.SetFocus; btnExcluir.Click; end; end; end; procedure TfrmBaseCadastro.Filtrar; begin if tsPesquisa.Showing then begin btnFiltrar.SetFocus; btnFiltrar.Click; end; end; procedure TfrmBaseCadastro.Filtro; begin if tsFiltro.Showing then begin btnFiltro.SetFocus; btnFiltro.Click; end; end; procedure TfrmBaseCadastro.FormClose(Sender: TObject; var Action: TCloseAction); begin try dsPesquisa.DataSet.Close; dsCad.DataSet.Close; except // end; Action := caFree; end; procedure TfrmBaseCadastro.FormCreate(Sender: TObject); var Imagem: TfrmImagens; begin Imagem := TfrmImagens.Create(Self); try btnPrimeiro.Glyph := Imagem.btnPrimeiro.Glyph; btnAnterior.Glyph := Imagem.btnAnterior.Glyph; btnProximo.Glyph := Imagem.btnProximo.Glyph; btnUltimo.Glyph := Imagem.btnUltimo.Glyph; btnNovo.Glyph := Imagem.btnNovo.Glyph; btnEditar.Glyph := Imagem.btnEditar.Glyph; btnExcluir.Glyph := Imagem.btnExcluir.Glyph; btnFiltrar.Glyph := Imagem.btnFiltrar.Glyph; btnSair.Glyph := Imagem.btnSair.Glyph; btnSalvar.Glyph := Imagem.btnSalvar.Glyph; btnCancelar.Glyph := Imagem.btnCancelar.Glyph; btnFiltro.Glyph := Imagem.btnFiltro.Glyph; btnImprimir.Glyph := Imagem.btnImprimir.Glyph; btnPrimeiro.Glyph := Imagem.btnPrimeiro.Glyph; btnFecharFiltro.Glyph := Imagem.btnRetornar.Glyph; finally FreeAndNil(Imagem); end; end; procedure TfrmBaseCadastro.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT : Novo; VK_F2 : Editar; VK_F3 : Filtrar; VK_F4 : Filtro; VK_F7 : Imprimir; VK_F8 : Salvar; VK_F12 : Selecionar; VK_ESCAPE : begin if tsPesquisa.Showing then Close else begin if tsEdicao.Showing then begin if dsCad.DataSet.State in [dsEdit, dsInsert] then begin begin btnCancelar.SetFocus; btnCancelarClick(Self); end; // raise Exception.Create('Salve ou Cancele para Sair.'); end else TelaPesquisar; end else TelaPesquisar; // try // edtDescricao.SetFocus; // except // // nada // end; end; end; end; if (Shift = [ssCtrl]) and (Key = VK_DELETE) then Excluir; if (Shift = [ssCtrl]) and (Key = 79) then // CTRL + O NavegarProximo; if (Shift = [ssCtrl]) and (Key = 73) then // CTRL + I NavegarAnterior; // if (Shift = [ssCtrl]) and (Key = VK_HOME) then // CTRL + HOME if Key = VK_LEFT then begin if edtDescricao.Focused then NavegarPrimeiroRegistro; end; // if (Shift = [ssCtrl]) and (Key = VK_END) then // CTRL + END if Key = VK_RIGHT then begin if edtDescricao.Focused then NavegarUltimoRegistro; end; // if (Shift = [ssCtrl]) and (Key = VK_UP) then // CTRL + ^ if Key = VK_UP then begin if edtDescricao.Focused then NavegarRegistroAnterior; end; // if (Shift = [ssCtrl]) and (Key = VK_DOWN) then // CTRL + v if Key = VK_DOWN then begin if edtDescricao.Focused then NavegarProximoRegistro; end; end; procedure TfrmBaseCadastro.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin key:=#0; perform(Wm_NextDlgCtl,0,0); end; end; procedure TfrmBaseCadastro.FormShow(Sender: TObject); //var // i: Integer; var Botao: TPosicaoBotao; iPosicao: Integer; begin TelaPesquisar; pgControl.TabIndex := 0; PageControl2.TabIndex := 0; // FGrade := TGrade.Create; // for i := 0 to dbDados.Columns.Count -1 do // cbbCampos.Items.Add(dbDados.Columns[i].Title.Caption); // cbbCampos.ItemIndex := 1; if edtDescricao.Visible then edtDescricao.SetFocus; end; procedure TfrmBaseCadastro.Imprimir; begin if tsFiltro.Showing then begin btnImprimir.SetFocus; btnImprimir.Click; end; end; procedure TfrmBaseCadastro.Navegar; var sCampo: string; i: Integer; begin for I := 0 to dbDados.Columns.Count -1 do begin if dbDados.Columns[i].Title.Caption = cbbCampos.Text then begin sCampo := dbDados.Columns[i].FieldName; Break; end; end; (dsPesquisa.DataSet as TClientDataSet).IndexFieldNames := sCampo; end; procedure TfrmBaseCadastro.NavegarAnterior; begin if tsPesquisa.Showing then begin if cbbCampos.ItemIndex = 0 then cbbCampos.ItemIndex := 1; cbbCampos.ItemIndex := cbbCampos.ItemIndex - 1; Navegar(); edtDescricao.SetFocus; end; end; procedure TfrmBaseCadastro.NavegarPrimeiroRegistro; begin if tsPesquisa.Showing then btnPrimeiro.Click; end; procedure TfrmBaseCadastro.NavegarProximo; begin if tsPesquisa.Showing then begin cbbCampos.ItemIndex := cbbCampos.ItemIndex + 1; Navegar(); edtDescricao.SetFocus; end; end; procedure TfrmBaseCadastro.NavegarProximoRegistro; begin if tsPesquisa.Showing then btnProximo.Click; end; procedure TfrmBaseCadastro.NavegarRegistroAnterior; begin if tsPesquisa.Showing then btnAnterior.Click; end; procedure TfrmBaseCadastro.NavegarUltimoRegistro; begin if tsPesquisa.Showing then btnUltimo.Click; // btnEditar.Click; end; procedure TfrmBaseCadastro.Novo; begin if tsPesquisa.Showing then begin if btnNovo.Visible then btnNovo.Click; end; end; procedure TfrmBaseCadastro.Ordenar; var i: Integer; begin if not dsPesquisa.DataSet.Active then Exit; if not dsPesquisa.DataSet.IsEmpty then begin for i := 0 to dbDados.Columns.Count-1 do begin if cbbCampos.Text = dbDados.Columns[i].Title.Caption then begin (dsPesquisa.DataSet as TClientDataSet).IndexFieldNames := dbDados.Columns[i].FieldName; Break; end; end; end; end; procedure TfrmBaseCadastro.Salvar; begin if tsEdicao.Showing then begin if btnSalvar.Enabled then begin btnSalvar.SetFocus; btnSalvar.Click; end; end; end; procedure TfrmBaseCadastro.Selecionar; begin if tsPesquisa.Showing then begin if dsPesquisa.DataSet.RecordCount > 0 then begin if FPesquisa then begin dm.IdSelecionado := dbDados.Columns[0].Field.AsInteger; Close; end; end; end; end; procedure TfrmBaseCadastro.TelaEdicao; begin tsPesquisa.TabVisible := False; tsEdicao.TabVisible := True; tsFiltro.TabVisible := False; end; procedure TfrmBaseCadastro.TelaFiltro; begin tsPesquisa.TabVisible := False; tsEdicao.TabVisible := False; tsFiltro.TabVisible := True; end; procedure TfrmBaseCadastro.TelaPesquisar; begin tsPesquisa.TabVisible := True; tsEdicao.TabVisible := False; tsFiltro.TabVisible := False; PageControl2.TabIndex := 0; pgControl.TabIndex := 0; try if FPosicaoGrade > 0 then dsPesquisa.DataSet.RecNo := FPosicaoGrade; edtDescricao.SetFocus; except // nada end; end; end.
unit udmDBCore; interface uses Windows, Classes, SysUtils, DB, DBClient, Forms, Ora, uSupportLib, Variants, OraError; const CrLf = #13#10; resourcestring stCheckDel = 'Confermi l''eliminazione del record?'; stDeadlock = 'Il record corrente è attualmente in uso oppure bloccato'; stReqDErr = 'Inserire il valore'; stDuplicateRec = 'Il codice inserito è già utilizzato!'; stMaxCod = 'Codice maggiore dell''ultimo inserito!'; stDsError = 'Errore in fase di apertura del DataSet: '; stRecNotFound = 'Codice non presente!'; type TdmState = (hdmInsert, hdmEdit, hdmView, hdmDelete); TdmType = (hdmRead, hdmWrite, hdmReadWrite); TdmTipAttNum = (hPrgAut, hPrgMan, hPrgAutAaa); TdmDBCore = class; TdmDBCore = class(TDataModule) private { Private declarations } FhDataSet: TDataSet; FhdmType: TdmType; FhKeyValues: TStringList; FhKeyFields: TStringList; FhdmState: TdmState; FhTipAttNum: TdmTipAttNum; procedure SetValuesToDefault(DataSet: TDataSet); procedure SetDataSetsMethods; procedure SethKeyFields(const Value: TStringList); procedure SethKeyValues(const Value: TStringList); protected procedure dmAfterInsert(DataSet: TDataSet); virtual; procedure dmAfterEdit(DataSet: TDataSet); virtual; procedure dmAfterOpen(DataSet: TDataSet); virtual; procedure dmAfterPost(DataSet: TDataSet); virtual; procedure dmBeforeInsert(DataSet: TDataSet); virtual; procedure dmBeforeEdit(DataSet: TDataSet); virtual; procedure dmBeforeOpen(DataSet: TDataSet); virtual; procedure dmBeforePost(DataSet: TDataSet); virtual; function dmCheckValidateData: boolean; virtual; public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; function dmDsApplyUpdates(DataSet: TClientDataSet): boolean; virtual; procedure dmDsCancel(DataSet: TDataSet); virtual; procedure dmDsClose(DataSet: TDataSet); virtual; function dmDsDelete(DataSet: TDataSet): boolean; virtual; function dmDsEdit(DataSet: TDataSet): boolean; virtual; function dmDsInsert(DataSet: TDataSet): boolean; virtual; function dmDsOpen(DataSet: TDataSet): boolean; virtual; function dmDsPost(DataSet: TDataSet): boolean; virtual; procedure dmDsRefresh(DataSet: TDataSet); virtual; function dmExecStoredProc(ASp: TOraStoredProc): boolean; virtual; procedure dmOpenAll; virtual; function dmPostAll: boolean; virtual; procedure dmCloseAll; virtual; function getCodValKey: String; procedure SetKeyValues; procedure SetMasterParams; property hdmState : TdmState read FhdmState write FhdmState; published property hDataSet : TDataSet read FhDataSet write FhDataSet; property hdmType : TdmType read FhdmType write FhdmType default hdmRead; property hKeyFields : TStringList read FhKeyFields write SethKeyFields; property hKeyValues : TStringList read FhKeyValues write SethKeyValues; property hTipAttNum : TdmTipAttNum read FhTipAttNum write FhTipAttNum default hPrgAut; end; var dmDBCore: TdmDBCore; implementation uses Dialogs; constructor TdmDBCore.Create(Owner: TComponent); begin FhKeyFields := TStringList.Create; FhKeyValues := TStringList.Create; FhdmState := hdmView; inherited Create(Owner); SetDataSetsMethods; end; destructor TdmDBCore.Destroy; begin FhKeyValues.Free; FhKeyFields.Free; inherited Destroy; end; procedure TdmDBCore.dmAfterInsert(DataSet: TDataSet); begin SetValuesToDefault(DataSet); end; procedure TdmDBCore.dmAfterEdit(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmAfterOpen(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmAfterPost(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmBeforeInsert(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmBeforeEdit(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmBeforeOpen(DataSet: TDataSet); begin // do nothing end; procedure TdmDBCore.dmBeforePost(DataSet: TDataSet); begin SetValuesToDefault(DataSet); if Assigned(DataSet.FindField('Des_Pdl')) then DataSet.FieldByName('Des_Pdl').AsString := GetMachineName; if Assigned(DataSet.FindField('Dat_Agg_Rec')) then DataSet.FieldByName('Dat_Agg_Rec').AsDateTime := Now; end; {$Hints Off} function TdmDBCore.dmDsApplyUpdates(DataSet: TClientDataSet): boolean; begin try try DataSet.ApplyUpdates(-1); finally Result := True; end; except on E : Exception do begin MessageDlg(E.Message, mtWarning, [mbOK], 0); Result := False; end; end; end; function TdmDBCore.dmDsDelete(DataSet: TDataSet): boolean; begin try try DataSet.Delete; finally Result := True; end; except on E : Exception do begin MessageDlg(E.Message, mtWarning, [mbOK], 0); Result := False; end; end; end; function TdmDBCore.dmDsEdit(DataSet: TDataSet): boolean; begin try try DataSet.Edit; except Result := False; end; finally Result := True; end; end; function TdmDBCore.dmDsInsert(DataSet: TDataSet): boolean; begin try try DataSet.Insert; except Result := False; end; finally Result := True; end; end; function TdmDBCore.dmDsOpen(DataSet: TDataSet): boolean; begin try try DataSet.Open; except on E:Exception do begin MessageDlg(E.Message, mtInformation, [mbOK], 0); Result := False; end; end; finally Result := True; end; end; function TdmDBCore.dmDsPost(DataSet: TDataSet): boolean; begin try try DataSet.Post; except Result := False; end; finally Result := True; end; end; {$Hints On} procedure TdmDBCore.dmDsCancel(DataSet: TDataSet); begin try DataSet.Cancel; except end; end; procedure TdmDBCore.dmDsClose(DataSet: TDataSet); begin try DataSet.Close; except end; end; procedure TdmDBCore.dmDsRefresh(DataSet: TDataSet); begin try try dmDsClose(DataSet); finally dmDsOpen(DataSet); end; except end; end; function TdmDBCore.dmExecStoredProc(ASp: TOraStoredProc): boolean; begin Result := False; if ASp.StoredProcName <> '' then begin if Assigned(ASp.FindParam('iDes_Pdl')) then ASp.ParamByName('iDes_Pdl').AsString := GetMachineName; if Assigned(ASp.FindParam('iDat_Agg_Rec')) then ASp.ParamByName('iDat_Agg_Rec').AsDateTime := Now; try ASp.Execute; finally Result := True; end; end; end; function TdmDBCore.dmCheckValidateData: boolean; begin Result := True; end; procedure TdmDBCore.dmCloseAll; var i : integer; begin for i := 0 to ComponentCount - 1 do if Components[i] is TClientDataSet then dmDsClose(TClientDataSet(Components[i])); end; procedure TdmDBCore.dmOpenAll; var i : integer; begin if Assigned(hDataSet) then if dmDsOpen(hDataSet) then begin for i := 0 to ComponentCount - 1 do begin if (Components[i] is TClientDataSet) and (Components[i] <> hDataSet) then if not dmDsOpen(TClientDataSet(Components[i])) then begin MessageDlg(stDsError+TClientDataSet(Components[i]).Name, mtError, [mbOK], 0); Break; end; end; for i := 0 to ComponentCount - 1 do begin if (Components[i] is TDataSource) and (TDataSource(Components[i]).DataSet is TOraQuery) and (TDataSource(Components[i]).DataSet <> hDataSet) then if not dmDsOpen(TOraQuery(TDataSource(Components[i]).DataSet)) then begin MessageDlg(stDsError+TOraQuery(Components[i]).Name, mtError, [mbOK], 0); Break; end; end; end; if Assigned(hDataSet) then hDataSet.First; end; function TdmDBCore.dmPostAll: boolean; var i : integer; begin if dmDsPost(hDataSet) then begin if dmDsApplyUpdates(TClientDataSet(hDataSet)) then begin Result := True; for i := 0 to ComponentCount - 1 do if (Components[i] is TClientDataSet) and (Components[i] <> hDataSet) then begin Result := dmDsApplyUpdates(TClientDataSet(Components[i])); if not Result then Break; end; end else Result := False; end else Result := False; end; procedure TdmDBCore.SetDataSetsMethods; var i : integer; begin for i := 0 to ComponentCount - 1 do if Components[i] is TDataSet then begin TDataSet(Components[i]).AfterInsert := dmAfterInsert; TDataSet(Components[i]).AfterEdit := dmAfterEdit; TDataSet(Components[i]).AfterOpen := dmAfterOpen; TDataSet(Components[i]).AfterPost := dmAfterPost; TDataSet(Components[i]).BeforeInsert := dmBeforeInsert; TDataSet(Components[i]).BeforeEdit := dmBeforeEdit; TDataSet(Components[i]).BeforeOpen := dmBeforeOpen; TDataSet(Components[i]).BeforePost := dmBeforePost; TDataSet(Components[i]).FilterOptions := [foCaseInsensitive]; end; end; procedure TdmDBCore.SethKeyFields(const Value: TStringList); begin if Assigned(Value) then FhKeyFields.Assign(Value); end; procedure TdmDBCore.SethKeyValues(const Value: TStringList); begin if Assigned(Value) then FhKeyValues.Assign(Value); end; procedure TdmDBCore.SetKeyValues; var i : integer; begin Self.hKeyValues.Clear; for i := 0 to Self.hKeyFields.Count - 1 do if not Self.hDataSet.FieldByName(Self.hKeyFields[i]).IsNull then Self.hKeyValues.Append(VarToStr(Self.hDataSet.FieldByName(Self.hKeyFields[i]).Value)) else Self.hKeyValues.Append(''); end; function TdmDBCore.getCodValKey: String; var i : integer; AppKey: String; begin AppKey := ''; for i := 0 to hKeyValues.Count - 1 do AppKey := AppKey + hKeyValues[i]; Result := AppKey; end; procedure TdmDBCore.SetMasterParams; var i : integer; OraQuery : TOraQuery; begin if Assigned(hDataSet) then begin if hDataSet is TClientDataSet then OraQuery := TOraQuery(GetDataSetFromClientDataSet(TClientDataSet(hDataSet))) else OraQuery := TOraQuery(hDataSet); for i := 0 to hKeyValues.Count - 1 do if Assigned(OraQuery.FindParam(hKeyFields[i])) then OraQuery.ParamByName(hKeyFields[i]).Value := hKeyValues[i]; end; end; procedure TdmDBCore.SetValuesToDefault(DataSet: TDataSet); var i : integer; begin with DataSet do for i := 0 to DataSet.Fields.Count - 1 do if (Pos('ID_', ANSIUpperCase(DataSet.Fields[i].FieldName)) = 0) and DataSet.Fields[i].IsNull then case DataSet.Fields[i].DataType of ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftLargeint : DataSet.Fields[i].Value := 0; end; end; end.
unit TTSNOTCTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSNOTCRecord = record PLenderNum: String[4]; PCategory: String[8]; PStage: String[1]; PModCount: Integer; End; TTTSNOTCBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSNOTCRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSNOTC = (TTSNOTCPrimaryKey); TTTSNOTCTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCategory: TStringField; FDFStage: TStringField; FDFModCount: TIntegerField; FDFNoticeText: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCategory(const Value: String); function GetPCategory:String; procedure SetPStage(const Value: String); function GetPStage:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetEnumIndex(Value: TEITTSNOTC); function GetEnumIndex: TEITTSNOTC; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSNOTCRecord; procedure StoreDataBuffer(ABuffer:TTTSNOTCRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCategory: TStringField read FDFCategory; property DFStage: TStringField read FDFStage; property DFModCount: TIntegerField read FDFModCount; property DFNoticeText: TBlobField read FDFNoticeText; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCategory: String read GetPCategory write SetPCategory; property PStage: String read GetPStage write SetPStage; property PModCount: Integer read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEITTSNOTC read GetEnumIndex write SetEnumIndex; end; { TTTSNOTCTable } procedure Register; implementation procedure TTTSNOTCTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCategory := CreateField( 'Category' ) as TStringField; FDFStage := CreateField( 'Stage' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFNoticeText := CreateField( 'NoticeText' ) as TBlobField; end; { TTTSNOTCTable.CreateFields } procedure TTTSNOTCTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSNOTCTable.SetActive } procedure TTTSNOTCTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSNOTCTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSNOTCTable.SetPCategory(const Value: String); begin DFCategory.Value := Value; end; function TTTSNOTCTable.GetPCategory:String; begin result := DFCategory.Value; end; procedure TTTSNOTCTable.SetPStage(const Value: String); begin DFStage.Value := Value; end; function TTTSNOTCTable.GetPStage:String; begin result := DFStage.Value; end; procedure TTTSNOTCTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSNOTCTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSNOTCTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('Category, String, 8, N'); Add('Stage, String, 1, N'); Add('ModCount, Integer, 0, N'); Add('NoticeText, Memo, 0, N'); end; end; procedure TTTSNOTCTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;Category;Stage, Y, Y, N, N'); end; end; procedure TTTSNOTCTable.SetEnumIndex(Value: TEITTSNOTC); begin case Value of TTSNOTCPrimaryKey : IndexName := ''; end; end; function TTTSNOTCTable.GetDataBuffer:TTTSNOTCRecord; var buf: TTTSNOTCRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCategory := DFCategory.Value; buf.PStage := DFStage.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TTTSNOTCTable.StoreDataBuffer(ABuffer:TTTSNOTCRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCategory.Value := ABuffer.PCategory; DFStage.Value := ABuffer.PStage; DFModCount.Value := ABuffer.PModCount; end; function TTTSNOTCTable.GetEnumIndex: TEITTSNOTC; var iname : string; begin result := TTSNOTCPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSNOTCPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSNOTCTable, TTTSNOTCBuffer ] ); end; { Register } function TTTSNOTCBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..4] of string = ('LENDERNUM','CATEGORY','STAGE','MODCOUNT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 4) and (flist[x] <> s) do inc(x); if x <= 4 then result := x else result := 0; end; function TTTSNOTCBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; end; end; function TTTSNOTCBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCategory; 3 : result := @Data.PStage; 4 : result := @Data.PModCount; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.8 10/26/2004 8:12:30 PM JPMugaas Now uses TIdStrings and TIdStringList for portability. Rev 1.7 6/11/2004 8:28:56 AM DSiders Added "Do not Localize" comments. Rev 1.6 5/14/2004 12:14:50 PM BGooijen Fix for weird dotnet bug when querying the local binding Rev 1.5 4/18/04 2:45:54 PM RLebeau Conversion support for Int64 values Rev 1.4 2004.03.07 11:45:26 AM czhower Flushbuffer fix + other minor ones found Rev 1.3 3/6/2004 5:16:30 PM JPMugaas Bug 67 fixes. Do not write to const values. Rev 1.2 2/10/2004 7:33:26 PM JPMugaas I had to move the wrapper exception here for DotNET stack because Borland's update 1 does not permit unlisted units from being put into a package. That now would report an error and I didn't want to move IdExceptionCore into the System package. Rev 1.1 2/4/2004 8:48:30 AM JPMugaas Should compile. Rev 1.0 2004.02.03 3:14:46 PM czhower Move and updates Rev 1.32 2/1/2004 6:10:54 PM JPMugaas GetSockOpt. Rev 1.31 2/1/2004 3:28:32 AM JPMugaas Changed WSGetLocalAddress to GetLocalAddress and moved into IdStack since that will work the same in the DotNET as elsewhere. This is required to reenable IPWatch. Rev 1.30 1/31/2004 1:12:54 PM JPMugaas Minor stack changes required as DotNET does support getting all IP addresses just like the other stacks. Rev 1.29 2004.01.22 2:46:52 PM czhower Warning fixed. Rev 1.28 12/4/2003 3:14:54 PM BGooijen Added HostByAddress Rev 1.27 1/3/2004 12:22:14 AM BGooijen Added function SupportsIPv6 Rev 1.26 1/2/2004 4:24:08 PM BGooijen This time both IPv4 and IPv6 work Rev 1.25 02/01/2004 15:58:00 HHariri fix for bind Rev 1.24 12/31/2003 9:52:00 PM BGooijen Added IPv6 support Rev 1.23 10/28/2003 10:12:36 PM BGooijen DotNet Rev 1.22 10/26/2003 10:31:16 PM BGooijen oops, checked in debug version <g>, this is the right one Rev 1.21 10/26/2003 5:04:26 PM BGooijen UDP Server and Client Rev 1.20 10/21/2003 11:03:50 PM BGooijen More SendTo, ReceiveFrom Rev 1.19 10/21/2003 9:24:32 PM BGooijen Started on SendTo, ReceiveFrom Rev 1.18 10/19/2003 5:21:30 PM BGooijen SetSocketOption Rev 1.17 10/11/2003 4:16:40 PM BGooijen Compiles again Rev 1.16 10/5/2003 9:55:28 PM BGooijen TIdTCPServer works on D7 and DotNet now Rev 1.15 10/5/2003 3:10:42 PM BGooijen forgot to clone the Sockets list in some Select methods, + added Listen and Accept Rev 1.14 10/5/2003 1:52:14 AM BGooijen Added typecasts with network ordering calls, there are required for some reason Rev 1.13 10/4/2003 10:39:38 PM BGooijen Renamed WSXXX functions in implementation section too Rev 1.12 04/10/2003 22:32:00 HHariri moving of WSNXXX method to IdStack and renaming of the DotNet ones Rev 1.11 04/10/2003 21:28:42 HHariri Netowkr ordering functions Rev 1.10 10/3/2003 11:02:02 PM BGooijen fixed calls to Socket.Select Rev 1.9 10/3/2003 11:39:38 PM GGrieve more work Rev 1.8 10/3/2003 12:09:32 AM BGooijen DotNet Rev 1.7 10/2/2003 8:23:52 PM BGooijen .net Rev 1.6 10/2/2003 8:08:52 PM BGooijen .Connect works not in .net Rev 1.5 10/2/2003 7:31:20 PM BGooijen .net Rev 1.4 10/2/2003 6:12:36 PM GGrieve work in progress (hardly started) Rev 1.3 2003.10.01 9:11:24 PM czhower .Net Rev 1.2 2003.10.01 5:05:18 PM czhower .Net Rev 1.1 2003.10.01 1:12:40 AM czhower .Net Rev 1.0 2003.09.30 10:35:40 AM czhower Initial Checkin } unit IdStackDotNet; interface {$i IdCompilerDefines.inc} uses Classes, IdGlobal, IdStack, IdStackConsts, System.Collections, System.IO, System.Net, System.Net.Sockets; type TIdSocketListDotNet = class(TIdSocketList) protected FSockets: ArrayList; function GetItem(AIndex: Integer): TIdStackSocketHandle; override; public constructor Create; override; destructor Destroy; override; procedure Add(AHandle: TIdStackSocketHandle); override; procedure Remove(AHandle: TIdStackSocketHandle); override; function Count: Integer; override; procedure Clear; override; function Clone: TIdSocketList; override; function ContainsSocket(AHandle: TIdStackSocketHandle): boolean; override; class function Select(AReadList: TIdSocketList; AWriteList: TIdSocketList; AExceptList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; function SelectRead(const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; function SelectReadList(var VSocketList: TIdSocketList; const ATimeout: Integer = IdTimeoutInfinite): Boolean; override; end; TIdStackDotNet = class(TIdStack) protected //Stuff for ICMPv6 {$IFDEF DOTNET_2_OR_ABOVE} procedure QueryRoute(s : TIdStackSocketHandle; const AIP: String; const APort: TIdPort; var VSource, VDest : TIdBytes); procedure WriteChecksumIPv6(s: TIdStackSocketHandle; var VBuffer: TIdBytes; const AOffset: Integer; const AIP: String; const APort: TIdPort); {$ENDIF} function ReadHostName: string; override; function HostByName(const AHostName: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; override; //internal IP Mutlicasting membership stuff procedure MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const ASockOpt : TIdSocketOption; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); public [ThreadStatic] LastSocketError: Integer; //static; constructor Create; override; destructor Destroy; override; procedure Bind(ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION ); override; procedure Connect(const ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure Disconnect(ASocket: TIdStackSocketHandle); override; procedure GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion); override; procedure GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion); override; function WSGetLastError: Integer; override; procedure WSSetLastError(const AErr : Integer); override; function NewSocketHandle(const ASocketType: TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = False) : TIdStackSocketHandle; override; // Result: // > 0: Number of bytes received // 0: Connection closed gracefully // Will raise exceptions in other cases function Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes) : Integer; override; function Send(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer = 0; const ASize: Integer = -1): Integer; override; function IOControl(const s: TIdStackSocketHandle; const cmd: LongWord; var arg: LongWord): Integer; override; function ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; override; function ReceiveMsg(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; APkt: TIdPacketInfo): LongWord; override; function SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const ASize: Integer; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; override; function HostToNetwork(AValue: Word): Word; override; function NetworkToHost(AValue: Word): Word; override; function HostToNetwork(AValue: LongWord): LongWord; override; function NetworkToHost(AValue: LongWord): LongWord; override; function HostToNetwork(AValue: Int64): Int64; override; function NetworkToHost(AValue: Int64): Int64; override; function HostByAddress(const AAddress: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; override; procedure Listen(ASocket: TIdStackSocketHandle; ABackLog: Integer);override; function Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): TIdStackSocketHandle; override; procedure GetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; out AOptVal: Integer); override; procedure SetSocketOption(ASocket: TIdStackSocketHandle; ALevel:TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer); overload; override; function SupportsIPv6: Boolean; override; //multicast stuff Kudzu permitted me to add here. procedure SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue : Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure WriteChecksum(s : TIdStackSocketHandle; var VBuffer : TIdBytes; const AOffset : Integer; const AIP : String; const APort : TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure AddLocalAddressesToList(AAddresses: TStrings); override; procedure SetKeepAliveValues(ASocket: TIdStackSocketHandle; const AEnabled: Boolean; const ATimeMS, AInterval: Integer); override; end; {$IFDEF DOTNET_1_1} EIdNotSupportedInMicrosoftNET11 = class(EIdStackError); {$ENDIF} var GDotNETStack : TIdStackDotNet = nil; implementation uses IdException, IdResourceStrings {$IFDEF DOTNET_1_1} , IdResourceStringsDotNet11 {$ENDIF} ; const IdIPFamily : array[TIdIPVersion] of AddressFamily = (AddressFamily.InterNetwork, AddressFamily.InterNetworkV6); { TIdStackDotNet } function BuildException(AStack: TIdStackDotNet; AException: System.Exception) : EIdException; var LSocketError : System.Net.Sockets.SocketException; begin if AException is System.Net.Sockets.SocketException then begin LSocketError := AException as System.Net.Sockets.SocketException; AStack.LastSocketError := LSocketError.ErrorCode; Result := EIdSocketError.CreateError(LSocketError.ErrorCode, LSocketError.Message) end else begin Result := EIdWrapperException.Create(AException.Message, AException); end; end; { TIdStackDotNet } constructor TIdStackDotNet.Create; begin inherited Create; GDotNETStack := Self; end; destructor TIdStackDotNet.Destroy; begin GDotNETStack := nil; inherited Destroy; end; procedure TIdStackDotNet.Bind(ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LIPAddr : IPAddress; LEndPoint : IPEndPoint; LIP: String; begin try if not (AIPVersion in [Id_IPv4, Id_IPv6]) then begin IPVersionUnsupported; end; LIP := AIP; if LIP = '' then begin if AIPVersion = Id_IPv4 then begin LIPAddr := IPAddress.Any; end else begin LIPAddr := IPAddress.IPv6Any; end; end else begin LIPAddr := IPAddress.Parse(LIP); end; LEndPoint := IPEndPoint.Create(LIPAddr, APort); ASocket.Bind(LEndPoint); except on e: Exception do begin raise BuildException(Self, e); end; end; end; procedure TIdStackDotNet.Connect(const ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LEndPoint : IPEndPoint; begin try LEndPoint := IPEndPoint.Create(IPAddress.Parse(AIP), APort); ASocket.Connect(LEndPoint); except on e: Exception do begin raise BuildException(Self, e); end; end; end; procedure TIdStackDotNet.Disconnect(ASocket: TIdStackSocketHandle); begin try ASocket.Close; except on e: Exception do begin raise BuildException(Self, e); end; end; end; procedure TIdStackDotNet.Listen(ASocket: TIdStackSocketHandle; ABackLog: Integer); begin try ASocket.Listen(ABackLog); except on e: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.Accept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): TIdStackSocketHandle; var LEndPoint: IPEndPoint; begin try Result := ASocket.Accept(); LEndPoint := Result.RemoteEndPoint as IPEndPoint; if (Result.AddressFamily = AddressFamily.InterNetwork) or (Result.AddressFamily = AddressFamily.InterNetworkV6) then begin VIP := LEndPoint.Address.ToString(); VPort := LEndPoint.Port; if Result.AddressFamily = AddressFamily.InterNetworkV6 then begin VIPVersion := Id_IPv6; end else begin VIPVersion := Id_IPv4; end; end else begin Result := Id_INVALID_SOCKET; IPVersionUnsupported; end; except on e: Exception do begin raise BuildException(Self, e); end; end; end; procedure TIdStackDotNet.GetPeerName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion); var LEndPoint : IPEndPoint; begin try if (ASocket.AddressFamily = AddressFamily.InterNetwork) or (ASocket.AddressFamily = AddressFamily.InterNetworkV6) then begin LEndPoint := ASocket.RemoteEndPoint as IPEndPoint; VIP := LEndPoint.Address.ToString; VPort := LEndPoint.Port; if ASocket.AddressFamily = AddressFamily.InterNetworkV6 then begin VIPVersion := Id_IPv6; end else begin VIPVersion := Id_IPv4; end; end else begin IPVersionUnsupported; end; except on e: Exception do begin raise BuildException(Self, e); end; end; end; procedure TIdStackDotNet.GetSocketName(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion); var LEndPoint : IPEndPoint; begin try if (ASocket.AddressFamily = AddressFamily.InterNetwork) or (ASocket.AddressFamily = AddressFamily.InterNetworkV6) then begin LEndPoint := ASocket.LocalEndPoint as IPEndPoint; VIP := LEndPoint.Address.ToString; VPort := LEndPoint.Port; if ASocket.AddressFamily = AddressFamily.InterNetworkV6 then begin VIPVersion := Id_IPv6; end else begin VIPVersion := Id_IPv4; end; end else begin IPVersionUnsupported; end; except on e: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.HostByName(const AHostName: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; var LIP: array of IPAddress; a: Integer; begin try { [Warning] IdStackDotNet.pas(417): W1000 Symbol 'Resolve' is deprecated: 'Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202' } {$IFDEF DOTNET_2_OR_ABOVE} LIP := Dns.GetHostEntry(AHostName).AddressList; {$ENDIF} {$IFDEF DOTNET_1_1} LIP := Dns.Resolve(AHostName).AddressList; {$ENDIF} for a := Low(LIP) to High(LIP) do begin if LIP[a].AddressFamily = IdIPFamily[AIPVersion] then begin Result := LIP[a].ToString; Exit; end; end; raise System.Net.Sockets.SocketException.Create(11001); except on e: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.HostByAddress(const AAddress: string; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): string; begin try {$IFDEF DOTNET_2_OR_ABOVE} Result := Dns.GetHostEntry(AAddress).HostName; {$ENDIF} {$IFDEF DOTNET_1_1} Result := Dns.GetHostByAddress(AAddress).HostName; {$ENDIF} except on e: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.WSGetLastError: Integer; begin Result := LastSocketError; end; procedure TIdStackDotNet.WSSetLastError(const AErr : Integer); begin LastSocketError := AErr; end; function TIdStackDotNet.NewSocketHandle(const ASocketType: TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = False): TIdStackSocketHandle; begin try Result := Socket.Create(IdIPFamily[AIPVersion], ASocketType, AProtocol); except on E: Exception do begin raise BuildException(Self, E); end; end; end; function TIdStackDotNet.ReadHostName: string; begin try Result := System.Net.DNS.GetHostName; except on E: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes): Integer; begin try Result := ASocket.Receive(VBuffer, Length(VBuffer), SocketFlags.None); except on e: Exception do begin raise BuildException(Self, e); end; end; end; function TIdStackDotNet.Send(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer = 0; const ASize: Integer = -1): Integer; begin Result := IndyLength(ABuffer, ASize, AOffset); if Result > 0 then begin try Result := ASocket.Send(ABuffer, AOffset, Result, SocketFlags.None); except on E: Exception do begin raise BuildException(Self, E); end; end; end; end; function TIdStackDotNet.ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; var LIPAddr : IPAddress; LEndPoint : EndPoint; begin Result := 0; // to make the compiler happy case ASocket.AddressFamily of AddressFamily.InterNetwork: LIPAddr := IPAddress.Any; AddressFamily.InterNetworkV6: LIPAddr := IPAddress.IPv6Any; else IPVersionUnsupported; end; LEndPoint := IPEndPoint.Create(LIPAddr, 0); try try Result := ASocket.ReceiveFrom(VBuffer, SocketFlags.None, LEndPoint); except on e: Exception do begin raise BuildException(Self, e); end; end; VIP := IPEndPoint(LEndPoint).Address.ToString; VPort := IPEndPoint(LEndPoint).Port; case IPEndPoint(LEndPoint).AddressFamily of AddressFamily.InterNetwork: VIPVersion := Id_IPv4; AddressFamily.InterNetworkV6: VIPVersion := Id_IPv6; end; finally LEndPoint.Free; end; end; function TIdStackDotNet.SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const ASize: Integer; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; var LEndPoint : EndPoint; begin Result := IndyLength(ABuffer, ASize, AOffset); if Result > 0 then begin LEndPoint := IPEndPoint.Create(IPAddress.Parse(AIP), APort); try try Result := ASocket.SendTo(ABuffer, AOffset, Result, SocketFlags.None, LEndPoint); except on e: Exception do begin raise BuildException(Self, e); end; end; finally LEndPoint.Free; end; end; end; ////////////////////////////////////////////////////////////// constructor TIdSocketListDotNet.Create; begin inherited Create; FSockets := ArrayList.Create; end; destructor TIdSocketListDotNet.Destroy; begin FSockets.Free; inherited Destroy; end; procedure TIdSocketListDotNet.Add(AHandle: TIdStackSocketHandle); begin FSockets.Add(AHandle); end; procedure TIdSocketListDotNet.Clear; begin FSockets.Clear; end; function TIdSocketListDotNet.ContainsSocket(AHandle: TIdStackSocketHandle): Boolean; begin Result := FSockets.Contains(AHandle); end; function TIdSocketListDotNet.Count: Integer; begin Result := FSockets.Count; end; function TIdSocketListDotNet.GetItem(AIndex: Integer): TIdStackSocketHandle; begin Result := (FSockets.Item[AIndex]) as TIdStackSocketHandle; end; procedure TIdSocketListDotNet.Remove(AHandle: TIdStackSocketHandle); begin FSockets.Remove(AHandle); end; const cMaxMSPerLoop = MaxInt div 1000; // max milliseconds per Socket.Select() call function TIdSocketListDotNet.SelectRead(const ATimeout: Integer): Boolean; var LTimeout: Integer; function DoSelect(const AInterval: Integer): Boolean; var LTemp: ArrayList; begin // DotNet updates this object on return, so we need to copy it each time we need it LTemp := ArrayList(FSockets.Clone); try Socket.Select(LTemp, nil, nil, AInterval); Result := LTemp.Count > 0; finally LTemp.Free; end; end; begin Result := False; try // RLebeau 8/27/2007: the .NET docs say that -1 is supposed to // cause an infinite timeout, but it doesn't actually work! // So loop manually instead until Microsoft fixes it... if ATimeout = IdTimeoutInfinite then begin repeat Result := DoSelect(MaxInt); until Result; end else begin // RLebeau: Select() accepts a timeout in microseconds, not // milliseconds, so have to loop anyway to handle timeouts // that are greater then 35 minutes... LTimeout := ATimeout; while LTimeout >= cMaxMSPerLoop do begin Result := DoSelect(cMaxMSPerLoop * 1000); if Result then begin Exit; end; Dec(LTimeout, cMaxMSPerLoop); end; if (not Result) and (LTimeout > 0) then begin Result := DoSelect(LTimeout * 1000); end; end; except on e: ArgumentNullException do begin Result := False; end; on e: Exception do begin raise BuildException(GDotNETStack, e); end; end; end; function TIdSocketListDotNet.SelectReadList(var VSocketList: TIdSocketList; const ATimeout: Integer): Boolean; var LTemp: ArrayList; LTimeout: Integer; function DoSelect(const AInterval: Integer; var VList: ArrayList): Boolean; var LLTemp: ArrayList; begin // DotNet updates this object on return, so we need to copy it each time we need it LLTemp := ArrayList(FSockets.Clone); try Socket.Select(LLTemp, nil, nil, AInterval); Result := LLTemp.Count > 0; if Result then begin VList := LLTemp; LLTemp := nil; end; finally LLTemp.Free; end; end; begin Result := False; try // RLebeau 8/27/2007: the .NET docs say that -1 is supposed to // cause an infinite timeout, but it doesn't actually work! // So loop manually instead until Microsoft fixes it... if ATimeout = IdTimeoutInfinite then begin repeat Result := DoSelect(MaxInt, LTemp); until Result; end else begin // RLebeau: Select() accepts a timeout in microseconds, not // milliseconds, so have to loop anyway to handle timeouts // that are greater then 35 minutes... LTimeout := ATimeout; while LTimeout >= cMaxMSPerLoop do begin Result := DoSelect(cMaxMSPerLoop * 1000, LTemp); if Result then begin Break; end; Dec(LTimeout, cMaxMSPerLoop); end; if (not Result) and (LTimeout > 0) then begin Result := DoSelect(LTimeout * 1000, LTemp); end; end; if Result then begin try if VSocketList = nil then begin VSocketList := TIdSocketList.CreateSocketList; end; TIdSocketListDotNet(VSocketList).FSockets.Free; TIdSocketListDotNet(VSocketList).FSockets := LTemp; except LTemp.Free; raise; end; end; except on e: ArgumentNullException do begin Result := False; end; on e: Exception do begin raise BuildException(GDotNETStack, e); end; end; end; class function TIdSocketListDotNet.Select(AReadList, AWriteList, AExceptList: TIdSocketList; const ATimeout: Integer): Boolean; var LTimeout: Integer; LReadTemp, LWriteTemp, LExceptTemp: ArrayList; function DoSelect(var VReadList, VWriteList, VExceptList: ArrayList; const AInterval: Integer): Boolean; var LLReadTemp: ArrayList; LLWriteTemp: ArrayList; LLExceptTemp: ArrayList; begin LLReadTemp := nil; LLWriteTemp := nil; LLExceptTemp := nil; VReadList := nil; VWriteList := nil; VExceptList := nil; // DotNet updates these objects on return, so we need to copy them each time we need them if Assigned(AReadList) and Assigned(TIdSocketListDotNet(AReadList).FSockets) then begin LLReadTemp := ArrayList(TIdSocketListDotNet(AReadList).FSockets.Clone); end; try if Assigned(AWriteList) and Assigned(TIdSocketListDotNet(AWriteList).FSockets) then begin LLWriteTemp := ArrayList(TIdSocketListDotNet(AWriteList).FSockets.Clone); end; try if Assigned(AExceptList) and Assigned(TIdSocketListDotNet(AExceptList).FSockets) then begin LLExceptTemp := ArrayList(TIdSocketListDotNet(AExceptList).FSockets.Clone); end; try Socket.Select(LLReadTemp, LLWriteTemp, LLExceptTemp, AInterval); Result := (LLReadTemp.Count > 0) or (LLWriteTemp.Count > 0) or (LLExceptTemp.Count > 0); if Result then begin VReadList := LLReadTemp; LLReadTemp:= nil; VWriteList := LLWriteTemp; LLWriteTemp:= nil; VExceptList := LLExceptTemp; LLExceptTemp:= nil; end; finally LLExceptTemp.Free; end; finally LLWriteTemp.Free; end; finally LLReadTemp.Free; end; end; begin Result := False; try // RLebeau 8/27/2007: the .NET docs say that -1 is supposed to // cause an infinite timeout, but it doesn't actually work! // So loop manually instead until Microsoft fixes it... if ATimeout = IdTimeoutInfinite then begin repeat Result := DoSelect( LReadTemp, LWriteTemp, LExceptTemp, MaxInt); until Result; end else begin // RLebeau: Select() accepts a timeout in microseconds, not // milliseconds, so have to loop anyway to handle timeouts // that are greater then 35 minutes... LTimeout := ATimeout; while LTimeout >= cMaxMSPerLoop do begin Result := DoSelect( LReadTemp, LWriteTemp, LExceptTemp, cMaxMSPerLoop * 1000); if Result then begin Break; end; Dec(LTimeout, cMaxMSPerLoop); end; if (not Result) and (LTimeout > 0) then begin Result := DoSelect( LReadTemp, LWriteTemp, LExceptTemp, LTimeout * 1000); end; end; // RLebeau: this method is meant to update the // source lists inlined regardless of the Result... if Assigned(AReadList) then begin TIdSocketListDotNet(AReadList).FSockets.Free; TIdSocketListDotNet(AReadList).FSockets := LReadTemp; end; if Assigned(AWriteList) then begin TIdSocketListDotNet(AWriteList).FSockets.Free; TIdSocketListDotNet(AWriteList).FSockets := LWriteTemp; end; if Assigned(AExceptList) then begin TIdSocketListDotNet(AExceptList).FSockets.Free; TIdSocketListDotNet(AExceptList).FSockets := LExceptTemp; end; except on e: ArgumentNullException do begin Result := False; end; on e: Exception do begin raise BuildException(GDotNETStack, e); end; end; end; function TIdSocketListDotNet.Clone: TIdSocketList; begin Result := TIdSocketListDotNet.Create; //BGO: TODO: make prettier TIdSocketListDotNet(Result).FSockets.Free; TIdSocketListDotNet(Result).FSockets := ArrayList(FSockets.Clone); end; function TIdStackDotNet.HostToNetwork(AValue: Word): Word; begin Result := Word(IPAddress.HostToNetworkOrder(SmallInt(AValue))); end; function TIdStackDotNet.HostToNetwork(AValue: LongWord): LongWord; begin Result := LongWord(IPAddress.HostToNetworkOrder(integer(AValue))); end; function TIdStackDotNet.HostToNetwork(AValue: Int64): Int64; begin Result := IPAddress.HostToNetworkOrder(AValue); end; function TIdStackDotNet.NetworkToHost(AValue: Word): Word; begin Result := Word(IPAddress.NetworkToHostOrder(SmallInt(AValue))); end; function TIdStackDotNet.NetworkToHost(AValue: LongWord): LongWord; begin Result := LongWord(IPAddress.NetworkToHostOrder(Integer(AValue))); end; function TIdStackDotNet.NetworkToHost(AValue: Int64): Int64; begin Result := IPAddress.NetworkToHostOrder(AValue); end; procedure TIdStackDotNet.GetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; out AOptVal: Integer); var L : System.Object; begin L := ASocket.GetSocketOption(ALevel, AoptName); AOptVal := Integer(L); end; procedure TIdStackDotNet.SetSocketOption(ASocket: TIdStackSocketHandle; ALevel: TIdSocketOptionLevel; AOptName: TIdSocketOption; AOptVal: Integer); begin ASocket.SetSocketOption(ALevel, AOptName, AOptVal); end; function TIdStackDotNet.SupportsIPv6: Boolean; begin { [Warning] IdStackDotNet.pas(734): W1000 Symbol 'SupportsIPv6' is deprecated: 'SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. http://go.microsoft.com/fwlink/?linkid=14202' } {$IFDEF DOTNET_2_OR_ABOVE} Result := Socket.OSSupportsIPv6; {$ENDIF} {$IFDEF DOTNET_1_1} Result := Socket.SupportsIPv6; {$ENDIF} end; procedure TIdStackDotNet.AddLocalAddressesToList(AAddresses: TStrings); var {$IFDEF DOTNET_1_1} LAddr : IPAddress; {$ENDIF} LHost : IPHostEntry; i : Integer; begin {$IFDEF DOTNET_2_OR_ABOVE} // TODO: use NetworkInterface.GetAllNetworkInterfaces() instead. // See this article for an example: // http://blogs.msdn.com/b/dgorti/archive/2005/10/04/477078.aspx LHost := DNS.GetHostEntry(DNS.GetHostName); {$ENDIF} {$IFDEF DOTNET_1_1} LAddr := IPAddress.Any; LHost := DNS.GetHostByAddress(LAddr); {$ENDIF} if Length(LHost.AddressList) > 0 then begin AAddresses.BeginUpdate; try for i := Low(LHost.AddressList) to High(LHost.AddressList) do begin //This may be returning various types of addresses. // TODO: support IPv6 addresses if LHost.AddressList[i].AddressFamily = AddressFamily.InterNetwork then begin AAddresses.Add(LHost.AddressList[i].ToString); end; end; finally AAddresses.EndUpdate; end; end; end; procedure TIdStackDotNet.SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin //necessary because SetSocketOption only accepts an integer //see: http://groups-beta.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/6a35c6d9052cfc2b/f01fea11f9a24508?q=SetSocketOption+DotNET&rnum=2&hl=en#f01fea11f9a24508 AHandle.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, iif(AValue, 1, 0)); end; procedure TIdStackDotNet.DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle, AGroupIP, ALocalIP, SocketOptionName.DropMembership); end; procedure TIdStackDotNet.AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle, AGroupIP, ALocalIP, SocketOptionName.AddMembership); end; procedure TIdStackDotNet.SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue: Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin if AIPVersion = Id_IPv4 then begin AHandle.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, AValue); end else begin AHandle.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, AValue); end; end; procedure TIdStackDotNet.MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const ASockOpt: TIdSocketOption; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LM4 : MulticastOption; LM6 : IPv6MulticastOption; LGroupIP, LLocalIP : System.Net.IPAddress; begin LGroupIP := IPAddress.Parse(AGroupIP); if LGroupIP.AddressFamily = AddressFamily.InterNetworkV6 then begin LM6 := IPv6MulticastOption.Create(LGroupIP); AHandle.SetSocketOption(SocketOptionLevel.IPv6, ASockOpt, LM6); end else begin if ALocalIP.Length = 0 then begin LM4 := System.Net.Sockets.MulticastOption.Create(LGroupIP); end else begin LLocalIP := IPAddress.Parse(ALocalIP); LM4 := System.Net.Sockets.MulticastOption.Create(LGroupIP, LLocalIP); end; AHandle.SetSocketOption(SocketOptionLevel.IP, ASockOpt, LM4); end; end; function TIdStackDotNet.ReceiveMsg(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; APkt: TIdPacketInfo): LongWord; var {$IFDEF DOTNET_1_1} LIP : String; LPort : TIdPort; LIPVersion: TIdIPVersion; {$ELSE} LSF : SocketFlags; LIPAddr : IPAddress; LRemEP : EndPoint; LPki : IPPacketInformation; {$ENDIF} begin {$IFDEF DOTNET_1_1} Result := ReceiveFrom(ASocket, VBuffer, LIP, LPort, LIPVersion); APkt.Reset; APkt.SourceIP := LIP; APkt.SourcePort := LPort; APkt.SourceIPVersion := LIPVersion; APkt.DestIPVersion := LIPVersion; {$ELSE} LSF := SocketFlags.None; { The AddressFamily of the EndPoint used in ReceiveFrom needs to match the AddressFamily of the EndPoint used in SendTo. } case ASocket.AddressFamily of AddressFamily.InterNetwork: LIPAddr := IPAddress.Any; AddressFamily.InterNetworkV6: LIPAddr := IPAddress.IPv6Any; else Result := 0; // keep the compiler happy IPVersionUnsupported; end; LRemEP := IPEndPoint.Create(LIPAddr, 0); Result := ASocket.ReceiveMessageFrom(VBuffer, 0, Length(VBUffer), LSF, LRemEP, lpki); APkt.Reset; APkt.SourceIP := IPEndPoint(LRemEP).Address.ToString; APkt.SourcePort := IPEndPoint(LRemEP).Port; case IPEndPoint(LRemEP).AddressFamily of AddressFamily.InterNetwork: APkt.SourceIPVersion := Id_IPv4; AddressFamily.InterNetworkV6: APkt.SourceIPVersion := Id_IPv6; end; APkt.DestIP := LPki.Address.ToString; APkt.DestIF := LPki.&Interface; APkt.DestIPVersion := APkt.SourceIPVersion; {$ENDIF} end; { This extracts an IP address as a series of bytes from a TIdBytes that contains one SockAddress structure. } procedure SockAddrToIPBytes(const ASockAddr : TIdBytes; var VIPAddr : TIdBytes); {$IFDEF USE_INLINE}inline;{$ENDIF} begin case IdGlobal.BytesToWord(ASockAddr,0) of 23 : //AddressFamily.InterNetworkV6 : begin //16 = size of SOCKADDR_IN6.sin6_addr SetLength(VIPAddr,16); // 8 = offset of sin6_addr in SOCKADDR_IN6 // sin6_family : Smallint; // AF_INET6 // sin6_port : u_short; // Transport level port number // sin6_flowinfo : u_long; // IPv6 flow information System.array.Copy(ASockAddr,8, VIPAddr, 0, 16); end; 2 : //AddressFamily.InterNetwork : begin //size of sockaddr_in.sin_addr SetLength(VIPAddr,4); // 4 = offset of sockaddr_in.sin_addr // sin_family : u_short; // sin_port : u_short; System.array.Copy(ASockAddr,4, VIPAddr, 0, 4); end; end; end; procedure TIdStackDotNet.QueryRoute(s : TIdStackSocketHandle; const AIP: String; const APort: TIdPort; var VSource, VDest : TIdBytes); {$IFDEF DOTNET_2_OR_ABOVE} const SIO_ROUTING_INTERFACE_QUERY = 3355443220; {$ENDIF} var LEP : IPEndPoint; LDestIF : SocketAddress; LIn, LOut : TBytes; i : Integer; begin LEP := IPEndPoint.Create(IPAddress.Parse(AIP),APort); LDestIf := LEP.Serialize; { The first 2 bytes of the underlying buffer are reserved for the AddressFamily enumerated value. When the SocketAddress is used to store a serialized IPEndPoint, the third and fourth bytes are used to store port number information. The next bytes are used to store the IP address. You can access any information within this underlying byte buffer by referring to its index position; the byte buffer uses zero-based indexing. You can also use the Family and Size properties to get the AddressFamily value and the buffer size, respectively. To view any of this information as a string, use the ToString method. } SetLength(LIn,LDestIf.Size); for i := 0 to LDestIf.Size - 1 do begin LIn[i] := LDestIf[i]; end; SetLength(LOut,LDestIf.Size); { IMPORTANT!!!! We can not do something like: s.IOControl( IOControlCode.RoutingInterfaceQuery, LIn, LOut); because to IOControlCode.RoutingInterfaceQuery has a value of -539371432 and that is not correct. I found that out the hard way. } s.IOControl(LongInt(SIO_ROUTING_INTERFACE_QUERY),Lin,LOut); SockAddrToIPBytes(LOut,VSource); SockAddrToIPBytes(LIn,VDest); end; procedure TIdStackDotNet.WriteChecksumIPv6(s: TIdStackSocketHandle; var VBuffer: TIdBytes; const AOffset: Integer; const AIP: String; const APort: TIdPort); var LSource : TIdBytes; LDest : TIdBytes; LTmp : TIdBytes; LIdx : Integer; LC : LongWord; { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + Source Address + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + Destination Address + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Upper-Layer Packet Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | zero | Next Header | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } begin QueryRoute(s, AIP, APort, LSource, LDest); SetLength(LTmp, 40+Length(VBuffer)); System.&Array.Clear(LTmp,0,Length(LTmp)); //16 CopyTIdBytes(LSource, 0, LTmp, 0, 16); LIdx := 16; //32 CopyTIdBytes(LDest, 0, LTmp,LIdx, 16); Inc(LIdx, 16); //use a word so you don't wind up using the wrong network byte order function LC := Length(VBuffer); CopyTIdLongWord(GStack.HostToNetwork(LC), LTmp, LIdx); Inc(LIdx, 4); //36 //zero the next three bytes //done in the begging Inc(LIdx, 3); //next header (protocol type determines it LTmp[LIdx] := Ord(Id_IPPROTO_ICMPv6); Inc(LIdx); //combine the two CopyTIdBytes(VBuffer, 0, LTmp, LIdx, Length(VBuffer)); //zero out the checksum field CopyTIdWord(0, LTmp, LIdx+AOffset); CopyTIdWord(HostToLittleEndian(CalcCheckSum(LTmp)), VBuffer, AOffset); end; {$ENDIF} procedure TIdStackDotNet.WriteChecksum(s: TIdStackSocketHandle; var VBuffer: TIdBytes; const AOffset: Integer; const AIP: String; const APort: TIdPort; const AIPVersion: TIdIPVersion); begin if AIPVersion = Id_IPv4 then begin CopyTIdWord(CalcCheckSum(VBuffer), VBuffer, AOffset); end else begin {$IFDEF DOTNET_1_1} {This is a todo because to do a checksum for ICMPv6, you need to obtain the address for the IP the packet will come from (query the network interfaces). You then have to make a IPv6 pseudo header. About the only other alternative is to have the kernel (or DotNET Framework) generate the checksum but we don't have an API for it. I'm not sure if we have an API for it at all. Even if we did, would it be worth doing when you consider that Microsoft's NET Framework 1.1 does not support ICMPv6 in its enumerations.} raise EIdNotSupportedInMicrosoftNET11.Create(RSNotSupportedInMicrosoftNET11); {$ELSE} WriteChecksumIPv6(s,VBuffer,AOffset,AIP,APort); {$ENDIF} end; end; function TIdStackDotNet.IOControl(const s: TIdStackSocketHandle; const cmd: LongWord; var arg: LongWord): Integer; var LTmp : TIdBytes; begin LTmp := ToBytes(arg); s.IOControl(cmd, ToBytes(arg), LTmp); arg := BytesToLongWord(LTmp); Result := 0; end; {$IFDEF DOTNET_2_OR_ABOVE} function ServeFile(ASocket: TIdStackSocketHandle; const AFileName: string): Int64; var LFile : FileInfo; begin ASocket.SendFile(AFileName); LFile := System.IO.FileInfo.Create(AFileName); Result := LFile.Length; end; {$ENDIF} procedure TIdStackDotNet.SetKeepAliveValues(ASocket: TIdStackSocketHandle; const AEnabled: Boolean; const ATimeMS, AInterval: Integer); {$IFNDEF DOTNET_2_OR_ABOVE} const SIO_KEEPALIVE_VALS = 2550136836; {$ENDIF} var LBuf: TIdBytes; begin // SIO_KEEPALIVE_VALS is supported on Win2K+ only if AEnabled and (System.OperatingSystem.Version.Major >= 5) then begin SetLength(LBuf, 12); CopyTIdLongWord(1, LBuf, 0); CopyTIdLongWord(ATimeMS, LBuf, 4); CopyTIdLongWord(AInterval, LBuf, 8); ASocket.IOControl( {$IFDEF DOTNET_2_OR_ABOVE}IOControlCode.KeepAliveValues{$ELSE}SIO_KEEPALIVE_VALS{$ENDIF}, LBuf, nil); end else begin LBuf := nil; ASocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, iif(AEnabled, 1, 0)); end; end; initialization GSocketListClass := TIdSocketListDotNet; {$IFDEF DOTNET_2_OR_ABOVE} GServeFileProc := ServeFile; {$ENDIF} end.
unit evEditorWindowHotSpot; // Модуль: "w:\common\components\gui\Garant\Everest\evEditorWindowHotSpot.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevEditorWindowHotSpot" MUID: (48E229CC03DF) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3Tool , nevGUIInterfaces , nevTools , nevBase , l3Interfaces , l3Base , l3IID , afwInterfaces ; type TevForeignHotSpotMode = ( ev_fhsmNone , ev_fhsmDisabled , ev_fhsmEnabled );//TevForeignHotSpotMode TevEditorWindowHotSpot = class(Tl3Tool, IevAdvancedHotSpot, IevHotSpot) private fl_ForeignHotSpotMove: TevForeignHotSpotMode; f_ForeignHotSpot: IevHotSpot; {* "чужой" HotSpot - вся обработка сначала отдается ему } f_ClickCursor: InevBasePoint; {* курсор куда кликнули } protected function pm_GetStartMark: InevPoint; function pm_GetFinishMark: InevPoint; function pm_GetOwner: TObject; procedure DoBeforeSelection(const aView: InevControlView); virtual; {* Запоминает точку начала выделения } function NeedSelectCursor(const aView: InevControlView; const aPt: TnevPoint): Boolean; virtual; {* Проверяет корректность выделения при движении мыши и, если выделение заканчивается за пределами параграфа-виджета, то возвращаемся к запомненной в DoBeforeSelection точке } function CheckCursorPos(const aView: InevView): Boolean; virtual; {* Вызывается для проверки позиционирования курсора и/или окончания выделения. Срабатывает после отпускания кнопки мыши, если управление не было перехвачено самим виджетом } function DoLButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; virtual; function DoLButtonDown(const aView: InevControlView; const aKeys: TevMouseState; var Effect: TevMouseEffect): Boolean; virtual; function DoMouseMove(const aView: InevControlView; const aKeys: TevMouseState): Boolean; virtual; {* Обрабатывает движение мыши, после нажатия левой кнопки } function TryDragDrop(const aKeys: TevMouseState): Boolean; procedure TranslatePt(const aView: InevControlView; const aKeys: TevMouseState); {* транслирует точку aPt в ClickCursor или StartMark. Если транслируется в StartMark, то FinishMark = ClickCursor } procedure AlignMarks(const aView: InevControlView; const aKeys: TevMouseState); virtual; {* "выравнивает" StartMark и FinishMark - например на границу слова } procedure ExtendBlock(const aView: InevControlView); {* устанавливает StartMark и FinishMark в выделение } procedure DoExtendBlock(const aView: InevControlView; const aSelection: InevSelection); virtual; {* устанавливает StartMark и FinishMark в выделение } function DoLButtonUp(const aView: InevControlView; const aKeys: TevMouseState; aNeedUnselect: Boolean): Boolean; virtual; {* обрабатывает отпускание левой кнопки мыши } function BeginMouseOp(const aView: InevControlView; out theSelection: Tl3Base): InevOp; {* начало операторных скобок. Для закрытия скобки надо освободить OpPack. theSelection - объект, содержащий выделение, его надо освобождать процедурой l3Free в секции finally } function MouseAction(const aView: InevControlView; aButton: Tl3MouseButton; anAction: Tl3MouseAction; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false } function MouseMove(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает перемещение мыши } function LButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает нажатие левой кнопки мыши } function LButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание левой кнопки мыши } function LButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает двойное нажатие левой кнопки мыши } function RButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие правой кнопки мыши } function RButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание правой конопки мыши } function MButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие колеса мыши } function MButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание колеса мыши } function CanDrag: Boolean; procedure Cleanup; override; {* Функция очистки полей объекта. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } procedure ClearFields; override; public constructor Create(const anOwner: Il3ToolOwner; const aForeignHotSpot: IevHotSpot); reintroduce; class function Make(const anOwner: Il3ToolOwner; const aForeignHotSpot: IevHotSpot = nil): IevHotSpot; reintroduce; procedure HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); protected property ForeignHotSpot: IevHotSpot read f_ForeignHotSpot; {* "чужой" HotSpot - вся обработка сначала отдается ему } property ClickCursor: InevBasePoint read f_ClickCursor; {* курсор куда кликнули } property StartMark: InevPoint read pm_GetStartMark; {* курсор где сейчас мышь } property Owner: TObject read pm_GetOwner; public property FinishMark: InevPoint read pm_GetFinishMark; {* курсор куда кликнули - обычно = ClickCursor } end;//TevEditorWindowHotSpot implementation uses l3ImplUses , evCustomEditorWindow , evTypes , l3InternalInterfaces , evMsgCode , evDataObject , SysUtils , evOp , evExcept , Classes , l3Variant //#UC START# *48E229CC03DFimpl_uses* //#UC END# *48E229CC03DFimpl_uses* ; function TevEditorWindowHotSpot.pm_GetStartMark: InevPoint; //#UC START# *48EF2EB0009F_48E229CC03DFget_var* //#UC END# *48EF2EB0009F_48E229CC03DFget_var* begin //#UC START# *48EF2EB0009F_48E229CC03DFget_impl* Result := (Owner As TevCustomEditorWindow).Selection.StartMark; //#UC END# *48EF2EB0009F_48E229CC03DFget_impl* end;//TevEditorWindowHotSpot.pm_GetStartMark function TevEditorWindowHotSpot.pm_GetFinishMark: InevPoint; //#UC START# *48EF2EE00254_48E229CC03DFget_var* //#UC END# *48EF2EE00254_48E229CC03DFget_var* begin //#UC START# *48EF2EE00254_48E229CC03DFget_impl* Result := (Owner As TevCustomEditorWindow).Selection.FinishMark; //#UC END# *48EF2EE00254_48E229CC03DFget_impl* end;//TevEditorWindowHotSpot.pm_GetFinishMark function TevEditorWindowHotSpot.pm_GetOwner: TObject; //#UC START# *4DD28E040057_48E229CC03DFget_var* //#UC END# *4DD28E040057_48E229CC03DFget_var* begin //#UC START# *4DD28E040057_48E229CC03DFget_impl* if (f_Owner = nil) then Result := nil else Result := ((Il3Tool(f_Owner) As Il3ObjectWrap).GetObject As TPersistent); //#UC END# *4DD28E040057_48E229CC03DFget_impl* end;//TevEditorWindowHotSpot.pm_GetOwner procedure TevEditorWindowHotSpot.DoBeforeSelection(const aView: InevControlView); {* Запоминает точку начала выделения } //#UC START# *48E4A900029B_48E229CC03DF_var* //#UC END# *48E4A900029B_48E229CC03DF_var* begin //#UC START# *48E4A900029B_48E229CC03DF_impl* //#UC END# *48E4A900029B_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoBeforeSelection function TevEditorWindowHotSpot.NeedSelectCursor(const aView: InevControlView; const aPt: TnevPoint): Boolean; {* Проверяет корректность выделения при движении мыши и, если выделение заканчивается за пределами параграфа-виджета, то возвращаемся к запомненной в DoBeforeSelection точке } //#UC START# *48E4A93300A9_48E229CC03DF_var* //#UC END# *48E4A93300A9_48E229CC03DF_var* begin //#UC START# *48E4A93300A9_48E229CC03DF_impl* InevSelection((Owner As TevCustomEditorWindow).Selection).SelectPt(aPt, false); Result := true; //#UC END# *48E4A93300A9_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.NeedSelectCursor function TevEditorWindowHotSpot.CheckCursorPos(const aView: InevView): Boolean; {* Вызывается для проверки позиционирования курсора и/или окончания выделения. Срабатывает после отпускания кнопки мыши, если управление не было перехвачено самим виджетом } //#UC START# *48E4A96000D4_48E229CC03DF_var* //#UC END# *48E4A96000D4_48E229CC03DF_var* begin //#UC START# *48E4A96000D4_48E229CC03DF_impl* Result := True; //Для обычного редактора это не нужно! //#UC END# *48E4A96000D4_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.CheckCursorPos function TevEditorWindowHotSpot.DoLButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *48E4A976007D_48E229CC03DF_var* //#UC END# *48E4A976007D_48E229CC03DF_var* begin //#UC START# *48E4A976007D_48E229CC03DF_impl* Result := true; if (f_ForeignHotSpot = nil) OR ((ssShift in Keys.rKeys)) OR not f_ForeignHotSpot.LButtonDoubleClick(aView, Keys, Effect) then if Effect.rAllowAutoSelect then (Owner As TevCustomEditorWindow).Select(ev_stWord); //#UC END# *48E4A976007D_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoLButtonDoubleClick function TevEditorWindowHotSpot.DoLButtonDown(const aView: InevControlView; const aKeys: TevMouseState; var Effect: TevMouseEffect): Boolean; //#UC START# *48E4A99D02A2_48E229CC03DF_var* var l_Pack : InevOp; //#UC END# *48E4A99D02A2_48E229CC03DF_var* begin //#UC START# *48E4A99D02A2_48E229CC03DF_impl* Result := true; with (Owner As TevCustomEditorWindow) do begin l_Pack := StartOp(ev_msgMove); try if (Selection <> nil) then with Selection do begin DoBeforeSelection(aView); InevSelection(Selection).SelectPt(aKeys.rPoint, false); if (f_ClickCursor = nil) then f_ClickCursor := Cursor.ClonePoint(aView) else ClickCursor.AssignPoint(aView, Cursor); {if not !Double then StartMark.Assign(Cursor);} end;//with Selection finally l_Pack := nil; end;//try..finally end;//with (Owner As TevCustomEditorWindow) //#UC END# *48E4A99D02A2_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoLButtonDown constructor TevEditorWindowHotSpot.Create(const anOwner: Il3ToolOwner; const aForeignHotSpot: IevHotSpot); //#UC START# *48EF2DAB031D_48E229CC03DF_var* //#UC END# *48EF2DAB031D_48E229CC03DF_var* begin //#UC START# *48EF2DAB031D_48E229CC03DF_impl* inherited Create(anOwner); f_ForeignHotSpot := aForeignHotSpot; //#UC END# *48EF2DAB031D_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.Create class function TevEditorWindowHotSpot.Make(const anOwner: Il3ToolOwner; const aForeignHotSpot: IevHotSpot = nil): IevHotSpot; var l_Inst : TevEditorWindowHotSpot; begin l_Inst := Create(anOwner, aForeignHotSpot); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevEditorWindowHotSpot.Make function TevEditorWindowHotSpot.DoMouseMove(const aView: InevControlView; const aKeys: TevMouseState): Boolean; {* Обрабатывает движение мыши, после нажатия левой кнопки } //#UC START# *48EF36A30277_48E229CC03DF_var* //#UC END# *48EF36A30277_48E229CC03DF_var* begin //#UC START# *48EF36A30277_48E229CC03DF_impl* Result := true; TranslatePt(aView, aKeys); AlignMarks(aView, aKeys); ExtendBlock(aView); //#UC END# *48EF36A30277_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoMouseMove function TevEditorWindowHotSpot.TryDragDrop(const aKeys: TevMouseState): Boolean; //#UC START# *48EF36CC0039_48E229CC03DF_var* var l_Pack : InevOp; l_DataObject : TevDataObject; l_Block : InevRange; l_OutEffect : Integer; l_Formats : Tl3ClipboardFormats; //#UC END# *48EF36CC0039_48E229CC03DF_var* begin //#UC START# *48EF36CC0039_48E229CC03DF_impl* Result := false; if (aKeys.rInitialClick = afw_ckSingle) then with (Owner As TevCustomEditorWindow) do begin l_Pack := StartOp(ev_msgMove); try with Selection do begin // http://mdp.garant.ru/pages/viewpage.action?pageId=297714497 if (ssCtrl in aKeys.rKeys) and (not DisableDragAndDropSupport) then begin if Supports(SaveBlock(Mouse), InevRange, l_Block) then try if GetAvaliableFormats(l_Formats) then try l_DataObject := TevDataObject.Create(l_Block.Data, l_Formats, MakeExportFilters(false, false)); try if (DoDragDrop(l_DataObject, DROPEFFECT_Copy or DROPEFFECT_Move, l_OutEffect) = DRAGDROP_S_DROP) then begin end;//DoDragDrop Result := true; Exit; finally l3Free(l_DataObject); end;//try..finally finally l_Formats := nil; end;//try..finally finally l_Block := nil; end;//try..finally end;//ssCtrl in aKeys.rKeys end;//with Selection finally l_Pack := nil; end;//try..finally end;//with (Owner As TevCustomEditorWindow) //#UC END# *48EF36CC0039_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.TryDragDrop procedure TevEditorWindowHotSpot.TranslatePt(const aView: InevControlView; const aKeys: TevMouseState); {* транслирует точку aPt в ClickCursor или StartMark. Если транслируется в StartMark, то FinishMark = ClickCursor } //#UC START# *48EF37DF00C3_48E229CC03DF_var* //#UC END# *48EF37DF00C3_48E229CC03DF_var* begin //#UC START# *48EF37DF00C3_48E229CC03DF_impl* with (Owner As TevCustomEditorWindow).Selection do begin if NeedSelectCursor(aView, aKeys.rPoint) then begin if aKeys.rInMove then begin if (ClickCursor = nil) then begin {$IFDEF Archi} f_ClickCursor := Cursor.ClonePoint(aView); {$ELSE} f_ClickCursor := Start.ClonePoint(aView); {$ENDIF Archi} FinishMark.AssignPoint(aView, Finish); end//ClickCursor = nil else FinishMark.AssignPoint(aView, Cursor); StartMark.AssignPoint(aView, ClickCursor); end//aKeys.rInMove else begin if (ClickCursor = nil) then f_ClickCursor := Cursor.ClonePoint(aView) else ClickCursor.AssignPoint(aView, Cursor); end;//aKeys.rInMove end;//NeedSelectCursor(aPt) end;//with (Owner As TevCustomEditorWindow) //#UC END# *48EF37DF00C3_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.TranslatePt procedure TevEditorWindowHotSpot.AlignMarks(const aView: InevControlView; const aKeys: TevMouseState); {* "выравнивает" StartMark и FinishMark - например на границу слова } //#UC START# *48EF380C026E_48E229CC03DF_var* var l_S, l_F : Integer; //#UC END# *48EF380C026E_48E229CC03DF_var* begin //#UC START# *48EF380C026E_48E229CC03DF_impl* Case aKeys.rInitialClick of afw_ckSingle: begin if not (Owner As TevCustomEditorWindow).NeedAlignMarksOnSingleClick then Exit; l_S := ev_ocWordStart; l_F := ev_ocWordFinish; end;//afw_ckSingle, afw_ckDouble afw_ckDouble: begin l_S := ev_ocWordStart; l_F := ev_ocWordFinish; end;//afw_ckSingle, afw_ckDouble afw_ckTriple: begin l_S := ev_ocParaHome; l_F := ev_ocParaEnd; end;//afw_ckTriple else Exit; end;//Case aKeys.rInitialClick if (StartMark.Compare(FinishMark) < 0) then begin StartMark.Move(aView, l_S); FinishMark.Move(aView, l_F); end else begin StartMark.Move(aView, l_F); FinishMark.Move(aView, l_S); end;//StartMark.Compare(FinishMark) < 0 //#UC END# *48EF380C026E_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.AlignMarks procedure TevEditorWindowHotSpot.ExtendBlock(const aView: InevControlView); {* устанавливает StartMark и FinishMark в выделение } //#UC START# *48EF385503A8_48E229CC03DF_var* //#UC END# *48EF385503A8_48E229CC03DF_var* begin //#UC START# *48EF385503A8_48E229CC03DF_impl* DoExtendBlock(aView, (Owner As TevCustomEditorWindow).Selection); //#UC END# *48EF385503A8_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.ExtendBlock procedure TevEditorWindowHotSpot.DoExtendBlock(const aView: InevControlView; const aSelection: InevSelection); {* устанавливает StartMark и FinishMark в выделение } //#UC START# *48EF3A860139_48E229CC03DF_var* //#UC END# *48EF3A860139_48E229CC03DF_var* begin //#UC START# *48EF3A860139_48E229CC03DF_impl* aSelection.AddBlock(StartMark, FinishMark); //#UC END# *48EF3A860139_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoExtendBlock function TevEditorWindowHotSpot.DoLButtonUp(const aView: InevControlView; const aKeys: TevMouseState; aNeedUnselect: Boolean): Boolean; {* обрабатывает отпускание левой кнопки мыши } //#UC START# *48EF3C6E0276_48E229CC03DF_var* var l_Editor : TevCustomEditorWindow; //#UC END# *48EF3C6E0276_48E229CC03DF_var* begin //#UC START# *48EF3C6E0276_48E229CC03DF_impl* Result := true; l_Editor := Owner As TevCustomEditorWindow; with l_Editor do begin if not aKeys.rInMove AND aNeedUnselect AND (aKeys.rInitialClick = afw_ckSingle) AND (Selection <> nil) AND not Selection.Persistent then InevSelection(Selection).Unselect; DoUpdateBlock; DoParaChange; end;//with l_Editor //#UC END# *48EF3C6E0276_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.DoLButtonUp function TevEditorWindowHotSpot.BeginMouseOp(const aView: InevControlView; out theSelection: Tl3Base): InevOp; {* начало операторных скобок. Для закрытия скобки надо освободить OpPack. theSelection - объект, содержащий выделение, его надо освобождать процедурой l3Free в секции finally } //#UC START# *48EF3D680254_48E229CC03DF_var* //#UC END# *48EF3D680254_48E229CC03DF_var* begin //#UC START# *48EF3D680254_48E229CC03DF_impl* with (Owner As TevCustomEditorWindow) do begin Result := StartOp(ev_msgMove); theSelection := Selection.Use; end;//with (Owner As TevCustomEditorWindow) //#UC END# *48EF3D680254_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.BeginMouseOp procedure TevEditorWindowHotSpot.HitTest(const aView: InevControlView; const aState: TafwCursorState; var theInfo: TafwCursorInfo); //#UC START# *48E2622A03C4_48E229CC03DF_var* //#UC END# *48E2622A03C4_48E229CC03DF_var* begin //#UC START# *48E2622A03C4_48E229CC03DF_impl* if (f_ForeignHotSpot <> nil) then f_ForeignHotSpot.HitTest(aView, aState, theInfo); with (Owner As TevCustomEditorWindow) do if (f_ForeignHotSpot = nil) then DoHitTest(Self, aState, theInfo) else DoHitTest(f_ForeignHotSpot, aState, theInfo); //#UC END# *48E2622A03C4_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.HitTest function TevEditorWindowHotSpot.MouseAction(const aView: InevControlView; aButton: Tl3MouseButton; anAction: Tl3MouseAction; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false } //#UC START# *48E263CD01BD_48E229CC03DF_var* //#UC END# *48E263CD01BD_48E229CC03DF_var* begin //#UC START# *48E263CD01BD_48E229CC03DF_impl* Case aButton of l3_mbLeft: begin Case anAction of l3_maDown: Result := LButtonDown(aView, Keys, Effect); l3_maUp: Result := LButtonUp(aView, Keys); l3_maDouble: Result := LButtonDoubleClick(aView, Keys, Effect); else Result := false; end;//Case anAction end;//l3_mbLeft l3_mbRight: begin Case anAction of l3_maDown: Result := RButtonDown(aView, Keys); l3_maUp: Result := RButtonUp(aView, Keys); l3_maDouble: Result := false; else Result := false; end;//Case anAction end;//l3_mbRight l3_mbMiddle: begin Case anAction of l3_maDown: Result := MButtonDown(aView, Keys); l3_maUp: Result := MButtonUp(aView, Keys); l3_maDouble: Result := false; else Result := false; end;//Case anAction end;//l3_mbMiddle else Result := false; end;//Case aButton //#UC END# *48E263CD01BD_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.MouseAction function TevEditorWindowHotSpot.MouseMove(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает перемещение мыши } //#UC START# *48E266730188_48E229CC03DF_var* //#UC END# *48E266730188_48E229CC03DF_var* begin //#UC START# *48E266730188_48E229CC03DF_impl* if (fl_ForeignHotSpotMove = ev_fhsmEnabled) then Result := f_ForeignHotSpot.MouseMove(aView, Keys) else begin Result := DoMouseMove(aView, Keys); aView.Control.ViewArea.Update; end;//fl_ForeignHotSpotMove //#UC END# *48E266730188_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.MouseMove function TevEditorWindowHotSpot.LButtonDown(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает нажатие левой кнопки мыши } //#UC START# *48E266AA00A4_48E229CC03DF_var* var l_CursorBefore : InevBasePoint; l_HS : IevHotSpot; //#UC END# *48E266AA00A4_48E229CC03DF_var* begin //#UC START# *48E266AA00A4_48E229CC03DF_impl* if (f_ForeignHotSpot = nil) or f_ForeignHotSpot.CanDrag then if TryDragDrop(Keys) then begin Result := false; Exit; end;//TryDragDrop(aKeys) Result := true; if (f_ForeignHotSpot = nil) then l_HS := Self else l_HS := f_ForeignHotSpot; with (Owner As TevCustomEditorWindow) do if Assigned(OnMouseAction) then if OnMouseAction(l_HS, l3_mbLeft, l3_maDown, Keys.rKeys, Effect.rNeedAsyncLoop) then Exit; if (f_ForeignHotSpot <> nil) AND f_ForeignHotSpot.LButtonDown(aView, Keys, Effect) then fl_ForeignHotSpotMove := ev_fhsmEnabled else begin fl_ForeignHotSpotMove := ev_fhsmDisabled; with (Owner As TevCustomEditorWindow).Selection do if Collapsed then l_CursorBefore := Cursor.ClonePoint(aView) else l_CursorBefore := StartMark.ClonePoint(aView); try Effect.rExtendingSelection := ([ssCtrl, ssShift, ssAlt] * Keys.rKeys) = [ssShift]; Result := DoLButtonDown(aView, Keys, Effect); if Effect.rExtendingSelection then ClickCursor.AssignPoint(aView, l_CursorBefore); finally l_CursorBefore := nil; end;//try..finally end;//f_ForeignHotSpot <> nil.. //#UC END# *48E266AA00A4_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.LButtonDown function TevEditorWindowHotSpot.LButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание левой кнопки мыши } //#UC START# *48E266C70128_48E229CC03DF_var* var l_Unselect : Boolean; l_Editor : TevCustomEditorWindow; //#UC END# *48E266C70128_48E229CC03DF_var* begin //#UC START# *48E266C70128_48E229CC03DF_impl* Result := true; if (fl_ForeignHotSpotMove <> ev_fhsmDisabled) AND (f_ForeignHotSpot <> nil) then try Result := f_ForeignHotSpot.LButtonUp(aView, Keys); except on EevReadOnly do; end//try..except else begin l_Unselect := true; if not Keys.rInMove then begin if (StartMark <> nil) then begin if CheckCursorPos(aView) then begin (* l_Editor := Owner As TevCustomEditorWindow; if (l_Editor.Selection <> nil) AND not l_Editor.Selection.Persistent then*) // http://mdp.garant.ru/pages/viewpage.action?pageId=227478574 // - закомментировано, ибо - http://mdp.garant.ru/pages/viewpage.action?pageId=296631959 StartMark.AssignPoint(aView, FinishMark); end//CheckCursorPos(aView) else l_Unselect := false; end;//StartMark <> nil end//not Keys.rInMove else CheckCursorPos(aView); if not Keys.rInMove then if (Owner As TevCustomEditorWindow).CheckMouseUp(Self, Keys) then Exit; Result := DoLButtonUp(aView, Keys, l_Unselect); if not Keys.rInMove then with (Owner As TevCustomEditorWindow) do if (ev_uwfBlock in UpdateFlags) then Invalidate; end;//fl_ForeignHotSpotMove //#UC END# *48E266C70128_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.LButtonUp function TevEditorWindowHotSpot.LButtonDoubleClick(const aView: InevControlView; const Keys: TevMouseState; var Effect: TevMouseEffect): Boolean; {* Обрабатывает двойное нажатие левой кнопки мыши } //#UC START# *48E266DE026B_48E229CC03DF_var* var l_HS : IevHotSpot; //#UC END# *48E266DE026B_48E229CC03DF_var* begin //#UC START# *48E266DE026B_48E229CC03DF_impl* if (f_ForeignHotSpot = nil) then l_HS := Self else l_HS := f_ForeignHotSpot; with (Owner As TevCustomEditorWindow) do if Assigned(OnMouseAction) then if OnMouseAction(l_HS, l3_mbLeft, l3_maDouble, Keys.rKeys, Effect.rNeedAsyncLoop) then begin Result := true; Exit; end;//OnMouseAction.. Result := DoLButtonDoubleClick(aView, Keys, Effect); //#UC END# *48E266DE026B_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.LButtonDoubleClick function TevEditorWindowHotSpot.RButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие правой кнопки мыши } //#UC START# *48E266FB01FC_48E229CC03DF_var* //#UC END# *48E266FB01FC_48E229CC03DF_var* begin //#UC START# *48E266FB01FC_48E229CC03DF_impl* Result := (f_ForeignHotSpot <> nil) AND f_ForeignHotSpot.RButtonDown(aView, Keys); //#UC END# *48E266FB01FC_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.RButtonDown function TevEditorWindowHotSpot.RButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание правой конопки мыши } //#UC START# *48E267150266_48E229CC03DF_var* //#UC END# *48E267150266_48E229CC03DF_var* begin //#UC START# *48E267150266_48E229CC03DF_impl* Result := (f_ForeignHotSpot <> nil) AND f_ForeignHotSpot.RButtonUp(aView, Keys); //#UC END# *48E267150266_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.RButtonUp function TevEditorWindowHotSpot.MButtonDown(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает нажатие колеса мыши } //#UC START# *49DB4675025E_48E229CC03DF_var* //#UC END# *49DB4675025E_48E229CC03DF_var* begin //#UC START# *49DB4675025E_48E229CC03DF_impl* Result := (f_ForeignHotSpot <> nil) AND f_ForeignHotSpot.MButtonDown(aView, Keys); //#UC END# *49DB4675025E_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.MButtonDown function TevEditorWindowHotSpot.MButtonUp(const aView: InevControlView; const Keys: TevMouseState): Boolean; {* Обрабатывает отпускание колеса мыши } //#UC START# *49DB468302A5_48E229CC03DF_var* //#UC END# *49DB468302A5_48E229CC03DF_var* begin //#UC START# *49DB468302A5_48E229CC03DF_impl* Result := (f_ForeignHotSpot <> nil) AND f_ForeignHotSpot.MButtonUp(aView, Keys); //#UC END# *49DB468302A5_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.MButtonUp function TevEditorWindowHotSpot.CanDrag: Boolean; //#UC START# *4ECCD6840014_48E229CC03DF_var* //#UC END# *4ECCD6840014_48E229CC03DF_var* begin //#UC START# *4ECCD6840014_48E229CC03DF_impl* Result := True; //#UC END# *4ECCD6840014_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.CanDrag procedure TevEditorWindowHotSpot.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48E229CC03DF_var* //#UC END# *479731C50290_48E229CC03DF_var* begin //#UC START# *479731C50290_48E229CC03DF_impl* fl_ForeignHotSpotMove := ev_fhsmNone; f_ClickCursor := nil; f_ForeignHotSpot := nil; inherited; //#UC END# *479731C50290_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.Cleanup function TevEditorWindowHotSpot.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_48E229CC03DF_var* //#UC END# *4A60B23E00C3_48E229CC03DF_var* begin //#UC START# *4A60B23E00C3_48E229CC03DF_impl* if IID.EQ(Il3TagRef) then Result.SetNoInterface else Result := inherited COMQueryInterface(IID, Obj); if Result.Fail AND (f_ForeignHotSpot <> nil) then Result := Tl3HResult_C(f_ForeignHotSpot.QueryInterface(IID.IID, Obj)); //#UC END# *4A60B23E00C3_48E229CC03DF_impl* end;//TevEditorWindowHotSpot.COMQueryInterface procedure TevEditorWindowHotSpot.ClearFields; begin f_ForeignHotSpot := nil; f_ClickCursor := nil; inherited; end;//TevEditorWindowHotSpot.ClearFields end.
unit NetServerOverbyte; interface uses Classes, SysUtils, OverbyteIcsWSocket, OverbyteIcsWSocketS, WinSock; // Tagging starts with some number away from -2 -1 0 used as sender/recipient constants // and off from usual players indexes 1..8, so we could not confuse them by mistake const FIRST_TAG = 15; type THandleEvent = procedure (aHandle: SmallInt) of object; TNotifyDataEvent = procedure (aHandle: SmallInt; aData: pointer; aLength: Cardinal) of object; TNetServerOverbyte = class private fSocketServer: TWSocketServer; fLastTag: SmallInt; fOnError: TGetStrProc; fOnClientConnect: THandleEvent; fOnClientDisconnect: THandleEvent; fOnDataAvailable: TNotifyDataEvent; procedure NilEvents(); procedure Error(const aText: String); procedure ClientConnect(aSender: TObject; aClient: TWSocketClient; aError: Word); procedure ClientDisconnect(aSender: TObject; aClient: TWSocketClient; aError: Word); procedure DataAvailable(aSender: TObject; aError: Word); public constructor Create(); destructor Destroy(); override; property OnError: TGetStrProc write fOnError; property OnClientConnect: THandleEvent write fOnClientConnect; property OnClientDisconnect: THandleEvent write fOnClientDisconnect; property OnDataAvailable: TNotifyDataEvent write fOnDataAvailable; property Socket: TWSocketServer read fSocketServer; procedure StartListening(aPort: Word); procedure StopListening; procedure SendData(aHandle: SmallInt; aData: Pointer; aLength: Cardinal); procedure Kick(aHandle: SmallInt); function GetIP(aHandle: SmallInt): String; function GetMaxHandle: SmallInt; end; implementation constructor TNetServerOverbyte.Create(); var wsaData: TWSAData; begin Inherited Create; fSocketServer := nil; NilEvents(); fLastTag := FIRST_TAG - 1; // First client will be fLastTag+1 if (WSAStartup($101, wsaData) <> 0) then Error('Error in Network'); end; destructor TNetServerOverbyte.Destroy(); begin NilEvents(); // Disable callbacks before destroying socket (the app is terminating, callbacks do not have to work anymore) fSocketServer.Free; Inherited; end; procedure TNetServerOverbyte.NilEvents(); begin fOnError := nil; fOnClientConnect := nil; fOnClientDisconnect := nil; fOnDataAvailable := nil; end; procedure TNetServerOverbyte.Error(const aText: String); begin if Assigned(fOnError) then fOnError(aText); end; procedure TNetServerOverbyte.StartListening(aPort: Word); begin FreeAndNil(fSocketServer); fSocketServer := TWSocketServer.Create(nil); fSocketServer.ComponentOptions := [wsoTcpNoDelay]; // Send packets ASAP (disables Nagle's algorithm) fSocketServer.Proto := 'tcp'; fSocketServer.Addr := '127.0.0.1'; // Listen to local adress fSocketServer.Port := IntToStr(aPort); fSocketServer.Banner := ''; fSocketServer.OnClientConnect := ClientConnect; fSocketServer.OnClientDisconnect := ClientDisconnect; fSocketServer.OnDataAvailable := DataAvailable; fSocketServer.Listen; fSocketServer.SetTcpNoDelayOption; // Send packets ASAP (disables Nagle's algorithm) end; procedure TNetServerOverbyte.StopListening(); begin if (fSocketServer <> nil) then fSocketServer.ShutDown(1); FreeAndNil(fSocketServer); fLastTag := FIRST_TAG-1; end; // Someone has connected to us procedure TNetServerOverbyte.ClientConnect(aSender: TObject; aClient: TWSocketClient; aError: Word); begin if (aError <> 0) then begin Error(Format('ClientConnect. Error: %s (#%d)', [WSocketErrorDesc(aError), aError])); Exit; end; // Identify index of the Client, so we can address it if (fLastTag = GetMaxHandle) then fLastTag := FIRST_TAG - 1; Inc(fLastTag); aClient.Tag := fLastTag; aClient.OnDataAvailable := DataAvailable; aClient.ComponentOptions := [wsoTcpNoDelay]; //Send packets ASAP (disables Nagle's algorithm) aClient.SetTcpNoDelayOption; if Assigned(fOnClientConnect) then fOnClientConnect(aClient.Tag); end; procedure TNetServerOverbyte.ClientDisconnect(aSender: TObject; aClient: TWSocketClient; aError: Word); begin if (aError <> 0) then begin Error(Format('ClientDisconnect. Error: %s (#%d)', [WSocketErrorDesc(aError), aError])); // Do not exit because the client has to disconnect end; if Assigned(fOnClientDisconnect) then fOnClientDisconnect(aClient.Tag); end; // We recieved data from someone procedure TNetServerOverbyte.DataAvailable(aSender: TObject; aError: Word); const BufferSize = 10240; // 10kb var P: Pointer; L: Integer; // L could be -1 when no data is available begin if (aError <> 0) then begin Error(Format('DataAvailable. Error: %s (#%d)', [WSocketErrorDesc(aError), aError])); Exit; end; GetMem(P, BufferSize + 1); // +1 to avoid RangeCheckError when L = BufferSize L := TWSocket(aSender).Receive(P, BufferSize); if (L > 0) AND Assigned(fOnDataAvailable) then fOnDataAvailable(TWSocket(aSender).Tag, P, L) // The pointer is stored in ExtAINetServer and the memory will be freed later else FreeMem(P); // The pointer is NOT used and must be freed end; // Make sure we send data to specified client procedure TNetServerOverbyte.SendData(aHandle: SmallInt; aData: Pointer; aLength: Cardinal); var K: Integer; begin for K := 0 to fSocketServer.ClientCount - 1 do if (fSocketServer.Client[K].Tag = aHandle) then if (fSocketServer.Client[K].State <> wsClosed) then // Sometimes this occurs just before ClientDisconnect if (Cardinal(fSocketServer.Client[K].Send(aData, aLength)) <> aLength) then Error(Format('Overbyte Server: Failed to send packet to client %d', [aHandle])); end; function TNetServerOverbyte.GetMaxHandle(): SmallInt; begin Result := 32767; end; procedure TNetServerOverbyte.Kick(aHandle: SmallInt); var K: Integer; begin for K := 0 to fSocketServer.ClientCount - 1 do if (fSocketServer.Client[K].Tag = aHandle) then begin if (fSocketServer.Client[K].State <> wsClosed) then // Sometimes this occurs just before ClientDisconnect fSocketServer.Client[K].Close; Exit; // Only one client should have this handle end; end; function TNetServerOverbyte.GetIP(aHandle: SmallInt): String; var K: Integer; begin Result := ''; for K := 0 to fSocketServer.ClientCount-1 do if (fSocketServer.Client[K].Tag = aHandle) then begin if (fSocketServer.Client[K].State <> wsClosed) then // Sometimes this occurs just before ClientDisconnect Result := fSocketServer.Client[K].GetPeerAddr; Exit; // Only one client should have this handle end; end; end.
unit K619944727_D910b0036111; {* [RequestLink:619944727] } // Модуль: "w:\common\components\rtl\Garant\Daily\K619944727_D910b0036111.pas" // Стереотип: "TestCase" // Элемент модели: "K619944727_D910b0036111" MUID: (56E951AC03B8) // Имя типа: "TK619944727_D910b0036111" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK619944727_D910b0036111 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:619944727] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK619944727_D910b0036111 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56E951AC03B8impl_uses* //#UC END# *56E951AC03B8impl_uses* ; function TK619944727_D910b0036111.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK619944727_D910b0036111.GetFolder function TK619944727_D910b0036111.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56E951AC03B8'; end;//TK619944727_D910b0036111.GetModelElementGUID initialization TestFramework.RegisterTest(TK619944727_D910b0036111.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{ RxDBGridPrintGrid unit Copyright (C) 2005-2014 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit RxDBGridPrintGrid; {$I rx.inc} interface uses Classes, SysUtils, DB, rxdbgrid, LR_Class, LR_DSet, LR_DBSet, contnrs, Graphics, Printers; type TRxDBGridPrintOption = (rxpoShowTitle, rxpoShowFooter, rxpoShowGridColor, rxpoShowFooterColor, rxpoShowReportTitle, rxpoHideZeroValues ); TRxDBGridPrintOptions = set of TRxDBGridPrintOption; { TRxColInfo } TRxColInfo = class Col:TRxColumn; ColWidth:integer; ColTitles:TStringList; constructor Create; destructor Destroy; override; end; { TRxPageMargin } TRxPageMargin = class(TPersistent) private FBottom: integer; FLeft: integer; FRight: integer; FTop: integer; protected procedure AssignTo(Dest: TPersistent); override; public constructor Create; published property Left:integer read FLeft write FLeft default 20; property Top:integer read FTop write FTop default 20; property Right:integer read FRight write FRight default 20; property Bottom:integer read FBottom write FBottom default 20; end; { TRxDBGridPrint } TRxDBGridPrint = class(TRxDBGridAbstractTools) private FOptions: TRxDBGridPrintOptions; FOrientation: TPrinterOrientation; FPageMargin: TRxPageMargin; FReport : TfrReport; FReportDataSet : TfrDBDataSet; FColumnDataSet : TfrUserDataSet; FDataSet : TDataset; FPage : TfrPage; FReportTitle: string; FShowColumnHeaderOnAllPage: boolean; FShowProgress : Boolean; FTitleRowCount : integer; FRxColInfoList : TObjectList; FYPos: Integer; FXPos: Integer; procedure DoCreateReport; procedure DoShowReportTitle; procedure DoSetupColumns; procedure DoShowColumnsTitle; procedure DoShowFooter; procedure OnPrintColumn(ColNo: Integer; var Width: Integer); procedure OnEnterRect(Memo: TStringList; View: TfrView); procedure SetPageMargin(AValue: TRxPageMargin); protected function DoExecTools:boolean;override; function DoSetupTools:boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure PreviewReport; published property Orientation: TPrinterOrientation read FOrientation write FOrientation default poPortrait; property Options:TRxDBGridPrintOptions read FOptions write FOptions; property ShowProgress : Boolean read FShowProgress write FShowProgress default false; property PageMargin:TRxPageMargin read FPageMargin write SetPageMargin; property ReportTitle:string read FReportTitle write FReportTitle; property ShowColumnHeaderOnAllPage:boolean read FShowColumnHeaderOnAllPage write FShowColumnHeaderOnAllPage default false; end; procedure Register; implementation uses math, RxDBGridPrintGrid_SetupUnit, Forms, Controls, rxdconst; {$R rxdbgridprintgrid.res} procedure Register; begin RegisterComponents('RX DBAware',[TRxDBGridPrint]); end; { TRxPageMargin } procedure TRxPageMargin.AssignTo(Dest: TPersistent); begin if (Dest is TRxPageMargin) then begin TRxPageMargin(Dest).FBottom:=FBottom; TRxPageMargin(Dest).FLeft:=FLeft; TRxPageMargin(Dest).FRight:=FRight; TRxPageMargin(Dest).FTop:=FTop; end else inherited AssignTo(Dest); end; constructor TRxPageMargin.Create; begin inherited Create; FBottom:=20; FLeft:=20; FRight:=20; FTop:=20; end; { TRxColInfo } constructor TRxColInfo.Create; begin inherited Create; ColTitles:=TStringList.Create; end; destructor TRxColInfo.Destroy; begin ColTitles.Clear; FreeAndNil(ColTitles); inherited Destroy; end; { TRxDBGridPrint } procedure TRxDBGridPrint.DoShowReportTitle; var FBand: TfrBandView; FView: TfrMemoView; begin FBand := TfrBandView(frCreateObject(gtBand, '', FPage)); FBand.SetBounds(10, FYPos, 1000, 25); FBand.BandType := btReportTitle; // FPage.Objects.Add(FBand); FView := frCreateObject(gtMemo, '', FPage) as TfrMemoView; FView.SetBounds(FXPos, FYPos, FPage.PrnInfo.PgW - 40, 25); FView.Alignment:=taCenter; FView.Font.Size:=12; // FView.Font.Assign(FTitleFont); FView.Memo.Add(FReportTitle); // FPage.Objects.Add(FView); Inc(FYPos, 27) end; procedure TRxDBGridPrint.DoCreateReport; var FBand: TfrBandView; FView: TfrMemoView; begin if FReport.Pages.Count=0 then FReport.Pages.add; FPage := FReport.Pages[FReport.Pages.Count-1]; FPage.ChangePaper(FPage.pgSize, FPage.Width, FPage.Height, FOrientation); FPage.Margins.Top:=FPageMargin.Top; FPage.Margins.Left:=FPageMargin.Left; FPage.Margins.Bottom:=FPageMargin.Bottom; FPage.Margins.Right:=FPageMargin.Right; FYPos:=FPageMargin.Top; FXPos:=FPageMargin.Left; if rxpoShowReportTitle in FOptions then DoShowReportTitle; if rxpoShowTitle in FOptions then DoShowColumnsTitle; FBand := TfrBandView(frCreateObject(gtBand, '', FPage)); FBand.BandType := btMasterData; FBand.Dataset := FReportDataSet.Name; FBand.SetBounds(0, FYPos, 1000, 18); FBand.Flags:=FBand.Flags or flStretched; // FPage.Objects.Add(FBand); FBand := TfrBandView(frCreateObject(gtBand, '', FPage)); FBand.BandType := btCrossData; FBand.Dataset := FColumnDataSet.Name; FBand.SetBounds(FXPos, 0, 20, 1000); // FPage.Objects.Add(FBand); FView := frCreateObject(gtMemo, '', FPage) as TfrMemoView; FView.SetBounds(FXPos, FYPos, 20, 18); FView.Memo.Add('[Cell]'); FView.Flags:=FView.Flags or flStretched; FView.Font.Size:=10; // FView.Font.Assign(FFont); FView.Frames:=frAllFrames; FView.Layout:=tlTop; // FPage.Objects.Add(FView); FYPos := FYPos + 22; if (RxDBGrid.FooterOptions.Active) and (RxDBGrid.FooterOptions.RowCount>0) then DoShowFooter; end; procedure TRxDBGridPrint.DoSetupColumns; var P:TRxColInfo; i: Integer; j: Integer; begin FTitleRowCount:=1; FRxColInfoList.Clear; for i:=0 to RxDBGrid.Columns.Count-1 do begin if RxDBGrid.Columns[i].Visible then begin P:=TRxColInfo.Create; FRxColInfoList.Add(P); P.Col:=RxDBGrid.Columns[i] as TRxColumn; P.ColWidth:=RxDBGrid.Columns[i].Width; for j:=0 to TRxColumnTitle(RxDBGrid.Columns[i].Title).CaptionLinesCount-1 do P.ColTitles.Add(TRxColumnTitle(RxDBGrid.Columns[i].Title).CaptionLine(j).Caption); FTitleRowCount:=Max(FTitleRowCount, P.ColTitles.Count) end; end; end; procedure TRxDBGridPrint.DoShowColumnsTitle; var FBand: TfrBandView; FView: TfrMemoView; i: Integer; begin FBand := TfrBandView(frCreateObject(gtBand, '', FPage)); FBand.BandType := btMasterHeader; FBand.SetBounds(0, FYPos, 1000, 20 * FTitleRowCount); FBand.Flags:=FBand.Flags or flStretched; // FPage.Objects.Add(FBand); if FShowColumnHeaderOnAllPage then FBand.Flags:=FBand.Flags + flBandRepeatHeader; for i:=0 to FTitleRowCount-1 do begin FView := frCreateObject(gtMemo, '', FPage) as TfrMemoView; FView.SetBounds(FXPos, FYPos, 20, 20); FView.Alignment:=taCenter; FView.FillColor := clSilver; // FView.Font.Assign(FTitleFont); FView.Font.Size:=12; FView.Frames:=frAllFrames; FView.Layout:=tlTop; FView.Memo.Add(Format('Header_%d', [i])); // FPage.Objects.Add(FView); FYPos:=FYPos + 20 end; FYPos := FYPos + 2; end; procedure TRxDBGridPrint.DoShowFooter; var FBand: TfrBandView; FView: TfrMemoView; i: Integer; begin FBand := TfrBandView(frCreateObject(gtBand, '', FPage)); FBand.BandType := btMasterFooter; FBand.SetBounds(FXPos, FYPos, 1000, 20); FBand.Flags:=FBand.Flags or flStretched; // FPage.Objects.Add(FBand); FView := frCreateObject(gtMemo, '', FPage) as TfrMemoView; FView.SetBounds(FXPos, FYPos, 20, 20); if rxpoShowFooterColor in FOptions then FView.FillColor := RxDBGrid.FooterOptions.Color; // FView.Font.Assign(FTitleFont); FView.Font.Size:=12; FView.Frames:=frAllFrames; FView.Layout:=tlTop; FView.Memo.Add(Format('Footer', [i])); // FPage.Objects.Add(FView); FYPos := FYPos + 22; end; procedure TRxDBGridPrint.OnPrintColumn(ColNo: Integer; var Width: Integer); begin if (ColNo > 0) and (ColNo <= FRxColInfoList.Count) then Width := TRxColInfo(FRxColInfoList[ColNo-1]).ColWidth; end; procedure TRxDBGridPrint.OnEnterRect(Memo: TStringList; View: TfrView); var i, k: Integer; F:TRxColInfo; S: String; C:TColor; J: Integer; begin i := FColumnDataset.RecNo; if (i >= 0) and (i < FRxColInfoList.Count) then begin F:=TRxColInfo(FRxColInfoList[i]); View.dx := F.ColWidth; if Assigned(F.Col) and (Memo.Count>0) then begin S:=Memo[0]; if (S='[Cell]') and Assigned(F.Col.Field) then begin if rxpoShowGridColor in FOptions then begin C:=F.Col.Color; if Assigned(RxDBGrid.OnGetCellProps) then RxDBGrid.OnGetCellProps(RxDBGrid, F.Col.Field, TfrMemoView(View).Font, C); TfrMemoView(View).FillColor:=C; end; S:=F.Col.Field.DisplayText; if Assigned(F.Col) and (F.Col.KeyList.Count > 0) and (F.Col.PickList.Count > 0) then begin J := F.Col.KeyList.IndexOf(S); if (J >= 0) and (J < F.Col.PickList.Count) then S := F.Col.PickList[j]; end else if (rxpoHideZeroValues in FOptions) and Assigned(F.Col.Field) and (F.Col.Field.DataType in [ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftLargeint]) and (F.Col.Field.AsFloat = 0) then S:=''; Memo[0] := S; TfrMemoView(View).Alignment:=F.Col.Alignment; end else if Copy(S, 1, 7) = 'Header_' then begin TfrMemoView(View).Alignment:=F.Col.Title.Alignment; K:=StrToIntDef(Copy(S, 8, Length(S)), 0); if TRxColumnTitle(F.Col.Title).CaptionLinesCount = 0 then begin S:=TRxColumnTitle(F.Col.Title).Caption; if K = 0 then Memo[0] := TRxColumnTitle(F.Col.Title).Caption else Memo[0] := ''; end else if K<TRxColumnTitle(F.Col.Title).CaptionLinesCount then begin; Memo[0] :=TRxColumnTitle(F.Col.Title).CaptionLine(k).Caption; //F.Col.Title.Caption; end else Memo[0] := ''; end else if S = 'Footer' then begin Memo[0] :=F.Col.Footer.DisplayText; TfrMemoView(View).Alignment:=F.Col.Footer.Alignment; end; end; end; end; procedure TRxDBGridPrint.SetPageMargin(AValue: TRxPageMargin); begin FPageMargin.Assign(AValue); end; function TRxDBGridPrint.DoExecTools: boolean; var C:integer; SaveDesign: TfrReportDesigner; begin Result:=false; if (RxDBGrid = nil) or (RxDBGrid.DataSource = nil) or (RxDBGrid.DataSource.Dataset = nil) then Exit; SaveDesign:=frDesigner; frDesigner:=nil; FDataSet := RxDBGrid.Datasource.Dataset; FReport:=TfrReport.Create(Self); FReport.OnPrintColumn:=@OnPrintColumn; FReport.OnEnterRect:=@OnEnterRect; FReportDataSet := TfrDBDataSet.Create(Self); FColumnDataSet := TfrUserDataSet.Create(Self); try DoSetupColumns; FReportDataSet.Name := 'frGridDBDataSet1'; FReportDataSet.DataSet := FDataSet; // FReportDataSet.DataSource := RxDBGrid.DataSource; FColumnDataSet.Name := 'frGridUserDataSet1'; FColumnDataSet.RangeEnd := reCount; FColumnDataSet.RangeEndCount := FRxColInfoList.Count; FReport.ShowProgress:=FShowProgress; DoCreateReport; FReport.ShowReport; Result:=true; finally FreeAndNil(FColumnDataSet); FreeAndNil(FReportDataSet); FreeAndNil(FReport); frDesigner:=SaveDesign; end; end; function TRxDBGridPrint.DoSetupTools: boolean; var RxDBGridPrintGrid_SetupForm: TRxDBGridPrintGrid_SetupForm; begin RxDBGridPrintGrid_SetupForm:=TRxDBGridPrintGrid_SetupForm.Create(Application); RxDBGridPrintGrid_SetupForm.Edit1.Text:=FReportTitle; RxDBGridPrintGrid_SetupForm.RadioGroup1.ItemIndex:=ord(FOrientation); RxDBGridPrintGrid_SetupForm.SpinEdit2.Value:=FPageMargin.Left; RxDBGridPrintGrid_SetupForm.SpinEdit1.Value:=FPageMargin.Top; RxDBGridPrintGrid_SetupForm.SpinEdit3.Value:=FPageMargin.Right; RxDBGridPrintGrid_SetupForm.SpinEdit4.Value:=FPageMargin.Bottom; RxDBGridPrintGrid_SetupForm.CheckBox1.Checked:=FShowColumnHeaderOnAllPage; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[0]:=rxpoShowTitle in FOptions; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[1]:=rxpoShowFooter in FOptions; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[2]:=rxpoShowFooterColor in FOptions; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[3]:=rxpoShowGridColor in FOptions; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[4]:=rxpoShowReportTitle in FOptions; RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[5]:=rxpoHideZeroValues in FOptions; Result:=RxDBGridPrintGrid_SetupForm.ShowModal = mrOk; if Result then begin FReportTitle := RxDBGridPrintGrid_SetupForm.Edit1.Text; FOrientation := TPrinterOrientation(RxDBGridPrintGrid_SetupForm.RadioGroup1.ItemIndex); FPageMargin.Left := RxDBGridPrintGrid_SetupForm.SpinEdit2.Value; FPageMargin.Top := RxDBGridPrintGrid_SetupForm.SpinEdit1.Value; FPageMargin.Right := RxDBGridPrintGrid_SetupForm.SpinEdit3.Value; FPageMargin.Bottom := RxDBGridPrintGrid_SetupForm.SpinEdit4.Value; FOptions:=[]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[0] then FOptions:=FOptions + [rxpoShowTitle]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[1] then FOptions:=FOptions + [rxpoShowFooter]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[2] then FOptions:=FOptions + [rxpoShowFooterColor]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[3] then FOptions:=FOptions + [rxpoShowGridColor]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[4] then FOptions:=FOptions + [rxpoShowReportTitle]; if RxDBGridPrintGrid_SetupForm.CheckGroup1.Checked[5] then FOptions:=FOptions + [rxpoHideZeroValues]; FShowColumnHeaderOnAllPage:=RxDBGridPrintGrid_SetupForm.CheckBox1.Checked; end; RxDBGridPrintGrid_SetupForm.Free; end; constructor TRxDBGridPrint.Create(AOwner: TComponent); begin inherited Create(AOwner); FPageMargin:=TRxPageMargin.Create; FCaption:=sPrintGrid; FShowProgress:=false; FRxColInfoList:=TObjectList.Create(true); FOrientation:=poPortrait; ShowSetupForm:=false; FOptions:=[rxpoShowTitle, rxpoShowFooter, rxpoShowGridColor, rxpoShowFooterColor, rxpoShowReportTitle]; FShowColumnHeaderOnAllPage:=false; end; destructor TRxDBGridPrint.Destroy; begin FreeAndNil(FRxColInfoList); FreeAndNil(FPageMargin); inherited Destroy; end; procedure TRxDBGridPrint.PreviewReport; begin Execute; end; end. { DONE -oalexs : Необходимо настраивать отступы в печатной форме} { DONE -oalexs : Необходимо настроить отображение раскраски ячеек } { DONE -oalexs : Необходимо правильно выгружать лукапные значение KeyList/PickList } { TODO -oalexs : Необходимо реализовать настройку шрифтов }
unit d01.coverage.Calculator; interface type TCalculator = class public function Calculate(i, j: Integer): Integer; end; implementation function TCalculator.Calculate(i, j: Integer): Integer; begin Calculate := i+j; end; end.
{ Module of routines that help writing code to deal with jump targets. } module sst_r_syo_goto; define sst_r_syo_goto; %include 'sst_r_syo.ins.pas'; { ************************************************ * * Subroutine SST_R_SYO_GOTO (JTARG, FLAGS, SYM_MFLAG) * * Make sure execution ends up as specified in the jump targets JTARG. * At this point, the MFLAG variable indicates the yes/no value. * SYM_MFLAG is the symbol descriptor for this MFLAG variable. * Execution is already at the right place for the "fall thru" case. } procedure sst_r_syo_goto ( {go to jump targets, as required} in out jtarg: jump_targets_t; {indicates where execution is to end up} in flags: jtarg_t; {indicates which jump targets to use} in sym_mflag: sst_symbol_t); {handle to MFLAG symbol} val_param; begin { * Jump to ERR target if not fall thru. } if (jtarg_err_k in flags) and {this jump target enabled ?} ( (not (jflag_fall_k in jtarg.err.flags)) or {not fall thru ?} (jflag_indir_k in jtarg.err.flags)) {indirect reference ?} then begin sst_opcode_new; {create new opcode for IF} sst_opc_p^.opcode := sst_opc_if_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_opc_p^.if_exp_p := sst_exp_make_var(sym_error_p^); sst_opc_p^.if_true_p := nil; sst_opc_p^.if_false_p := nil; sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_r_syo_jtarget_sym ( {get or make jump target symbol} jtarg.err, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} end; { * Jump to YES target if not fall thru. } if (jtarg_yes_k in flags) and {this jump target enabled ?} ( (not (jflag_fall_k in jtarg.yes.flags)) or {not fall thru ?} (jflag_indir_k in jtarg.yes.flags)) {indirect reference ?} then begin sst_opcode_new; {create new opcode for IF} sst_opc_p^.opcode := sst_opc_if_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_r_syo_comp_var_sym ( {create comparison expression} sym_mflag, {symbol for term 1} sym_mflag_yes_p^, {enum constant for term 2} sst_op2_eq_k, {comparison operation} sst_opc_p^.if_exp_p); {returned pointer to new expression} sst_opc_p^.if_true_p := nil; sst_opc_p^.if_false_p := nil; sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_r_syo_jtarget_sym ( {get or make jump target symbol} jtarg.yes, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} end; { * Jump to NO target if not fall thru. } if (jtarg_no_k in flags) and {this jump target enabled ?} ( (not (jflag_fall_k in jtarg.no.flags)) or {not fall thru ?} (jflag_indir_k in jtarg.no.flags)) {indirect reference ?} then begin sst_opcode_new; {create new opcode for IF} sst_opc_p^.opcode := sst_opc_if_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_r_syo_comp_var_sym ( {create comparison expression} sym_mflag, {symbol for term 1} sym_mflag_no_p^, {enum constant for term 2} sst_op2_eq_k, {comparison operation} sst_opc_p^.if_exp_p); {returned pointer to new expression} sst_opc_p^.if_true_p := nil; sst_opc_p^.if_false_p := nil; sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_r_syo_jtarget_sym ( {get or make jump target symbol} jtarg.no, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} end; end;
unit GX_EventHook; interface uses Windows, SysUtils, Classes, Forms; type ///<summary> /// This class is meant to be used as the destination of a TNotifyEvent. /// It is kept very simple on purpose. Use it as is, do *not* add to it or derive from it, do /// *not* rename the class. /// See the procedure below on how to use it. TNotifyEventHook = class public ///<summary> /// Store the original event here. </summary> OrigEvent: TMethod; ///<summary> /// Store the event you want to call here. </summary> HookEvent: TMethod; ///<summary> /// Assign this method to the Event you want to hook. /// It first calls HookEvent and afterwards OrigEvent. </summary> procedure HandleEvent(_Sender: TObject); virtual; constructor Create(_OrigEvent: TMethod; _HookEvent: TMethod); end; type ///<summary> /// This class is meant to be used as the destination of a TMessageEvent. /// It is kept very simple on purpose. Use it as is, do *not* add to it or derive from it, do /// *not* rename the class. /// See the procedure below on how to use it. TMessageEventHook = class public ///<summary> /// Store the original event here. </summary> OrigEvent: TMethod; ///<summary> /// Store the event you want to call here. </summary> HookEvent: TMethod; ///<summary> /// Assign this method to the Event you want to hook. /// It first calls HookEvent and afterwards OrigEvent. </summary> procedure HandleEvent(var _Msg: TMsg; var _Handled: Boolean); virtual; constructor Create(_OrigEvent: TMethod; _HookEvent: TMethod); end; type ///<summary> /// This class provides the abstract declarations of two class methods: /// GetEvent returns the original event handler, typecasted to TMethod /// SetEvent sets the replacement event handler, typecated from TMethod /// Both methods must be overriden to access an actual event. </summary> TSecureEventHook = class protected class function GetEvent: TMethod; virtual; abstract; class procedure SetEvent(_Value: TMethod); virtual; abstract; end; ///<summary> /// Provides the Methods Install and Remove to hook/unhook an event of type TNotifyEvent /// It uses the inherited virtual methods GetEvent and SetEvent to access the actual /// event. Since GetEvent/SetEvent are still abstract, a descendant is required /// that implements them. </summary> TSecureNotifyEventHook = class(TSecureEventHook) public class function Install(_HookEvent: TNotifyEvent): TNotifyEventHook; class procedure Remove(_Hook: TNotifyEventHook); end; type ///<summary> /// Implements the GetEvent/SetEvent methods to access Screen.ActiveFormChange </summary> TScreenActiveFormChangeHook = class(TSecureNotifyEventHook) protected class function GetEvent: TMethod; override; class procedure SetEvent(_Value: TMethod); override; end; type ///<summary> /// Implements the GetEvent/SetEvent methods to access Screen.ActiveControlChange </summary> TScreenActiveControlChangeHook = class(TSecureNotifyEventHook) protected class function GetEvent: TMethod; override; class procedure SetEvent(_Value: TMethod); override; end; type ///<summary> /// Provides the Methods Install and Remove to hook/unhook an event of type TMessageEvent /// It uses the inherited virtual methods GetEvent and SetEvent to access the actual /// event. Since GetEvent/SetEvent are still abstract, a descendant is required /// that implements them. </summary> TSecureMessageEventHook = class(TSecureEventHook) class function Install(_HookEvent: TMessageEvent): TMessageEventHook; class procedure Remove(_Hook: TMessageEventHook); end; type ///<summary> /// Implements the GetEvent/SetEvent methods to access Application.OnMessage </summary> TApplicationOnMessageHook = class(TSecureMessageEventHook) class function GetEvent: TMethod; override; class procedure SetEvent(_Value: TMethod); override; end; implementation { TNotifyEventHook } constructor TNotifyEventHook.Create(_OrigEvent, _HookEvent: TMethod); begin inherited Create; OrigEvent := _OrigEvent; HookEvent := _HookEvent; end; procedure TNotifyEventHook.HandleEvent(_Sender: TObject); begin if Assigned(HookEvent.Data) and Assigned(HookEvent.Code) then TNotifyEvent(HookEvent)(_Sender); if Assigned(OrigEvent.Data) and Assigned(OrigEvent.Code) then TNotifyEvent(OrigEvent)(_Sender); end; { TMessageEventHook } constructor TMessageEventHook.Create(_OrigEvent, _HookEvent: TMethod); begin inherited Create; OrigEvent := _OrigEvent; HookEvent := _HookEvent; end; procedure TMessageEventHook.HandleEvent(var _Msg: TMsg; var _Handled: Boolean); begin if Assigned(HookEvent.Data) and Assigned(HookEvent.Code) then TMessageEvent(HookEvent)(_Msg, _Handled); if Assigned(OrigEvent.Data) and Assigned(OrigEvent.Code) then TMessageEvent(OrigEvent)(_Msg, _Handled); end; { TSecureNotifyEventHook } class function TSecureNotifyEventHook.Install(_HookEvent: TNotifyEvent): TNotifyEventHook; var evt: TNotifyEvent; begin Result := TNotifyEventHook.Create(GetEvent, TMethod(_HookEvent)); evt := Result.HandleEvent; SetEvent(TMethod(evt)); end; class procedure TSecureNotifyEventHook.Remove(_Hook: TNotifyEventHook); var Ptr: TMethod; begin if not Assigned(_Hook) then begin // Just in case somebody did not check whether HookScreenActiveFormChange actually returned // a valid object or simply didn't call it. Exit; end; Ptr := GetEvent; if not Assigned(Ptr.Data) and not Assigned(Ptr.Code) then begin // Somebody has assigned NIL to the event. // It's probably safe to assume that there will be no reference to our hook left, so we just // free the object and be done. _Hook.Free; Exit; end; while TObject(Ptr.Data).ClassNameIs('TNotifyEventHook') do begin // Somebody who knows about this standard has hooked the event. // (Remember: Do not change the class name or the class structure. Otherwise this // check will fail!) // Let's check whether we can find our own hook in the chain. if Ptr.Data = _Hook then begin // We are lucky, nobody has tampered with the event, we can just assign the original event, // free the hook object and be done with it. SetEvent(_Hook.OrigEvent); _Hook.Free; Exit; end; // check the next event in the chain Ptr := TMethod(TNotifyEventHook(Ptr.Data).OrigEvent); end; // If we get here, somebody who does not adhere to this standard has changed the event. // The best thing we can do, is Assign NIL to the HookEvent so it no longer gets called. // We cannot free the hook because somebody might still have reference // to _Hook.HandleEvent. _Hook.HookEvent.Code := nil; _Hook.HookEvent.Data := nil; end; /// Assume you want to hook Screen.OnActiveFormChange (which is a TNotifyEvent) with /// the method HandleActiveFormChange of your already existing object MyObject. /// So you call HookScreenActiveFormChange like this: /// Hook := TScreenActiveFormChangeHook.Hook(MyObject.HandleActiveFormChange); class function TScreenActiveFormChangeHook.GetEvent: TMethod; begin Result := TMethod(Screen.OnActiveFormChange); end; class procedure TScreenActiveFormChangeHook.SetEvent(_Value: TMethod); begin Screen.OnActiveFormChange := TNotifyEvent(_Value); end; /// Assume you want to hook Screen.OnActiveControlChange (which is a TNotifyEvent) with /// the method HandleActiveFormChange of your already existing object MyObject. /// So you call HookScreenActiveFormChange like this: /// Hook := TScreenActiveControlChangeHook.Hook(MyObject.HandleActiveFormChange); class function TScreenActiveControlChangeHook.GetEvent: TMethod; begin Result := TMethod(Screen.OnActiveControlChange); end; class procedure TScreenActiveControlChangeHook.SetEvent(_Value: TMethod); begin Screen.OnActiveControlChange := TNotifyEvent(_Value); end; class function TSecureMessageEventHook.Install(_HookEvent: TMessageEvent): TMessageEventHook; var evt: TMessageEvent; begin Result := TMessageEventHook.Create(GetEvent, TMethod(_HookEvent)); evt := Result.HandleEvent; SetEvent(TMethod(evt)); end; class procedure TSecureMessageEventHook.Remove(_Hook: TMessageEventHook); var Ptr: TMethod; begin if not Assigned(_Hook) then begin // Just in case somebody did not check whether HookApplicationOnMessage actually returned // a valid object or simply didn't call it. Exit; end; Ptr := GetEvent; if not Assigned(Ptr.Data) and not Assigned(Ptr.Code) then begin // Somebody has assigned NIL to the event. // It's probably safe to assume that there will be no reference to our hook left, so we just // free the object and be done. _Hook.Free; Exit; end; while TObject(Ptr.Data).ClassNameIs('TMessageEventHook') do begin // Somebody who knows about this standard has hooked the event. // (Remember: Do not change the class name or the class structure. Otherwise this // check will fail!) // Let's check whether we can find our own hook in the chain. if Ptr.Data = _Hook then begin // We are lucky, nobody has tampered with the event, we can just assign the original event, // free the hook object and be done with it. SetEvent(_Hook.OrigEvent); _Hook.Free; Exit; end; // check the next event in the chain Ptr := TMethod(TMessageEventHook(Ptr.Data).OrigEvent); end; // If we get here, somebody who does not adhere to this standard has changed the event. // The best thing we can do, is Assign NIL to the HookEvent so it no longer gets called. // We cannot free the hook because somebody might still have reference // to _Hook.HandleEvent. _Hook.HookEvent.Code := nil; _Hook.HookEvent.Data := nil; end; class function TApplicationOnMessageHook.GetEvent: TMethod; begin Result := TMethod(Application.OnMessage); end; class procedure TApplicationOnMessageHook.SetEvent(_Value: TMethod); begin Application.OnMessage := TMessageEvent(_Value); end; end.
unit fDebugROMViewer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, math, StdCtrls, cMegaROM, cConfiguration, iNESImage; type TfrmDebugROMViewer = class(TForm) DrawGrid: TDrawGrid; lblLevel: TLabel; cbLevels: TComboBox; cmdRoomOrder: TButton; cmdLevelPointers: TButton; cmdEnemyPointer: TButton; cmdActualEnemyData: TButton; cmdPalette: TButton; cmdScroll: TButton; cmdRoomOrderStartOffset: TButton; cmdSpecObjData: TButton; procedure FormShow(Sender: TObject); procedure DrawGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure DrawGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure cmdRoomOrderClick(Sender: TObject); procedure cmdPaletteClick(Sender: TObject); procedure cmdEnemyPointerClick(Sender: TObject); procedure cmdActualEnemyDataClick(Sender: TObject); procedure cmdLevelPointersClick(Sender: TObject); procedure cmdScrollClick(Sender: TObject); procedure cmdRoomOrderStartOffsetClick(Sender: TObject); procedure cmdSpecObjDataClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; procedure JumpTo(pOffset : Integer); { Private declarations } public property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmDebugROMViewer: TfrmDebugROMViewer; implementation {$R *.dfm} procedure TfrmDebugROMViewer.FormShow(Sender: TObject); var i : Integer; begin cbLevels.Items.BeginUpdate; cbLevels.Items.Clear; for i := 0 to _ROMData.Levels.Count -1 do cbLevels.Items.Add(_ROMData.Levels[i].Name); cbLevels.Items.EndUpdate; cbLevels.ItemIndex := _ROMData.CurrentLevel; DrawGrid.ColWidths[0] := 80; DrawGrid.ColWidths[1] := 1; DrawGrid.ColWidths[34] := 1; DrawGrid.Col := 2; // DrawGrid.RowCount := floor(simpleroundto(_ROMData.ROM.ROMSize / $20,0)); end; procedure TfrmDebugROMViewer.DrawGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if ACol = 0 then CanSelect := False; if ACol = 1 then CanSelect := False; if ACol = 34 then CanSelect := False; end; procedure TfrmDebugROMViewer.DrawGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if ACol = 0 then begin DrawGrid.Font.Color := clBlack; DrawGrid.Canvas.TextOut(Rect.Left +4,Rect.Top+4,IntToHex(ARow * 32,8)); end; if (ACol > 1) and (Acol < 34) then begin { if (ARow * 32) + (Acol - 2) < _ROMdata.ROM.ROMSize then DrawGrid.Canvas.TextOut(Rect.Left,Rect.Top+4,IntToHex(_ROMdata.ROM[(ARow * 32) + (Acol - 2)],2));} end; if (ACol = 34) or (ACol = 1) then begin DrawGrid.Canvas.Brush.Color := clBlack; DrawGrid.Canvas.FillRect(Rect); end; Caption := 'Debug ROM Viewer O:' + IntToHex((DrawGrid.Col - 2) + (DrawGrid.Row * 32),8); end; procedure TfrmDebugROMViewer.JumpTo(pOffset : Integer); begin DrawGrid.Row := pOffset div 32; DrawGrid.Col := (pOffset mod 32) + 2; end; procedure TfrmDebugROMViewer.cmdRoomOrderClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].RoomOrderOffset + _ROMdata.ROM[_ROMData.Levels[cbLevels.ItemIndex].Properties['ScreenStartCheck1'].Value]); end; procedure TfrmDebugROMViewer.cmdPaletteClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].PaletteOffset); end; procedure TfrmDebugROMViewer.cmdEnemyPointerClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].EnemyPointerOffset); end; procedure TfrmDebugROMViewer.cmdActualEnemyDataClick(Sender: TObject); begin // JumpTo(_ROMdata.ROM.PointerToOffset(_ROMData.Levels[cbLevels.ItemIndex].EnemyPointerOffset)); end; procedure TfrmDebugROMViewer.cmdLevelPointersClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].RoomPointersOffset); end; procedure TfrmDebugROMViewer.cmdScrollClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].ScrollOffset + _ROMdata.ROM[_ROMData.Levels[cbLevels.ItemIndex].ScrollStartOffset]); end; procedure TfrmDebugROMViewer.cmdRoomOrderStartOffsetClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].Properties['ScreenStartCheck1'].Offset); end; procedure TfrmDebugROMViewer.cmdSpecObjDataClick(Sender: TObject); begin // JumpTo(_ROMData.Levels[cbLevels.ItemIndex].SpecObjOffset); end; end.
unit ucMain; interface uses uvMain, umMainData, uvITileView, umTileData, ucFrmTile; type TFormMainController<D : TTileDataModel, constructor> = class private fView: TFormMain; fModel: TTilesDataList<D>; fFrmTileController : TFrmTileController<D>; fdataChanged : boolean; procedure OnBtnAddClick(Sender: TObject); procedure OnBtnSaveClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure updateTilesLabel; public constructor Create(aView: TFormMain; aModel: TTilesDataList<D>; aFrmTileController : TFrmTileController<D>); destructor Destroy; override; procedure addTile(aTileData : D); procedure removeTile(aTile : ITileView); procedure DBLoadTiles; end; const MaxTileCount = 21; implementation uses SysUtils,Forms,Windows, ZDbcIntfs, uvLogin, controls; procedure TFormMainController<D>.updateTilesLabel; begin fView.lblTilesCount.Caption := intToStr(fView.pnlTiles.ControlCount) + '/' + intToStr(MaxTileCount); end; constructor TFormMainController<D>.Create(aView: TFormMain; aModel: TTilesDataList<D>; aFrmTileController : TFrmTileController<D>); var fmLogin : TfmLogin; begin inherited Create; fView := aView; fModel := aModel; fModel.OnAddTile := self.addTile; fFrmTileController := aFrmTileController; fFrmTileController.RemoveTileProc := self.removeTile; fView.btnAdd.OnClick := OnBtnAddClick; fView.btnSave.OnClick := OnBtnSaveClick; fView.OnCloseQuery := FormCloseQuery; updateTilesLabel; try fModel.ConnectDb; DBLoadTiles; fView.tailsReposition; updateTilesLabel; except Application.MessageBox('Неправильные параметры подключения.', 'Ошибка', mb_Ok); fView.pnlTool.Enabled := false; end; end; destructor TFormMainController<D>.Destroy; begin fModel.DisconnectDB; inherited Destroy; end; procedure TFormMainController<D>.addTile(aTileData : D); var tile : ITileView; begin tile := fFrmTileController.makeFrameTile(aTileData); fModel.TilesList.Add(aTileData); fView.tailsReposition; updateTilesLabel; end; procedure TFormMainController<D>.OnBtnAddClick(Sender: TObject); var TileData : TTileDataModel; begin if fView.pnlTiles.ControlCount >= 21 then begin Application.MessageBox('Больше 21-й папки вставлять нельзя.', 'Внимание', mb_Ok); exit; end; if Length(fView.edTileName.Text) < 3 then begin Application.MessageBox('В имени папки должно быть больше 2-х символов.', 'Внимание', mb_Ok); exit; end; TileData := D.Create; fFrmTileController.InitTileDataModel(TileData); addTile(TileData); TileData.DataState := dsIns; fdataChanged := true; end; procedure TFormMainController<D>.removeTile(aTile : ITileView); begin fView.pnlTiles.RemoveControl(aTile as TControl); (TTileDataModel(aTile.getTileData)).DataState := dsDel; fView.tailsReposition; updateTilesLabel; fdataChanged := true; end; procedure TFormMainController<D>.OnBtnSaveClick(Sender: TObject); var curTileData : TTileDataModel; i, maxNum : integer; begin maxNum := fModel.TilesList.Count - 1; // insert into DB for i := 0 to maxNum do begin curTileData := fModel.TilesList.Items[i]; if curTileData.DataState = dsIns then begin try fModel.DBInsertTile(curTileData); except //TODO переделать на счетчик ошибок и вывод одного окна обо всех неудачах в конце: Application.MessageBox('Ошибка записи в базу данных.', 'Внимание', mb_ok) ; exit; // возможн вариант продолжения цикла, но если не выйти, можно попасть на ряд раздражающих мельканий окна об ошибке end; curTileData.DataState := dsOk; end; end; // del from DB for i := maxNum downto 0 do begin curTileData := fModel.TilesList.Items[i]; if curTileData.DataState = dsDel then begin try fModel.DBDelTile(curTileData); except //TODO переделать на счетчик ошибок и вывод одного окна обо всех неудачах в конце: Application.MessageBox('Ошибка записи в базу данных.', 'Внимание', mb_ok) ; exit; // возможн вариант продолжения цикла, но если не выйти, можно попасть на ряд раздражающих мельканий окна об ошибке end; fModel.TilesList.Remove(curTileData); // List is owner for items => auto destroy items end; end; DBLoadTiles; updateTilesLabel; fView.tailsReposition; fdataChanged := false; end; procedure TFormMainController<D>.DBLoadTiles; var i, MaxNum : integer; curData : D; begin // чистка фреймов на главном окне: MaxNum := fView.pnlTiles.ControlCount - 1; for i := maxNum downto 0 do begin fView.pnlTiles.RemoveControl(fView.pnlTiles.Controls[i]); end; fView.IsTilesRepositionEnabled := false; fModel.DBLoadTiles; fView.IsTilesRepositionEnabled := true; end; procedure TFormMainController<D>.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:= not (fdataChanged and (Application.MessageBox('Данные были изменены. Отменить выход?', 'Внимание', mb_YesNo) = id_yes)); end; end.
unit uRealRelatorio; interface uses Vcl.Forms, System.SysUtils, FMX.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type tOrdemRelatorio = (tOrdemRelatorioCRESCENTE, tOrdemRelatorioDECRESCENTE); tOrdenacaoRelacaoProdutos = (tOrdenRelProdCODIGO, tOrdenRelProdNOME, tOrdenRelProdVALOR); procedure relatorioModelo(); procedure relatorioListagemGeralProdutos(ordenacao: tOrdenacaoRelacaoProdutos; ordem: tOrdemRelatorio); implementation uses dmRelatoriosFast, uConstantes, uUsuario; procedure relatorioModelo(); const RELATORIO_MODELO = 'MODELO DE RELATÓRIO PARA IMPRESSAO'; var relatorio: TdmRelatorioFast; dsConsulta: TFDQuery; begin relatorio := abrirModuloRelatorio(); dsConsulta := TFDQuery.Create(Application); try dsConsulta.Connection := conexaoSistema; dsConsulta.SQL.Text := 'SELECT * FROM RADIUS_PRODUTO'; dsConsulta.Active := True; relatorio.cdsModelo.Close; relatorio.cdsModelo.CreateDataSet; while not dsConsulta.Eof do begin relatorio.cdsModelo.Insert; relatorio.cdsModelo.FieldByName('CODIGO').AsInteger := dsConsulta.FieldByName('ID_PRODUTO').AsInteger; relatorio.cdsModelo.Post; dsConsulta.Next; end; abrirRelatorio(relatorio.frxReportModelo, RELATORIO_MODELO); finally FreeAndNil(dsConsulta); fecharModuloRelatorio(); end; end; procedure relatorioListagemGeralProdutos(ordenacao: tOrdenacaoRelacaoProdutos; ordem: tOrdemRelatorio); const RELATORIO_MODELO = 'RELAÇÃO GERAL DE PRODUTOS'; var relatorio: TdmRelatorioFast; dsConsulta: TFDQuery; strOrdenacao: string; strOrdem: string; begin relatorio := abrirModuloRelatorio(); dsConsulta := TFDQuery.Create(Application); try dsConsulta.Connection := conexaoSistema; case ordenacao of tOrdenRelProdCODIGO: strOrdenacao := ' ORDER BY ID_PRODUTO'; tOrdenRelProdNOME: strOrdenacao := ' ORDER BY NOME_PRODUTO'; tOrdenRelProdVALOR: strOrdenacao := ' ORDER BY VALOR_PRODUTO'; end; case ordem of tOrdemRelatorioCRESCENTE: strOrdem := ' DESC'; tOrdemRelatorioDECRESCENTE: strOrdem := ''; end; dsConsulta.SQL.Text := 'SELECT ID_PRODUTO, NOME_PRODUTO, VALOR_PRODUTO FROM RADIUS_PRODUTO ' + strOrdenacao + strOrdem; dsConsulta.Active := True; relatorio.cdsListagemProduto.Close; relatorio.cdsListagemProduto.CreateDataSet; while not dsConsulta.Eof do begin relatorio.cdsListagemProduto.Insert; relatorio.cdsListagemProduto.FieldByName('ID_PRODUTO').AsInteger := dsConsulta.FieldByName('ID_PRODUTO').AsInteger; relatorio.cdsListagemProduto.FieldByName('NOME_PRODUTO').AsString := dsConsulta.FieldByName('NOME_PRODUTO').AsString; relatorio.cdsListagemProduto.FieldByName('VALOR_PRODUTO').AsCurrency := dsConsulta.FieldByName('VALOR_PRODUTO').AsCurrency; relatorio.cdsListagemProduto.Post; dsConsulta.Next; end; abrirRelatorio(relatorio.frxReportListagemProduto, RELATORIO_MODELO); finally FreeAndNil(dsConsulta); fecharModuloRelatorio(); end; end; end.
unit m_radiobutton; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TMariaeRadioButton } TMariaeRadioButton = class(TRadioButton) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public procedure OnChange; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_radiobutton_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeRadioButton]); end; { TMariaeRadioButton } procedure TMariaeRadioButton.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; procedure TMariaeRadioButton.OnChange; begin Self.SetChanged(True); end; procedure TMariaeRadioButton.ResetChanged; begin Self.SetChanged(False); end; end.
unit aeLoaderAionCGF; interface uses windows, ae3DModelLoaderBase, aeGeometry, System.Generics.Collections, types, aeMesh, classes, sysutils, aeMaths, aeRenderable, aeIndexBuffer, aeVectorBuffer; const CGF_CHUNKTYPE_MESH = $CCCC0000; CGF_CHUNKTYPE_NODE = $CCCC000B; CGF_CHUNKTYPE_MATERIAL = $CCCC000C; CGF_FILETYPE_GEOMETRY = $FFFF0000; CGF_FILETYPE_ANIMATION = $FFFF0001; type TaeLoaderAionCGF = class(Tae3DModelLoaderBase) private type PaeAionCGFChunkHeader = ^TaeAionCGFChunkHeader; TaeAionCGFChunkHeader = record chunkType: integer; chunkVersion: integer; chunkOffset: integer; chunkId: integer; end; type PaeAionCGFNode823 = ^TaeAionCGFNode823; TaeAionCGFNode823 = packed record header: TaeAionCGFChunkHeader; name: array [0 .. 63] of ansichar; ObjectID: integer; ParentID: integer; nChildren: integer; MaterialID: integer; isGroupHead, isGroupMember: boolean; transformMatrix: TaeMatrix44; end; type PaeAionCGFMesh744 = ^TaeAionCGFMesh744; TaeAionCGFMesh744 = packed record header: TaeAionCGFChunkHeader; verticesCount: integer; verticesArray: array of single; indicesCount: integer; indexArray: array of word; end; var _cgfNodes: array of TaeAionCGFNode823; _cgfMeshes: array of TaeAionCGFMesh744; _cgfChunks: array of TaeAionCGFChunkHeader; function GetChunkByChunkID(chunkId: integer): Pointer; function GetMeshFromChunk(fs: TFileStream; chunk_offset: integer): TaeAionCGFMesh744; function GetNodeFromChunk(fs: TFileStream; chunk_offset: integer): TaeAionCGFNode823; function ReadChunkHeader(fs: TFileStream; chunk_offset: integer): TaeAionCGFChunkHeader; function RemoveLODMeshes(geo: TaeGeometry): integer; procedure ResetLoader; public constructor Create; function loadFromFile(file_name: string; var geo: TaeGeometry): boolean; override; end; implementation { TaeLoaderCGF } constructor TaeLoaderAionCGF.Create; begin self.setHandledFileExtension('cgf'); // we want to handle 3ds with this loader! self._fileType := AE_LOADER_FILETYPE_AIONCGF; end; function TaeLoaderAionCGF.GetChunkByChunkID(chunkId: integer): Pointer; var i: integer; begin result := nil; for i := 0 to length(self._cgfNodes) - 1 do if (self._cgfNodes[i].header.chunkId = chunkId) then begin result := @self._cgfNodes[i]; exit; end; for i := 0 to length(self._cgfMeshes) - 1 do if (self._cgfMeshes[i].header.chunkId = chunkId) then begin result := @self._cgfMeshes[i]; exit; end; end; function TaeLoaderAionCGF.GetMeshFromChunk(fs: TFileStream; chunk_offset: integer): TaeAionCGFMesh744; var m: TaeMesh; v, ind: integer; indx: integer; vert: single; begin result.header := self.ReadChunkHeader(fs, chunk_offset); fs.Position := fs.Position + 4; // Skip byte[hasVertexWeights, hasVertexColors, reserved1, reserved2] fs.ReadData(result.verticesCount, 4); fs.Position := fs.Position + 4; // skip uvs count fs.ReadData(result.indicesCount, 4); fs.Position := fs.Position + 4; // skip vertAnim reference if (result.verticesCount > 0) and (result.indicesCount > 0) then begin // copy data... SetLength(result.verticesArray, result.verticesCount * 3); SetLength(result.indexArray, result.indicesCount * 3); for v := 0 to result.verticesCount - 1 do begin //CryVertex fs.ReadData(vert, 4); vert := vert / 100.0; result.verticesArray[v * 3] := vert; fs.ReadData(vert, 4); vert := vert / 100.0; result.verticesArray[v * 3 + 1] := vert; fs.ReadData(vert, 4); vert := vert / 100.0; result.verticesArray[v * 3 + 2] := vert; fs.Position := fs.Position + 12; // Skip normal end; for ind := 0 to result.indicesCount - 1 do begin //CryFace fs.ReadData(indx, 4); result.indexArray[ind * 3] := indx; fs.ReadData(indx, 4); result.indexArray[ind * 3 + 1] := indx; fs.ReadData(indx, 4); result.indexArray[ind * 3 + 2] := indx; fs.Position := fs.Position + 8; // Skip normal end; end; end; (* char name[64]; int ObjectID; // ID of this node's object chunk (if present) int ParentID; // chunk ID of the parent Node's chunk int nChildren; // # of children Nodes int MatID; // Material chunk No bool IsGroupHead; bool IsGroupMember; float tm[4][4]; // transformation matrix Vec3 pos; // pos component of matrix CryQuat rot; // rotation component of matrix Vec3 scl; // scale component of matrix int pos_cont_id; // position controller chunk id int rot_cont_id; // rotation controller chunk id int scl_cont_id; // scale controller chunk id int PropStrLen; // lenght of the property string *) function TaeLoaderAionCGF.GetNodeFromChunk(fs: TFileStream; chunk_offset: integer): TaeAionCGFNode823; var sm: TaeSerializedMatrix44; begin result.header := self.ReadChunkHeader(fs, chunk_offset); ZeroMemory(@result.name[0], 64); fs.ReadData(@result.name[0], 64); fs.ReadData(result.ObjectID, 4); fs.ReadData(result.ParentID, 4); fs.ReadData(result.nChildren, 4); fs.ReadData(result.MaterialID, 4); fs.ReadData(result.isGroupHead, 1); fs.ReadData(result.isGroupMember, 1); fs.Position := fs.Position + 2; // Skip strange 2 bytes before transforma matrix... fs.ReadData(@sm[0], 4 * 16); result.transformMatrix.DeserializeMatrix44(sm); fs.Position := fs.Position + 26 * 4; // Skip other shit... end; function TaeLoaderAionCGF.loadFromFile(file_name: string; var geo: TaeGeometry): boolean; var fs: TFileStream; cgf_mesh: TaeMesh; ib: TaeIndexBuffer; vb: TaeVectorBuffer; signature: array [0 .. 5] of ansichar; cgf_file_type: integer; cgf_tableoffset: integer; cgf_chunk_count: integer; cgf_chunk_header: TaeAionCGFChunkHeader; cgf_chunk_mesh: TaeAionCGFMesh744; cgf_chunk_node: TaeAionCGFNode823; cgf_chunk_ptr: Pointer; i: integer; e: integer; v_i, i_i: integer; v: TVectorArray; begin self.ResetLoader; // Now, let's read. fs := TFileStream.Create(file_name, fmOpenRead); fs.ReadData(@signature[0], 6); if (signature = 'NCAion') then begin fs.Position := fs.Position + 2; // 2 00 bytes... fs.ReadData(cgf_file_type, 4); case cgf_file_type of CGF_FILETYPE_ANIMATION: begin result := False; exit; end; CGF_FILETYPE_GEOMETRY: begin // read headers fs.Position := fs.Position + 4; // unknown data fs.ReadData(cgf_tableoffset, 4); // now move to the chunk table fs.Position := cgf_tableoffset; fs.ReadData(cgf_chunk_count, 4); for i := 0 to cgf_chunk_count - 1 do begin cgf_chunk_header := self.ReadChunkHeader(fs, fs.Position); SetLength(self._cgfChunks, length(self._cgfChunks) + 1); self._cgfChunks[length(self._cgfChunks) - 1] := cgf_chunk_header; end; // process headers for i := 0 to cgf_chunk_count - 1 do begin case self._cgfChunks[i].chunkType of CGF_CHUNKTYPE_MESH: begin if (self._cgfChunks[i].chunkVersion = $744) then begin cgf_chunk_mesh := self.GetMeshFromChunk(fs, self._cgfChunks[i].chunkOffset); SetLength(self._cgfMeshes, length(self._cgfMeshes) + 1); self._cgfMeshes[length(self._cgfMeshes) - 1] := cgf_chunk_mesh; end; end; CGF_CHUNKTYPE_NODE: begin cgf_chunk_node := self.GetNodeFromChunk(fs, self._cgfChunks[i].chunkOffset); SetLength(self._cgfNodes, length(self._cgfNodes) + 1); self._cgfNodes[length(self._cgfNodes) - 1] := cgf_chunk_node; end; else // nothing end; end; geo := TaeGeometry.Create(fs.FileName); // cycle nodes, and see if we can find a geometry attached to the nodes... then we have correct transform values at least! for i := 0 to length(self._cgfNodes) - 1 do begin cgf_chunk_node := self._cgfNodes[i]; // get object that's bound to node...... if (cgf_chunk_node.ObjectID > 0) then begin for e := 0 to length(self._cgfMeshes) - 1 do if (self._cgfMeshes[e].header.chunkId = cgf_chunk_node.ObjectID) then begin // geo.GetLocalTransform.SetMatrix(cgf_chunk_node.transformMatrix); cgf_mesh := TaeMesh.Create; vb := TaeVectorBuffer.Create; vb.PreallocateVectors(self._cgfMeshes[i].verticesCount); ib := TaeIndexBuffer.Create; ib.PreallocateIndices(self._cgfMeshes[i].indicesCount); vb.AddVectorRange(@self._cgfMeshes[i].verticesArray[0], self._cgfMeshes[i].verticesCount); ib.AddIndexRange(@self._cgfMeshes[i].indexArray[0], self._cgfMeshes[i].indicesCount); vb.Pack; ib.Pack; cgf_mesh.SetVertexBuffer(vb); cgf_mesh.SetIndexBuffer(ib); geo.addMesh(cgf_mesh); end; end; end; // only keep largest mesh - the others are probably LOD! self.RemoveLODMeshes(geo); geo.updateBoundingVolume; end; end; end; fs.free; end; function TaeLoaderAionCGF.ReadChunkHeader(fs: TFileStream; chunk_offset: integer): TaeAionCGFChunkHeader; begin fs.Position := chunk_offset; fs.ReadData(result.chunkType, 4); fs.ReadData(result.chunkVersion, 4); fs.ReadData(result.chunkOffset, 4); fs.ReadData(result.chunkId, 4); end; function TaeLoaderAionCGF.RemoveLODMeshes(geo: TaeGeometry): integer; var maxVertexCount: integer; maxVertexCountIndex: integer; currentVertices: integer; i: integer; begin // remove lod meshes maxVertexCount := 0; maxVertexCountIndex := 0; result := 0; if (geo.getMeshes.Count > 0) then begin for i := 0 to geo.getMeshes.Count - 1 do begin currentVertices := geo.getMeshes[i].getVertexCount; if (currentVertices > maxVertexCount) then begin maxVertexCountIndex := i; maxVertexCount := currentVertices; end; end; // delete all meshes except maxVertexCountIndex! for i := 0 to geo.getMeshes.Count - 1 do if (i <> maxVertexCountIndex) then begin geo.getMeshes[i].free; geo.getMeshes[i] := nil; end; geo.getMeshes.Pack; geo.getMeshes.Capacity := 1; end; end; procedure TaeLoaderAionCGF.ResetLoader; begin SetLength(_cgfNodes, 0); SetLength(_cgfMeshes, 0); SetLength(_cgfChunks, 0); end; end.
{ The calculator program, reads arithmetic expressions following the next grammar, and calculates the value of those expressions according to the arithmetic and algebraic laws embedded in the leading procedures in the program. The input expressions should be attached to the syntax showed, if not, the program would indicate the mistake using a ^ symbol. The output is divided into lines per expression. Note that the syntax does not include negative numbers in expression parsing. If an error is catched, the expression would be evaluated until the program encounters the error. With two or more errors, the behaviour is undefined. The syntax has been designed to facilitate analysis without backtracking. This means that the program can read a character at a time from the input medium and choose the correct course of action wthout ever going wrong and having to retrace its steps. For example, when a factor is expected, the next character must be digit or a left parentheses: any other character must be erroneous. The next character must be always be available for inspection. Syntax: <calculation> ::= <expression> ";" | <expression> "," <calculation> <expression> ::= <term> | <term> <arithmetic> <expression> <arithmetic> ::= "+" | "-" <term> ::= <factor> | <factor> <algebraic> <term> <algebraic> ::= "*" | "/" <factor> ::= <number> | "(" <expression> ")" <number> ::= <digit> | <digit> <number> | <number> "." <number> <digit> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" Usage: INPUT: 180 / (2 * 3.14159), 16 * 62.5 * 27, 169 * (5 + 8); OUTPUT: 28.65 27000.00 2197.00 } program calculator(input, output); (* ====================== GLOBAL CONSTANTS ==================== *) const TERMINATOR = ';'; SEPARATOR = ','; (* ===================== GLOBAL VARIABLES ===================== *) var nextchar : char; nextpos : integer; result : real; (* ========================= FUNCTIONS ======================== *) function addition(a, b : real) : real; begin addition := a + b end; function substraction(a, b : real) : real; begin substraction := a - b end; (* ======================== PROCEDURES ======================== *) procedure readchar(var ch : char; var charpos : integer); (* ========== CONSTANTS ========== *) const BLANLK = ' '; begin {readchar} repeat if eoln then begin charpos := 0; ch := BLANLK; readln(); end else begin charpos := succ(charpos); read(ch); end; until ch <> BLANLK; end; {readchar} procedure reporterror(var errchar : char; var errcharpos : integer); (* ========== CONSTANTS ========== *) const MARKER = '^'; begin {reporterror} writeln(MARKER : errcharpos); while not (errchar = SEPARATOR) or (errchar = TERMINATOR) do readchar(errchar, errcharpos) end; {reporterror} procedure readnumber(var numchar : char; var numpos : integer; var numvalue : real); (* ========== CONSTANTS ========== *) const POINT = '.'; RADIX = 10; (* ========== VARIABLES ========== *) var count, scale : integer; begin {readnumber} numvalue := 0; while('0' <= numchar) and (numchar < chr(ord('0') + RADIX)) do begin numvalue := RADIX * numvalue + ord(numchar) - ord('0'); readchar(numchar, numpos) end; if numchar = POINT then begin readchar(numchar, numpos); scale := 0; while('0' <= numchar) and (numchar < chr(ord('0') + RADIX)) do begin numvalue := RADIX * numvalue + ord(numchar) - ord('0'); readchar(numchar, numpos); scale := succ(scale); end; for count := 1 to scale do numvalue := numvalue / RADIX; end; end; {readnumber} { An expression consists of terms and factors, while a factor may contain an expression, so this express the mutual recursive nature of the grammar. This means that expressions may be constructed recursively. } procedure readexpression(var exprchar : char; var exprpos : integer; var exprvalue : real); (* ========== CONSTANTS ========== *) const PLUS = '+'; MINUS = '-'; (* ========== VARIABLES ========== *) var addop : char; nexttermval : real; (* ====== NESTED PROCEDURES ====== *) procedure readterm(var termchar : char; var termpos : integer; var termvalue : real); (* ========== CONSTANTS ========== *) const MULTCHAR = '*'; DIVCHAR = '/'; (* ========== VARIABLES ========== *) var mulop : char; nextfacval : real; procedure readfactor(var factorchar : char; var factorpos : integer; var factorvalue : real); (* ========== CONSTANTS ========== *) const RADIX = 10; LEFTPAREN = '('; RIGHTPAREN = ')'; begin {readfactor} if ('0' < factorchar) and (factorchar < char(ord('0') + RADIX)) then readnumber(factorchar, factorpos, factorvalue) else if factorchar = LEFTPAREN then begin readchar(factorchar, factorpos); readexpression(factorchar, factorpos, factorvalue); if factorchar = RIGHTPAREN then readchar(factorchar, factorpos) else reporterror(factorchar, factorpos); end else begin reporterror(factorchar, factorpos); factorvalue := 0 end; end; {readfactor} begin {readterm} readfactor(termchar, termpos, termvalue); while (termchar = MULTCHAR) or (termchar = DIVCHAR) do begin mulop := termchar; readchar(termchar, termpos); readfactor(termchar, termpos, nextfacval); if mulop = MULTCHAR then termvalue := termvalue * nextfacval else if nextfacval <> 0 then termvalue := termvalue / nextfacval else reporterror(termchar, termpos); end; end; {readterm} begin {readexpression} readterm(exprchar, exprpos, exprvalue); while (exprchar = PLUS) or (exprchar = MINUS) do begin addop := exprchar; readchar(exprchar, exprpos); readterm(exprchar, exprpos, nexttermval); if addop = PLUS then exprvalue := addition(exprvalue, nexttermval) else exprvalue := substraction(exprvalue, nexttermval); end; end; {readexpression} (* ======================= MAIN PROGRAM ======================= *) begin {calculator} nextpos := 0; (* Position of the character *) readchar(nextchar, nextpos); while nextchar <> TERMINATOR do begin readexpression(nextchar, nextpos, result); if (nextchar = SEPARATOR) or (nextchar = TERMINATOR) then begin writeln(result : 10 : 2); if nextchar = SEPARATOR then readchar(nextchar, nextpos) end else reporterror(nextchar, nextpos); end end. {calculator}
unit FoldersUnit; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\FoldersUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "Folders" MUID: (4570501E037A) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit , BaseTypesUnit , BaseTreeSupportUnit , FiltersUnit , UnderControlUnit , ContextSearchSupportUnit ; const {* Значения flags для элемента FoldersNode. } NF_CONTROLLED: Cardinal = 1; {* Сохраненный элемент стоит на контроле. } NF_SHARED: Cardinal = 2; {* Расшарен ли этот узел (если папка). } NF_EXTERNAL: Cardinal = 4; {* Внешний узел. } NF_IN_SHARED: Cardinal = 8; {* Расположен ли этот узел в шареной папке. } NF_HAS_SHARED: Cardinal = 16; {* Есть ли в этом узле (если папка) шаренные папки. } NF_COMMENTS: Cardinal = 32; {* Папка Мои комментарии } NF_IN_COMMENTS: Cardinal = 64; {* Элемент внутри папки Мои кооментарии } NF_COMMON: Cardinal = 128; {* Папка Общие } NF_USER: Cardinal = 256; {* Папки внутри папки Общие (по именам пользователей) } NF_MY_DOCUMENTS: Cardinal = 512; {* Папка Мои документы } NF_MY_CONSULTATIONS: Cardinal = 1024; {* Папка Мои консультации } NF_FOLDER_SENT: Cardinal = 2048; {* Папка Мои консультации/Запросы в обработке } NF_FOLDER_RECEIVED: Cardinal = 4096; {* Папка Мои консультации/Ответы } NF_CONSULTATION_SENT: Cardinal = 8192; {* Консультация со статусом CS_SENT } NF_PAYMENT_REQUEST: Cardinal = 16384; {* Консультация со статусом CS_PAYMAND_REQUEST (Запрошена оплата) } NF_ANSWER_RECEIVED: Cardinal = 32768; {* Консультация со статусом CS_ANSWER_RECEIVED (получен ответ) } NF_ANSWER_READ: Cardinal = 65536; {* Консультация со статусом CS_ANSWER_READ (ответ прочитан) } NF_ESTIMATION_SENT: Cardinal = 131072; {* Консультация со статусом CS_ESTIMATION_SENT (отправлена оценка) } NF_FOLDER_DRAFTS: Cardinal = 262144; {* Папка Мои консультации/Исходящие запросы } NF_FOLDER_PAYMENT_REFUSAL: Cardinal = 524288; {* Папка Мои консультации/Неподтвержденные } NF_DRAFTS: Cardinal = 1048576; {* Консультация со статусом CS_DRAFTS (созданная, но еще не отправленная консультация) } NF_PAYMENT_REFUSAL: Cardinal = 2097152; {* Консультация со статусом CS_PAYMENT_REFUSAL (консультация с неподтвержденной оплатой) } NF_PAYMENT_CONFIRM: Cardinal = 4194304; {* Консультация со статусом CS_PAYMENT_CONFIRM (консультация с подтвержденной оплатой) } NF_VALIDATION_FAILED: Cardinal = 8388608; {* Консультация со статусом CS_VALIDATION_FAILED (консультация не отправлена, так как база невалидирована) } type TFolderId = Cardinal; {* тип папочной ноды } IFolders = interface; IFoldersNode = interface(INode) {* Специализированная нода для Папок. Хранит дополнительный атрибут "дата создания". Атрибуты Caption и Hint унаследованные от Node представляю собой Имя элемента и Пользовательский Комментарий соответственно. В качестве BaseEntity нода может содержать Закладку на Документ, Список, Запрос или собственно узел (Folder). Имена и хинты всех элементов (кроме узла) копируются при создании в ноду, однако потом могут изменятся независимо (т.е. изменения имени ноды не влечет за собой изменения имени сущности содержащейся в ней). } ['{6B1E4393-7BE4-4201-A8F9-D3C817C440B5}'] function GetId: TFolderId; stdcall; procedure GetCreationDate; stdcall; procedure SaveConsultationToXml(xml_file_path: PAnsiChar); stdcall; {* Сохраняет информацию о сущности, представляемой папочной нодой консультации в xml. } procedure SaveToXml(xml_file_path: PAnsiChar); stdcall; { can raise AccessDenied, InvalidEntityType } procedure LoadFromXml(xml_file_path: PAnsiChar); stdcall; { can raise AccessDenied, InvalidEntityType } {* загружает информацию из xml в папку (пустую, нерасшаренную). } procedure SaveToIntegrationXml(out aRet {* IString }); stdcall; { can raise InvalidEntityType } {* сохранить ноду для библиотеки интеграции } function CanSaveConsultationToXml: ByteBool; stdcall; {* Указывает может ли консультация быть сохранена в xml. } function CanSaveToXml: ByteBool; stdcall; {* указывает может ли нода быть сохранена в xml. } function CanLoadFromXml: ByteBool; stdcall; {* указывает можно ли в ноду загрузить данные из xml. } function CanSaveToIntegrationXml: ByteBool; stdcall; {* может ли нода быть сохранена для библиотеки интеграции } procedure GetPid; stdcall; property Id: TFolderId read GetId; {* Сонтент айди } property CreationDate: read GetCreationDate; {* Дата создания } end;//IFoldersNode IFolder = interface; IFolders = interface(IBaseCatalog) {* Интерфейс (менеджер) обеспечивающий работу с деревом папок. Сложит фабрикой для узлов (Folder). } ['{085870DB-A1B6-48E7-ADDD-3C9F3911FEF5}'] procedure CreateFolder(out aRet {* IFolder }); stdcall; {* Фабрика узлов, возвращает новый созданный экземпляр BaseEntity типа Folder. } procedure FindFolderNode(id: TFolderId {* Идентификатор узла папки. }; out aRet {* IFoldersNode }); stdcall; {* Найти узел папки по его идентификатору. Если не найден то CanNotFindData. } end;//IFolders TNotifyStatus = ( {* Статус изменения папки. } NS_NODE {* Изменена структура папки. Означает что удалился/добавился один из дочерних узлов. } , NS_CONTENT {* Изменено содержимое папки, например имя папки, комментарий, дата, и т.д. } );//TNotifyStatus IDoneNotifier = interface ['{B9089580-C0F0-43C8-B449-B2AA3A0D4FFF}'] function Done: ByteBool; stdcall; end;//IDoneNotifier IFolder = interface(IEntityBase) {* Реализация BaseEntity воплощающая узловой элемент дерва Папок. } ['{4B736A91-FDC7-4F00-B445-9C91CE120AB9}'] function GetShared: ByteBool; stdcall; procedure SetShared(const aValue: ByteBool); stdcall; function GetExternal: ByteBool; stdcall; function CanShare: ByteBool; stdcall; {* можно ли расшарить папку } property Shared: ByteBool read GetShared write SetShared; {* Для сетевой версии. Признак того что папка является общедоступной, т.е видимой другим пользователям. Прим. внешние папки вегда являются общедоступными. При попытки изменить данный признак у внешней папки генерируется исключение ConstantModify. } property External: ByteBool read GetExternal; {* Для сетевой версии. Признак того что папка является внешней (т.е. не собственной а принадлежащей другому пользователю). } end;//IFolder TFoldersItemType = ( {* Значения object_type для элемента FolderNode. } FIT_BOOKMARK {* Интерфейс Bookamark } , FIT_LIST {* Интерфейс List } , FIT_QUERY {* Интерфейс Query } , FIT_FOLDER {* Группирующий элемент (папка) } , FIT_CONSULTATION {* Консультация } , FIT_PHARM_LIST {* список мед. препаратов } , FIT_PHARM_BOOKMARK {* закладка на мед. препарат } , FIT_OLD_HISTORY {* Ссылка на старый журнал работы } );//TFoldersItemType TNotifyData = record {* Данные нотификации по изменению папок. } status: TNotifyStatus; {* Статус изменения. } done_notifier: ; folder: ; end;//TNotifyData IExternalFoldersChangeNotifier = interface {* Интерфейс нотификации изменения структуры папок. } ['{9AFA9214-42F7-439F-97DB-EB7827289CE0}'] procedure Fire(const data: TNotifyData {* Данные нотификации. }); stdcall; {* Произошло изменение папки. При этом необходимо перечитать только непосредственное содержимое папки, исключая рекурсивную прогрузку дочерних папок. } end;//IExternalFoldersChangeNotifier implementation uses l3ImplUses ; end.
PROGRAM SarahRevere(INPUT, OUTPUT); {Печать сообщения о том как идут британцы, в зависимости от того, первым во входе встречается 'land', 'sea' или 'by air'.} PROCEDURE CheckingWindow(VAR W1, W2, W3, W4, Looking: CHAR); BEGIN {CheckingWindow} IF ((W1 = 'L') OR (W1 = 'l')) AND ((W2 = 'A') OR (W2 = 'a')) AND ((W3 = 'N') OR (W3 = 'n')) AND ((W4 = 'D') OR (W4 = 'd')) {Land_Searc} THEN Looking := 'L'; IF ((W2 = 'S') OR (W2 = 's')) AND ((W3 = 'E') OR (W3 = 'e')) AND ((W4 = 'A') OR (W4 = 'a')) {Sea_Search} THEN Looking := 'S'; IF ((W2 = 'A') OR (W2 = 'a')) AND ((W3 = 'I') OR (W3 = 'i')) AND ((W4 = 'R') OR (W4 = 'r')) {Air_Search} THEN Looking := 'A' END; {CheckingWindow} PROCEDURE WindowSearch(VAR F1: TEXT; VAR Looking: CHAR); VAR W1, W2, W3, W4: CHAR; BEGIN {MoveWindow} W1 := ' '; W2 := ' '; W3 := ' '; W4 := ' '; Looking := 'Y'; WHILE NOT EOLN(F1) AND (Looking = 'Y') DO BEGIN W1 := W2; W2 := W3; W3 := W4; READ(F1, W4); IF EOLN THEN Looking := 'N'; CheckingWindow(W1, W2, W3, W4, Looking) END END; {MoveWindow} PROCEDURE WriteAnsw(VAR Look: CHAR); BEGIN {WriteAnsw} IF Look = 'N' THEN WRITELN('Sarah didn''t say') ELSE WRITE('British are coming by '); IF Look = 'L' THEN WRITELN('land.'); IF Look = 'S' THEN WRITELN('sea.'); IF Look = 'A' THEN WRITELN('air.') END; {WriteAnsw} VAR Looking: CHAR; BEGIN {SarahRevere} WindowSearch(INPUT, Looking); WriteAnsw(Looking) END. {SarahRevere}
unit uBoletoRWA; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, xmldom, XMLIntf, Menus, Grids, DBGrids, RPDBGrid, StdCtrls, cxButtons, DB, msxmldom, Forms, XMLDoc, DBClient, LbCipher, LbUtils, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, ExtCtrls, DBCtrls, JvExControls, JvNavigationPane, Buttons, ACBrBase, ACBrBoleto, ACBrBoletoFCFortesFr, ACBrBoletoFCFR, Math, TypInfo, uCobranca; type TfrmBoletoRWA = class(TForm) xmlBoletoRWA: TXMLDocument; DataSource1: TDataSource; RPDBGrid1: TRPDBGrid; cdsBoletoRWA: TClientDataSet; Panel1: TPanel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; btnAtualizar: TSpeedButton; JvNavPanelHeader1: TJvNavPanelHeader; DBText1: TDBText; DBText3: TDBText; Bevel1: TBevel; ACBrBoleto1: TACBrBoleto; ACBrBoletoFCFortes1: TACBrBoletoFCFortes; procedure cxButton1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure btnAtualizarClick(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure cdsBoletoRWAAfterOpen(DataSet: TDataSet); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ACBrBoletoFCFortes1ObterLogo(const PictureLogo: TPicture; const NumeroBanco: Integer); procedure RPDBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); private { Private declarations } NewDate: TDate; bMulta: Boolean; procedure ImprimeBoleto; procedure ConsultarBoleto; function GetLinkLoja(bConta: Boolean = False): string; public { Public declarations } end; var frmBoletoRWA: TfrmBoletoRWA; implementation uses funcoes, udmPrincipal, DateUtils; {$R *.dfm} { TfrmBoletoRWA } procedure TfrmBoletoRWA.ConsultarBoleto; var XML: TStringStream; begin try wait('Aguardando resposta dos Servidores da RWA...', 1); xmlBoletoRWA.FileName := GetLinkLoja; xmlBoletoRWA.Active := True; XML := TStringStream.Create(xmlBoletoRWA.XML.Text); cdsBoletoRWA.LoadFromStream(XML); cdsBoletoRWA.First; finally FreeAndNil(XML); xmlBoletoRWA.Active := False; wait; end; end; procedure TfrmBoletoRWA.cxButton1Click(Sender: TObject); begin ConsultarBoleto; end; procedure TfrmBoletoRWA.FormCreate(Sender: TObject); begin bMulta := False; ConsultarBoleto; end; procedure TfrmBoletoRWA.SpeedButton1Click(Sender: TObject); begin Close; end; procedure TfrmBoletoRWA.btnAtualizarClick(Sender: TObject); begin ConsultarBoleto; end; procedure TfrmBoletoRWA.ImprimeBoleto; var Titulo: TACBrTitulo; perc_multa, perc_juros: Double; valor_original, valor_corrigido: Currency; dias: Integer; begin ACBrBoleto1.ListadeBoletos.Clear; Titulo := ACBrBoleto1.CriarTituloNaLista; with ACBrBoleto1 do begin Banco.TipoCobranca := cobSantander; with Cedente do begin Agencia := cdsBoletoRWA.FieldByName('agencia').AsString; AgenciaDigito := '0'; Conta := cdsBoletoRWA.FieldByName('conta').AsString; ContaDigito := cdsBoletoRWA.FieldByName('conta_digito').AsString; Convenio := cdsBoletoRWA.FieldByName('convenio').AsString; CodigoCedente := cdsBoletoRWA.FieldByName('cedente_numero').AsString; Nome := 'RWA Comercio e Serviços de Informática LTDA'; TipoInscricao := pJuridica; CNPJCPF := '09058349000159'; ResponEmissao := tbBancoEmite; CEP := '13084762'; Logradouro := 'Rua Oscar Alves Costa'; Cidade := 'Campinas'; Bairro := 'Jd. Santa Genebra II'; UF := 'SP'; Complemento := 'Sala 05'; NumeroRes := ''; if StringEmBranco(cdsBoletoRWA.FieldByName('variacao').AsString) and (Banco.Numero = 033) then Modalidade := cdsBoletoRWA.FieldByName('carteira').AsString else Modalidade := cdsBoletoRWA.FieldByName('variacao').AsString; CodigoTransmissao := ''; CaracTitulo := tcSimples; end; with Titulo do begin Vencimento := cdsBoletoRWA.FieldByName('vencimento').AsDateTime; DataDocumento := cdsBoletoRWA.FieldByName('emissao').AsDateTime; NumeroDocumento := cdsBoletoRWA.FieldByName('seu_numero').AsString; EspecieDoc := ''; Aceite := atNao; DataProcessamento := dmPrincipal.SoData; NossoNumero := cdsBoletoRWA.FieldByName('nosso_numero').AsString; Carteira := cdsBoletoRWA.FieldByName('carteira').AsString; ValorDocumento := cdsBoletoRWA.FieldByName('valor').AsCurrency; Sacado.NomeSacado := cdsBoletoRWA.FieldByName('sacado_nome').AsString; Sacado.CNPJCPF := SoNumeros(cdsBoletoRWA.FieldByName('sacado_codigo').AsString); Sacado.Logradouro := cdsBoletoRWA.FieldByName('sacado_endereco').AsString; Sacado.Numero := cdsBoletoRWA.FieldByName('sacado_numero').AsString; Sacado.Bairro := cdsBoletoRWA.FieldByName('sacado_bairro').AsString; Sacado.Cidade := cdsBoletoRWA.FieldByName('sacado_cidade').AsString; Sacado.UF := cdsBoletoRWA.FieldByName('sacado_uf').AsString; Sacado.CEP := SoNumeros(cdsBoletoRWA.FieldByName('sacado_cep').AsString); ValorAbatimento := StrToCurrDef('', 0); ; LocalPagamento := ''; ValorMoraJuros := cdsBoletoRWA.FieldByName('mora_diaria').AsCurrency; ValorDesconto := cdsBoletoRWA.FieldByName('desconto').AsCurrency; ValorAbatimento := StrToCurrDef('', 0); ; DataMoraJuros := StrToDateDef('', 0); DataDesconto := cdsBoletoRWA.FieldByName('desconto').AsCurrency; DataAbatimento := StrToDateDef('', 0); DataProtesto := StrToDateDef('', 0); PercentualMulta := cdsBoletoRWA.FieldByName('multa').AsCurrency / ValorDocumento * 100; Mensagem.Text := cdsBoletoRWA.FieldByName('instrucoes').AsString; //OcorrenciaOriginal.Tipo := toRemessaBaixar; Instrucao1 := cdsBoletoRWA.FieldByName('instrucoes').AsString; Instrucao2 := cdsBoletoRWA.FieldByName('instrucoes_juros').AsString; //ACBrBoleto1.AdicionarMensagensPadroes(Titulo,Mensagem); if bMulta then begin valor_original := ValorDocumento; perc_multa := cdsBoletoRWA.FieldByName('multa').AsCurrency / valor_original; perc_juros := cdsBoletoRWA.FieldByName('mora_diaria').AsCurrency / valor_original; dias := Floor(NewDate - cdsBoletoRWA.FieldByName('vencimento').AsDateTime); valor_corrigido := valor_original * (1 + perc_multa); valor_corrigido := valor_corrigido + (dias * (valor_original * perc_juros)); ValorMoraJuros := 0; PercentualMulta := 0; Vencimento := NewDate; ValorDesconto := 0; ValorDocumento := valor_corrigido; Mensagem.Clear; if perc_juros > 0 then Mensagem.Add(Format('Cobrar juros de %s por dia de atraso após %s', [FormatFloat('R$ ###,##0.00', valor_corrigido * perc_juros), FormatDateTime('dd/mm/yyyy', NewDate)])); if perc_multa > 0 then Mensagem.Add(Format('Após o vencimento cobrar multa de %s', [FormatFloat('R$ ###,##0.00', valor_corrigido * perc_multa)])); Mensagem.Add('2a. Via'); end; end; end; ACBrBoleto1.Imprimir; end; procedure TfrmBoletoRWA.SpeedButton2Click(Sender: TObject); var Cobranca: TCobranca; begin NewDate := 0; bMulta := False; if cdsBoletoRWA.FieldByName('vencimento').AsDateTime >= dmPrincipal.SoData then ImprimeBoleto else begin Cobranca := TCobranca.Create; try Cobranca.InputTipoCobranca(NewDate); bMulta := NewDate > 0; ImprimeBoleto; finally FreeAndNil(Cobranca); end; end; end; function TfrmBoletoRWA.GetLinkLoja(bConta: Boolean): string; var Senha, Cliente: string; begin Cliente := SoNumeros(dmPrincipal.EmpresaCnpj); //Cliente := '01112320000104'; Senha := '1234'; Result := 'http://www.rwa.com.br/sistema/webservice/boletos/?senha=' + Senha + '&cliente=' + Cliente; //Result := 'http://127.0.0.1/site/sistema/webservice/boletos/?senha=' + Senha + '&cliente=' + Cliente; end; procedure TfrmBoletoRWA.cdsBoletoRWAAfterOpen(DataSet: TDataSet); var i: Integer; begin for i := 0 to Pred(DataSet.Fields.Count) do if (DataSet.Fields[i] is TFloatField) then (DataSet.Fields[i] as TFloatField).DisplayFormat := 'R$ #,##0.00'; end; procedure TfrmBoletoRWA.FormClose(Sender: TObject; var Action: TCloseAction); begin cdsBoletoRWA.Close; Action := caFree; end; procedure TfrmBoletoRWA.ACBrBoletoFCFortes1ObterLogo( const PictureLogo: TPicture; const NumeroBanco: Integer); begin dmPrincipal.ObterLogoBanco(PictureLogo, NumeroBanco); end; procedure TfrmBoletoRWA.RPDBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdSelected in State) then begin Exit; end else if (DataSource1.DataSet['vencimento'] < dmPrincipal.SoData) then begin if (MonthOf(DataSource1.DataSet['vencimento']) = MonthOf(dmPrincipal.SoData)) then RPDBGrid1.Canvas.Font.Style := [fsBold]; RPDBGrid1.Canvas.font.Color := clRed; RPDBGrid1.Canvas.FillRect(Rect); RPDBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end else if (MonthOf(DataSource1.DataSet['vencimento']) = MonthOf(dmPrincipal.SoData)) then begin if (DataSource1.DataSet['vencimento'] = dmPrincipal.SoData) then begin RPDBGrid1.Canvas.Font.Style := [fsItalic, fsBold]; RPDBGrid1.Canvas.font.Color := clGreen; RPDBGrid1.Canvas.FillRect(Rect); RPDBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end else begin RPDBGrid1.Canvas.Font.Style := [fsBold]; RPDBGrid1.Canvas.font.Color := clBlack; RPDBGrid1.Canvas.FillRect(Rect); RPDBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; end; end.
program Memory; uses crt,Win,Input,Message,Menu,Form,Base; {объявление классов - потомков библиотечных классов} Type TMain=Object(TMenu) {главное меню} may:boolean; {признак открытия файла} procedure Enter; virtual; end; Type TIName=object(TInput) {ввод имени файла} function Error:boolean; virtual; {проверка имени файла} end; Type TAdd=object(TForm) {форма для добавления записей} procedure Enter; virtual; {завершение ввода одной записи} end; Type TFind=Object(TForm) {форме для поиска телефонов} procedure Input; virtual; {ввод данных поиска} procedure Enter; virtual; {поиск одной записи} procedure Show; {вывод результата поиска в окна} end; {объявление объектов-переменнвх} var M:TMain; {объект Главное меню} N:TIName; {объект Ввод имени файла} A:TAdd; {объект Добавление записей} F:TFind; {объект Поиск записей} ND:TMessage; {объект Сообщение об отсутствии данных} B:TBase; {объект файл} {описание дополнительных методов} procedure TMain.Enter; {обработка выбора пунктов главного меню} begin case npos of 1:begin N.Draw; {выводим окно ввода} N.Input; {вводим имя файла, проверяя его допустимость} B.Open(N.inp.text); {если файл существует, то открываем, иначе - создаем} may:=true; {устанавливаем признак открытия файла} end; 2:if may then {если определен файл данных} A.Run; {осуществляем добавление записей} 3:if may then {если определен файл данных} F.Run; {осуществляем поиск записей} end; end; Function TIName.Error; {проверка имени файла} var l:integer; begin l:=pos('.',inp.Text); if l=0 then l:=length(inp.Text); if(l>0) and (l<=8) then Error:=false else Error:=true; end; procedure TAdd.Enter; {обработка пунктов меню добавления} begin case npos of 1:begin Input; {вводим фамилию, имя и телефон} B.Add(masinp[1].inp.text, masinp[2].inp.text, masinp[3].inp.text); {записываем в файл} end; end; {case} end; procedure TFind.Enter; {обработка пунтов меню поиска} begin case npos of 1:begin Input; {вводим фамилию и имя} if B.Find(masinp[1].inp.text, masinp[2].inp.text) then Show else ND.Run; {выводим сообщение об отсутствии данных} end; 2:begin if B.FindNext then Show else ND.Run; {выводим сообщение об отсутствии данных} end; end; end; procedure TFind.Input; {ввод данных для поиска информации} begin clear; {очищаем поля ввода} masinp[1].Input; {вводим фамилию} masinp[2].Input; {вводим имя} end; procedure TFind.Show; {вывод найденной информации в окно} begin clear; masinp[1].inp.text:=B.family; masinp[1].Draw; {выводим фамилию} masinp[2].inp.text:=B.name; masinp[2].Draw; {выводим имя} masinp[3].inp.text:=B.telefon; masinp[3].Draw; {выводим телефон} end; {описание констант для инициализации полей-массивов} const menu1:array[1..4] of TWin= ((x1:10; y1:14; x2:23; y2:18; attr:113; xt:3; yt:2; text:'Sozdat / Otkrit Knizhky'), (x1:26; y1:14; x2:39; y2:18; attr:113; xt:4; yt:2; text:'Zapisat telefon'), (x1:42; y1:14; x2:55; y2:18; attr:113; xt:5; yt:2; text:'Nayti telefon'), (x1:58; y1:14; x2:71; y2:18; attr:113; xt:4; yt:2; text:'Zavershit rabotu')); menu2:array[1..2] of TWin= ((x1:28; y1:18; x2:38; y2:21; attr:113; xt:2; yt:2; text:'Dobavit'), (x1:42; y1:18; x2:52; y2:21; attr:113; xt;2; yt;2; text:'Vihod')); menu3:array[1..3] of TWin= ((x1:23; y1:18; x2:33; y2:21; attr:113; xt:2; yt:2; text:'Nayti'), (x1:35; y1:18; x2:45; y2:21; attr:113; xt:2; yt:2; text:'Sleduyutshiy'), (x1:47; y1:18; x2:57; y2:21; attr:113; xt;2; yt:2; text:'Vihod')); inpp:array[1..3] of TInput= ((x1:22; y1:8; x2:32; y2:8; attr:94; xt:1; yt:1; text:'Familiya'; Inp:(x1:34; y1:8; x2:54; y2:8; attr:112; xt:1; yt:1; text:'')), (x1:22; y1:10; x2:32; y2:10; attr:94; xt:1; yt:1; text:'Imya'; Inp:(x1:34; y1:10; x2:54; y2:10; attr: 112; xt:1; yt:1; text:'')), (x1,22; y1:12; x2:32; y2:12; attr:94; xt:1; yt:1; text:'Telefon'; Inp:(x1:34; y1:12; x2:54; y2:12; attr:112; xt:1; yt:1; text:''))); {основная программа} begin {инициализируем объекты} M.Init(5,5,76,20,30,5,3,'Zapisnaya knizhka',4,menu1); A.Init(20,2,60,22,94,5,3,'Dobavlenie zapisey',2,menu2,3,inpp); N.Init(30,8,50,19,94,3,3,'Vvedite imya fayla:',35,12,45,12,112,1,1,''); F.Init(20,2,60,22,94,5,3,'Poisk zapisey',3,menu3,3,inpp); ND.Init(30,6,50,14,30,6,2,'Net dannih',34,11,46,12,71,2,1,'Prodolzhit'); {начинаем работу} M.may:=false; {устанавливаем признак "файл не открыт"} M.Run; {передаем управление Главному меню} if may then B.Closef; {закрываем файл} {очищаем экран} TextBackGround(0); TextColor(1); Window(1,1,80,25); clrscr; end; begin end.
unit l3WindowsStorageFiler; {* Обертка вокруг потока, который работает с IStorage на диске. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3WindowsStorageFiler - } { Начат: 18.10.2001 16:43 } { $Id: l3WindowsStorageFiler.pas,v 1.12 2015/08/04 13:02:49 fireton Exp $ } // $Log: l3WindowsStorageFiler.pas,v $ // Revision 1.12 2015/08/04 13:02:49 fireton // - bug fix: AV // // Revision 1.11 2014/11/05 05:58:16 fireton // - не собиралось // // Revision 1.10 2004/09/24 08:56:46 lulin // - bug fix: не компилировалось. // // Revision 1.9 2004/08/31 17:02:20 law // - cleanup: убраны ненужные параметры. // // Revision 1.8 2002/06/17 13:44:45 law // - new const: m3_saRead, m3_saReadWrite, m3_saCreate. // // Revision 1.7 2002/02/22 10:30:52 law // - optimization: используем интерфейс Im3IndexedStorage. // // Revision 1.6 2001/11/28 14:19:30 law // - new behavior: сделано создание хранилищ с автоматической паковкой. // // Revision 1.5 2001/10/23 16:45:16 law // - new behavior: прикручено пакование потоков при записи. // // Revision 1.4 2001/10/23 15:21:06 law // - new behavior: прикручен пакованый IStream на чтение. // // Revision 1.3 2001/10/23 08:15:47 law // - new behavior: переделан под Мишанин IStorage. // // Revision 1.2 2001/10/19 16:20:23 law // - new unit: evEvdWriter. // // Revision 1.1 2001/10/18 14:54:37 law // - new unit: l3WindowsStorageFiler. // {$I l3Define.inc } interface uses Windows, ComObj, ActiveX, l3Types, l3InternalInterfaces, l3Filer, m3StorageInterfaces, m3stgmgr ; type Tl3CustomWindowsStorageFiler = class(Tl3CustomDOSFiler, Il3StorageSource) {* Обертка вокруг потока, который работает с IStorage на диске. } private // internal fields f_Storage : Im3IndexedStorage; f_Plain : Bool; protected // property methos function pm_GetStorage: IStorage; {-} protected // internal methods function DoOpen: Boolean; override; {-} procedure DoClose; override; {-} procedure Release; override; {-} public // public properties property Storage: Im3IndexedStorage read f_Storage write f_Storage; {-} property Plain: Bool read f_Plain write f_Plain default false; {-} end;//Tl3CustomWindowsStorageFiler Tl3WindowsStorageFiler = class(Tl3CustomWindowsStorageFiler) {*! Обертка вокруг потока, который работает с IStorage на диске. Для конечного использования на форме. } published {properties} property ReadOnly; {-} property FileName; {-} property NeedProcessMessages; {-} property Indicator; {-} property CodePage; {-} published {events} property OnCheckAbortedLoad; {-} end;//Tl3WindowsStorageFiler implementation uses Classes, l3Base, l3Stream, m2COMLib, m3ArcMgr ; // start class Tl3CustomWindowsStorageFiler procedure Tl3CustomWindowsStorageFiler.Release; //override; {-} begin inherited; Storage := nil; end; function Tl3CustomWindowsStorageFiler.pm_GetStorage: IStorage; {-} begin if Assigned(Storage) then Result := Storage.As_IStorage else Result := nil; end; function Tl3CustomWindowsStorageFiler.DoOpen: Boolean; //override; {-} var l_Status : Tl3IStatus; l_Name : WideString; l_IStream : IStream; l_Stream : TStream; begin if Plain then Result := inherited DoOpen else begin Result := true; try l_Name := FileName; Case Mode of l3_fmRead : begin l_Status := Tm3ReadModeStorageManager.MakeSafeInterface(f_Storage, l_Name); if (l_Status = STG_E_FILEALREADYEXISTS) OR (l_Status = STG_E_INVALIDHEADER) then begin Result := inherited DoOpen; Exit; end else begin OleCheck(l_Status); l_IStream := m2COMOpenStream(f_Storage.As_IStorage, 'main', STGM_READ or STGM_SHARE_EXCLUSIVE, false); end;//l_Status = STG_E_FILEALREADYEXISTS end;//l3_fmRead l3_fmWrite : begin OleCheck(Tm3FullModeStorageManager.MakeSafeInterface(f_Storage, l_Name)); l_IStream := m2COMCreateStream(f_Storage.As_IStorage, 'main', m3_saCreate, false); end;//l3_fmWrite l3_fmReadWrite : begin end;//l3_fmReadWrite l3_fmAppend : begin end;//l3_fmAppend end;//Case Mode if (l_IStream <> nil) then begin l3IStream2Stream(l_IStream, l_Stream); try l3Set(f_Stream, l_Stream); finally l3Free(l_Stream); end;//try..finally end;//l_IStream <> nil finally l_IStream := nil; end;//try..finally end;//Plain end; procedure Tl3CustomWindowsStorageFiler.DoClose; //override; {-} begin inherited; Storage := nil; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type tbit=(zero,one); tbit_vector=array of tbit; tbit_table=array of tbit_vector; { TForm1 } TForm1 = class(TForm) Button_exit: TButton; CheckGroupA: TCheckGroup; CheckGroupAminusB: TCheckGroup; CheckGroupAmultB: TCheckGroup; CheckGroupAdivB: TCheckGroup; CheckGroupAmodB: TCheckGroup; CheckGroupB: TCheckGroup; CheckGroupAplusB: TCheckGroup; Memo_help: TMemo; procedure Button_exitClick(Sender: TObject); procedure CheckGroupAItemClick(Sender: TObject; Index: integer); procedure CheckGroupBItemClick(Sender: TObject; Index: integer); private { private declarations } public { public declarations } procedure calc_a_oper_b; end; var Form1: TForm1; implementation {$R *.lfm} //===================================================================== //toffoli quantum gate //===================================================================== procedure CCNOT_gate(x1,x2,x3:tbit; var y1,y2,y3:tbit); begin if (x1=zero)and(x2=zero)and(x3=zero) then begin y1:=zero; y2:=zero; y3:=zero; end; if (x1=zero)and(x2=zero)and(x3=one) then begin y1:=zero; y2:=zero; y3:=one; end; if (x1=zero)and(x2=one)and(x3=zero) then begin y1:=zero; y2:=one; y3:=zero; end; if (x1=zero)and(x2=one)and(x3=one) then begin y1:=zero; y2:=one; y3:=one; end; if (x1=one)and(x2=zero)and(x3=zero) then begin y1:=one; y2:=zero; y3:=zero; end; if (x1=one)and(x2=zero)and(x3=one) then begin y1:=one; y2:=zero; y3:=one; end; if (x1=one)and(x2=one)and(x3=zero) then begin y1:=one; y2:=one; y3:=one; end; if (x1=one)and(x2=one)and(x3=one) then begin y1:=one; y2:=one; y3:=zero; end; end; function q_not(op1:tbit):tbit; var g1,g2:tbit; begin CCNOT_gate(one,one,op1,g1,g2,q_not); end; function q_and(op1,op2:tbit):tbit; var g1,g2:tbit; begin CCNOT_gate(op1,op2,zero,g1,g2,q_and); end; function q_xor(op1,op2:tbit):tbit; var g1,g2:tbit; begin CCNOT_gate(op1,one,op2,g1,g2,q_xor); end; function q_nand(op1,op2:tbit):tbit; var g1,g2:tbit; begin CCNOT_gate(op1,op2,one,g1,g2,q_nand); end; function q_or(op1,op2:tbit):tbit; begin q_or:=q_nand(q_not(op1),q_not(op2)); end; //bits cutter function bin_cut_bits(start_pos,end_pos:integer; var x:tbit_vector):tbit_vector; var tmp:tbit_vector; i:integer; begin setlength(tmp,end_pos-start_pos+1); for i:=start_pos to end_pos do tmp[i-start_pos]:=x[i]; bin_cut_bits:=tmp; end; //bits setter procedure bin_ins_bits(start_pos,end_pos:integer; var src,dst:tbit_vector); var i:integer; begin for i:=start_pos to end_pos do dst[i]:=src[i-start_pos]; end; procedure bin_set_bits(start_pos,end_pos:integer; value:tbit; var x:tbit_vector); var i:integer; begin for i:=start_pos to end_pos do x[i]:=value; end; {half-adder} procedure bin_half_adder(a,b:tbit; var s,c:tbit); begin c:=q_and(a,b); s:=q_xor(a,b); end; {full-adder} procedure bin_full_adder(a,b,c_in:tbit; var s,c_out:tbit); var s1,p1,p2:tbit; begin bin_half_adder(a,b,s1,p1); bin_half_adder(s1,c_in,s,p2); c_out:=q_or(p1,p2); end; {n-bit adder} procedure quantum_adder(a,b:tbit_vector; var s:tbit_vector); var i,n:integer; c:tbit_vector; begin n:=length(a); setlength(c,n+1); c[0]:=zero; for i:=0 to n-1 do bin_full_adder(a[i],b[i],c[i],s[i],c[i+1]); setlength(c,0); end; {n-bit subtractor} procedure quantum_subtractor(a,b:tbit_vector; var s:tbit_vector); var i,n:integer; c:tbit_vector; begin n:=length(a); setlength(c,n+1); c[0]:=one; for i:=0 to n-1 do bin_full_adder(a[i],q_not(b[i]),c[i],s[i],c[i+1]); setlength(c,0); end; {n-bit multiplier} procedure quantum_multiplier(a,b:tbit_vector; var s:tbit_vector); var i,n:integer; tmp_sum,tmp_op1:tbit_table; begin n:=length(a); setlength(tmp_op1,n); for i:=0 to n-1 do setlength(tmp_op1[i],n); setlength(tmp_sum,n+1); for i:=0 to n do setlength(tmp_sum[i],n+1); for i:=0 to n-1 do tmp_sum[0,i]:=zero; for i:=0 to n-1 do begin if b[i]=one then begin bin_set_bits(0,i-1,zero,tmp_op1[i]); bin_ins_bits(i,n-1,a,tmp_op1[i]); end else bin_set_bits(0,n-1,zero,tmp_op1[i]); quantum_adder(tmp_op1[i],tmp_sum[i],tmp_sum[i+1]); end; bin_ins_bits(0,n-1,tmp_sum[n],s); for i:=0 to n-1 do setlength(tmp_op1[i],0); setlength(tmp_op1,0); for i:=0 to n do setlength(tmp_sum[i],0); setlength(tmp_sum,0); end; {n-bit equal compare} procedure bin_is_equal(a,b:tbit_vector; var res:tbit); var res_tmp:tbit_vector; i,n:integer; begin n:=length(a); setlength(res_tmp,n+1); res_tmp[0]:=zero; for i:=0 to n-1 do res_tmp[i+1]:=q_or(res_tmp[i],q_xor(a[i],b[i])); res:=q_not(res_tmp[n]); setlength(res_tmp,0); end; {n-bit greater compare. if a>b then res:=1} procedure bin_is_greater_than(a,b:tbit_vector; var res:tbit); var tmp_res,tmp_carry,tmp_cmp,tmp_equ:tbit_vector; i,n:integer; begin n:=length(a); setlength(tmp_res,n+1); setlength(tmp_carry,n+1); setlength(tmp_cmp,n); setlength(tmp_equ,n); tmp_res[n]:=zero; tmp_carry[n]:=one; for i:=n-1 downto 0 do begin tmp_cmp[i]:=q_and(a[i],q_not(b[i])); tmp_equ[i]:=q_not(q_xor(a[i],b[i])); tmp_carry[i]:=q_and(tmp_carry[i+1],tmp_equ[i]); tmp_res[i]:=q_or(tmp_res[i+1],q_and(tmp_carry[i+1],tmp_cmp[i])); end; res:=tmp_res[0]; setlength(tmp_res,0); setlength(tmp_carry,0); setlength(tmp_cmp,0); setlength(tmp_equ,0); end; {n-bit divider} procedure quantum_divider(a,b:tbit_vector; var q,r:tbit_vector); var tmp_q,tmp_equal,tmp_greater: tbit_vector; tmp_r,tmp_b: tbit_table; i,n:integer; begin n:=length(a); setlength(tmp_q,n); setlength(tmp_equal,n); setlength(tmp_greater,n); setlength(tmp_r,n+1); setlength(tmp_b,n+1); for i:=0 to n do begin setlength(tmp_r[i],2*n-1); setlength(tmp_b[i],2*n-1); end; bin_set_bits(n,2*n-1,zero,tmp_r[0]); bin_ins_bits(0,n-1,a,tmp_r[0]); for i:=0 to n-1 do begin bin_is_greater_than(bin_cut_bits(n-i-1,n+n-i-2,tmp_r[i]),b,tmp_greater[n-i-1]); bin_is_equal(bin_cut_bits(n-i-1,n+n-i-2,tmp_r[i]),b,tmp_equal[n-i-1]); tmp_q[n-i-1]:=q_or(tmp_greater[n-i-1],tmp_equal[n-i-1]); bin_set_bits(n+n-i-1,n+n-1,zero,tmp_b[i]); bin_set_bits(0,n-i-2,zero,tmp_b[i]); if tmp_q[n-i-1]=zero then bin_set_bits(n-i-1,n+n-i-2,zero,tmp_b[i]) else bin_ins_bits(n-i-1,n+n-i-2,b,tmp_b[i]); quantum_subtractor(tmp_r[i],tmp_b[i],tmp_r[i+1]); end; q:=tmp_q; bin_ins_bits(0,n-1,tmp_r[n],r); setlength(tmp_q,0); setlength(tmp_equal,0); setlength(tmp_greater,0); for i:=0 to n do begin setlength(tmp_r[i],0); setlength(tmp_b[i],0); end; setlength(tmp_r,0); setlength(tmp_b,0); end; //====================================================================== { TForm1 } procedure TForm1.calc_a_oper_b; var n:integer; a,b,c,d:tbit_vector; begin //input data tuning n:=8; setlength(a,n); setlength(b,n); setlength(c,n); setlength(d,n); //get input data if CheckGroupA.Checked[7] then a[7]:=one else a[7]:=zero; if CheckGroupA.Checked[6] then a[6]:=one else a[6]:=zero; if CheckGroupA.Checked[5] then a[5]:=one else a[5]:=zero; if CheckGroupA.Checked[4] then a[4]:=one else a[4]:=zero; if CheckGroupA.Checked[3] then a[3]:=one else a[3]:=zero; if CheckGroupA.Checked[2] then a[2]:=one else a[2]:=zero; if CheckGroupA.Checked[1] then a[1]:=one else a[1]:=zero; if CheckGroupA.Checked[0] then a[0]:=one else a[0]:=zero; if CheckGroupB.Checked[7] then b[7]:=one else b[7]:=zero; if CheckGroupB.Checked[6] then b[6]:=one else b[6]:=zero; if CheckGroupB.Checked[5] then b[5]:=one else b[5]:=zero; if CheckGroupB.Checked[4] then b[4]:=one else b[4]:=zero; if CheckGroupB.Checked[3] then b[3]:=one else b[3]:=zero; if CheckGroupB.Checked[2] then b[2]:=one else b[2]:=zero; if CheckGroupB.Checked[1] then b[1]:=one else b[1]:=zero; if CheckGroupB.Checked[0] then b[0]:=one else b[0]:=zero; //summator work quantum_adder(a,b,c); //report if c[7]=one then CheckGroupAplusB.Checked[7]:=true else CheckGroupAplusB.Checked[7]:=false; if c[6]=one then CheckGroupAplusB.Checked[6]:=true else CheckGroupAplusB.Checked[6]:=false; if c[5]=one then CheckGroupAplusB.Checked[5]:=true else CheckGroupAplusB.Checked[5]:=false; if c[4]=one then CheckGroupAplusB.Checked[4]:=true else CheckGroupAplusB.Checked[4]:=false; if c[3]=one then CheckGroupAplusB.Checked[3]:=true else CheckGroupAplusB.Checked[3]:=false; if c[2]=one then CheckGroupAplusB.Checked[2]:=true else CheckGroupAplusB.Checked[2]:=false; if c[1]=one then CheckGroupAplusB.Checked[1]:=true else CheckGroupAplusB.Checked[1]:=false; if c[0]=one then CheckGroupAplusB.Checked[0]:=true else CheckGroupAplusB.Checked[0]:=false; //subtractor work quantum_subtractor(a,b,c); //report if c[7]=one then CheckGroupAminusB.Checked[7]:=true else CheckGroupAminusB.Checked[7]:=false; if c[6]=one then CheckGroupAminusB.Checked[6]:=true else CheckGroupAminusB.Checked[6]:=false; if c[5]=one then CheckGroupAminusB.Checked[5]:=true else CheckGroupAminusB.Checked[5]:=false; if c[4]=one then CheckGroupAminusB.Checked[4]:=true else CheckGroupAminusB.Checked[4]:=false; if c[3]=one then CheckGroupAminusB.Checked[3]:=true else CheckGroupAminusB.Checked[3]:=false; if c[2]=one then CheckGroupAminusB.Checked[2]:=true else CheckGroupAminusB.Checked[2]:=false; if c[1]=one then CheckGroupAminusB.Checked[1]:=true else CheckGroupAminusB.Checked[1]:=false; if c[0]=one then CheckGroupAminusB.Checked[0]:=true else CheckGroupAminusB.Checked[0]:=false; //multiplier work quantum_multiplier(a,b,c); //report if c[7]=one then CheckGroupAmultB.Checked[7]:=true else CheckGroupAmultB.Checked[7]:=false; if c[6]=one then CheckGroupAmultB.Checked[6]:=true else CheckGroupAmultB.Checked[6]:=false; if c[5]=one then CheckGroupAmultB.Checked[5]:=true else CheckGroupAmultB.Checked[5]:=false; if c[4]=one then CheckGroupAmultB.Checked[4]:=true else CheckGroupAmultB.Checked[4]:=false; if c[3]=one then CheckGroupAmultB.Checked[3]:=true else CheckGroupAmultB.Checked[3]:=false; if c[2]=one then CheckGroupAmultB.Checked[2]:=true else CheckGroupAmultB.Checked[2]:=false; if c[1]=one then CheckGroupAmultB.Checked[1]:=true else CheckGroupAmultB.Checked[1]:=false; if c[0]=one then CheckGroupAmultB.Checked[0]:=true else CheckGroupAmultB.Checked[0]:=false; //divider work quantum_divider(a,b,c,d); //report if c[7]=one then CheckGroupAdivB.Checked[7]:=true else CheckGroupAdivB.Checked[7]:=false; if c[6]=one then CheckGroupAdivB.Checked[6]:=true else CheckGroupAdivB.Checked[6]:=false; if c[5]=one then CheckGroupAdivB.Checked[5]:=true else CheckGroupAdivB.Checked[5]:=false; if c[4]=one then CheckGroupAdivB.Checked[4]:=true else CheckGroupAdivB.Checked[4]:=false; if c[3]=one then CheckGroupAdivB.Checked[3]:=true else CheckGroupAdivB.Checked[3]:=false; if c[2]=one then CheckGroupAdivB.Checked[2]:=true else CheckGroupAdivB.Checked[2]:=false; if c[1]=one then CheckGroupAdivB.Checked[1]:=true else CheckGroupAdivB.Checked[1]:=false; if c[0]=one then CheckGroupAdivB.Checked[0]:=true else CheckGroupAdivB.Checked[0]:=false; if d[7]=one then CheckGroupAmodB.Checked[7]:=true else CheckGroupAmodB.Checked[7]:=false; if d[6]=one then CheckGroupAmodB.Checked[6]:=true else CheckGroupAmodB.Checked[6]:=false; if d[5]=one then CheckGroupAmodB.Checked[5]:=true else CheckGroupAmodB.Checked[5]:=false; if d[4]=one then CheckGroupAmodB.Checked[4]:=true else CheckGroupAmodB.Checked[4]:=false; if d[3]=one then CheckGroupAmodB.Checked[3]:=true else CheckGroupAmodB.Checked[3]:=false; if d[2]=one then CheckGroupAmodB.Checked[2]:=true else CheckGroupAmodB.Checked[2]:=false; if d[1]=one then CheckGroupAmodB.Checked[1]:=true else CheckGroupAmodB.Checked[1]:=false; if d[0]=one then CheckGroupAmodB.Checked[0]:=true else CheckGroupAmodB.Checked[0]:=false; //clear memory setlength(a,0); setlength(b,0); setlength(c,0); setlength(d,0); end; procedure TForm1.Button_exitClick(Sender: TObject); begin close; end; procedure TForm1.CheckGroupAItemClick(Sender: TObject; Index: integer); begin calc_a_oper_b; end; procedure TForm1.CheckGroupBItemClick(Sender: TObject; Index: integer); begin calc_a_oper_b; end; end.
unit ddSchedulerConfigTypes; {$Include ..\dd\ddDefine.inc} interface uses l3Interfaces, l3ValueMap, l3TypedIntegerValueMap, ddCalendarEvents; type TddCalendarEventsMap = class(Tl3IntegerValueMap) private protected // protected methods function DoDisplayNameToValue(const aDisplayName: Il3CString): Integer; override; {* Функция очистки полей объекта. } procedure DoGetDisplayNames(const aList: Il3StringsEx); override; function DoValueToDisplayName(aValue: Integer): Il3CString; override; function GetMapSize: Integer; override; public constructor Make; end; implementation uses l3Base, l3String; { TddCalendarEventsMap } function TddCalendarEventsMap.DoDisplayNameToValue( const aDisplayName: Il3CString): Integer; var i: TddCalendarTaskType; l_Value: String; begin Result:= -1; l_Value:= l3Str(aDisplayName); for i:= low(TddCalendarTaskType) to High(TddCalendarTaskType) do if (i in ddEnabledTasks) and (ddCalendarEventArray[i].Caption = l_Value) then Result:= Ord(i); end; procedure TddCalendarEventsMap.DoGetDisplayNames( const aList: Il3StringsEx); var l_Index: TddCalendarTaskType; begin inherited; aList.Add('Выберите тип задания'); for l_Index := low(TddCalendarTaskType) to High(TddCalendarTaskType) Do if (l_Index in ddEnabledTasks) then aList.Add(l3CStr(ddCalendarEventArray[l_Index].Caption)); end; function TddCalendarEventsMap.DoValueToDisplayName( aValue: Integer): Il3CString; var i: TddCalendarTaskType; begin Result:= nil; if aValue = -1 then Result:= l3CStr('Выберите тип задания') else for i:= low(TddCalendarTaskType) to High(TddCalendarTaskType) do if (i in ddEnabledTasks) and (Ord(i) = aValue) then Result:= l3CStr(ddCalendarEventArray[i].Caption); end; function TddCalendarEventsMap.GetMapSize: Integer; var i: TddCalendarTaskType; begin Result:= 0; for i:= low(TddCalendarTaskType) to High(TddCalendarTaskType) do if (i in ddEnabledTasks) then Inc(Result) end; constructor TddCalendarEventsMap.Make; var l_Rec: Tl3ValueMapID; begin l_Rec.rName:= 'Календарь'; l_Rec.rID:= 1; Create(l_Rec, TypeInfo(Integer)); end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Creation: Jan 15, 2005 Description: Version: 1.00 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Unsupported code. Legal issues: Copyright (C) 2005-2006 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsHttpPost1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, IniFiles, StdCtrls, ExtCtrls, OverbyteIcsUrl, OverbyteIcsWndControl, OverbyteIcsHttpProt; type THttpPostForm = class(TForm) ToolsPanel: TPanel; DisplayMemo: TMemo; Label1: TLabel; Label2: TLabel; FirstNameEdit: TEdit; LastNameEdit: TEdit; Label3: TLabel; ActionURLEdit: TEdit; PostButton: TButton; Label4: TLabel; HttpCli1: THttpCli; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure PostButtonClick(Sender: TObject); procedure HttpCli1RequestDone(Sender: TObject; RqType: THttpRequest; ErrCode: Word); private FIniFileName : String; FInitialized : Boolean; public procedure Display(Msg : String); property IniFileName : String read FIniFileName write FIniFileName; end; var HttpPostForm: THttpPostForm; implementation {$R *.DFM} const SectionWindow = 'Window'; // Must be unique for each window KeyTop = 'Top'; KeyLeft = 'Left'; KeyWidth = 'Width'; KeyHeight = 'Height'; SectionData = 'Data'; KeyFirstName = 'FirstName'; KeyLastName = 'LastName'; KeyActionURL = 'ActionURL'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.FormCreate(Sender: TObject); begin FIniFileName := LowerCase(ExtractFileName(Application.ExeName)); FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.FormShow(Sender: TObject); var IniFile : TIniFile; begin if not FInitialized then begin FInitialized := TRUE; IniFile := TIniFile.Create(FIniFileName); Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width); Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height); Top := IniFile.ReadInteger(SectionWindow, KeyTop, (Screen.Height - Height) div 2); Left := IniFile.ReadInteger(SectionWindow, KeyLeft, (Screen.Width - Width) div 2); FirstNameEdit.Text := IniFile.ReadString(SectionData, KeyFirstName, 'John'); LastNameEdit.Text := IniFile.ReadString(SectionData, KeyLastName, 'Doe'); ActionURLEdit.Text := IniFile.ReadString(SectionData, KeyActionURL, 'http://localhost/cgi-bin/FormHandler'); IniFile.Destroy; DisplayMemo.Clear; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.FormClose(Sender: TObject; var Action: TCloseAction); var IniFile : TIniFile; begin IniFile := TIniFile.Create(FIniFileName); IniFile.WriteInteger(SectionWindow, KeyTop, Top); IniFile.WriteInteger(SectionWindow, KeyLeft, Left); IniFile.WriteInteger(SectionWindow, KeyWidth, Width); IniFile.WriteInteger(SectionWindow, KeyHeight, Height); IniFile.WriteString(SectionData, KeyFirstName, FirstNameEdit.Text); IniFile.WriteString(SectionData, KeyLastName, LastNameEdit.Text); IniFile.WriteString(SectionData, KeyActionURL, ActionURLEdit.Text); IniFile.Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.Display(Msg : String); begin DisplayMemo.Lines.BeginUpdate; try if DisplayMemo.Lines.Count > 200 then begin while DisplayMemo.Lines.Count > 200 do DisplayMemo.Lines.Delete(0); end; DisplayMemo.Lines.Add(Msg); finally DisplayMemo.Lines.EndUpdate; SendMessage(DisplayMemo.Handle, EM_SCROLLCARET, 0, 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.PostButtonClick(Sender: TObject); var Data : String; begin Data := 'FirstName=' + UrlEncode(Trim(FirstNameEdit.Text)) + '&' + 'LastName=' + UrlEncode(Trim(LastNameEdit.Text)) + '&' + 'Submit=Submit'; HttpCli1.SendStream := TMemoryStream.Create; HttpCli1.SendStream.Write(Data[1], Length(Data)); HttpCli1.SendStream.Seek(0, 0); HttpCli1.RcvdStream := TMemoryStream.Create; HttpCli1.URL := Trim(ActionURLEdit.Text); HttpCli1.PostAsync; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BuildLongString(Len : Integer) : String; var I : Integer; begin SetLength(Result, Len); for I := 1 to Len do Result[I] := Char(48 + (I mod 10)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpPostForm.HttpCli1RequestDone( Sender : TObject; RqType : THttpRequest; ErrCode : Word); var Data : String; begin HttpCli1.SendStream.Free; HttpCli1.SendStream := nil; if ErrCode <> 0 then begin Display('Post failed with error #' + IntToStr(ErrCode)); HttpCli1.RcvdStream.Free; HttpCli1.RcvdStream := nil; Exit; end; if HttpCli1.StatusCode <> 200 then begin Display('Post failed with error: ' + IntToStr(HttpCli1.StatusCode) + HttpCli1.ReasonPhrase); HttpCli1.RcvdStream.Free; HttpCli1.RcvdStream := nil; Exit; end; Display('Post was OK. Response was:'); HttpCli1.RcvdStream.Seek(0, 0); SetLength(Data, HttpCli1.RcvdStream.Size); HttpCli1.RcvdStream.Read(Data[1], Length(Data)); Display(Data); end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clBodyChooser; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Forms, Classes, Controls, StdCtrls, {$ELSE} Vcl.Forms, System.Classes, Vcl.Controls, Vcl.StdCtrls, {$ENDIF} clMailMessage; type TclMessageBodyChooser = class(TForm) btnOK: TButton; btnCancel: TButton; ComboBox: TComboBox; lkpType: TLabel; public class function AddSingleBody(AMessageBodies: TclMessageBodies): Boolean; end; implementation {$R *.DFM} { TclMessageBodyChooser } class function TclMessageBodyChooser.AddSingleBody(AMessageBodies: TclMessageBodies): Boolean; var i: Integer; Dlg: TclMessageBodyChooser; begin Dlg := TclMessageBodyChooser.Create(nil); try Dlg.Caption := 'Select Body Type'; for i := 0 to GetRegisteredBodyItems().Count - 1 do begin Dlg.ComboBox.Items.Add(TclMessageBodyClass(GetRegisteredBodyItems()[i]).ClassName); end; Dlg.ComboBox.ItemIndex := 0; Result := (Dlg.ShowModal() = mrOK); if Result then begin AMessageBodies.Add(TclMessageBodyClass(GetRegisteredBodyItems()[Dlg.ComboBox.ItemIndex])); end; finally Dlg.Free(); end; end; end.
unit GetAddressUnit; interface uses SysUtils, BaseExampleUnit, AddressUnit; type TGetAddress = class(TBaseExample) public procedure Execute(RouteId: String; RouteDestinationId: integer); end; implementation uses AddressParametersUnit; procedure TGetAddress.Execute(RouteId: String; RouteDestinationId: integer); var ErrorString: String; Parameters: TAddressParameters; Address: TAddress; begin Parameters := TAddressParameters.Create(); try Parameters.RouteId := RouteId; Parameters.RouteDestinationId := RouteDestinationId; Parameters.Notes := True; Address := Route4MeManager.Address.Get(Parameters, ErrorString); try WriteLn(''); if (Address <> nil) then begin WriteLn('GetAddress executed successfully'); WriteLn(Format('RouteId: %s; RouteDestinationId: %d', [Address.RouteId.Value, Address.RouteDestinationId.Value])); end else WriteLn(Format('GetAddress error: "%s"', [ErrorString])); finally FreeAndNil(Address); end; finally FreeAndNil(Parameters); end; end; end.
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {* Extract all the points that fitt the bill *} function Indices(const Mat:T2DByteArray; B:TBox; Value: Byte; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); WrapAroundBox(B, W+1,H+1); SetLength(Result, (B.x2-B.x1+1)*(B.y2-B.y1+1)); i := 0; for Y:=B.y1 to B.y2 do for X:=B.x1 to B.x2 do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DIntArray; B:TBox; Value: Integer; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); WrapAroundBox(B, W+1,H+1); SetLength(Result, (B.x2-B.x1+1)*(B.y2-B.y1+1)); i := 0; for Y:=B.y1 to B.y2 do for X:=B.x1 to B.x2 do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DExtArray; B:TBox; Value: Extended; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); WrapAroundBox(B, W+1,H+1); SetLength(Result, (B.x2-B.x1+1)*(B.y2-B.y1+1)); i := 0; for Y:=B.y1 to B.y2 do for X:=B.x1 to B.x2 do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DDoubleArray; B:TBox; Value: Double; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); WrapAroundBox(B, W+1,H+1); SetLength(Result, (B.x2-B.x1+1)*(B.y2-B.y1+1)); i := 0; for Y:=B.y1 to B.y2 do for X:=B.x1 to B.x2 do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DFloatArray; B:TBox; Value: Single; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); WrapAroundBox(B, W+1,H+1); SetLength(Result, (B.x2-B.x1+1)*(B.y2-B.y1+1)); i := 0; for Y:=B.y1 to B.y2 do for X:=B.x1 to B.x2 do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; {* Extract all the points that fitt the bill *} function Indices(const Mat:T2DByteArray; Value: Byte; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, (W+1)*(H+1)); i := 0; for Y:=0 to H do for X:=0 to W do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DIntArray; Value: Integer; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, (W+1)*(H+1)); i := 0; for Y:=0 to H do for X:=0 to W do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DExtArray; Value: Extended; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, (W+1)*(H+1)); i := 0; for Y:=0 to H do for X:=0 to W do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DDoubleArray; Value: Double; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, (W+1)*(H+1)); i := 0; for Y:=0 to H do for X:=0 to W do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end; function Indices(const Mat:T2DFloatArray; Value: Single; const Comparator:TComparator): TPointArray; overload; var X,Y,W,H,i: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, (W+1)*(H+1)); i := 0; for Y:=0 to H do for X:=0 to W do case Comparator of __LT__: if Mat[y][x] < Value then Result[Asc(i)] := Point(x,y); __GT__: if Mat[y][x] > Value then Result[Asc(i)] := Point(x,y); __EQ__: if Mat[y][x] = Value then Result[Asc(i)] := Point(x,y); __LE__: if Mat[y][x] <= Value then Result[Asc(i)] := Point(x,y); __GE__: if Mat[y][x] >= Value then Result[Asc(i)] := Point(x,y); __NE__: if Mat[y][x] <> Value then Result[Asc(i)] := Point(x,y); end; SetLength(Result, i); end;
unit ImageClient; interface uses SysUtils, Classes; type TImageClient = class public constructor Create; destructor Destroy; override; private fName : string; fWorld : string; fSize : integer; fStream : TStream; fLoaded : boolean; public function Recieve(var data; len : integer) : boolean; public property Name : string read fName write fName; property World : string read fWorld write fWorld; property Size : integer read fSize write fSize; property Loaded : boolean read fLoaded write fLoaded; property Stream : TStream read fStream; end; implementation // TImageClient constructor TImageClient.Create; begin inherited; fStream := TMemoryStream.Create; end; destructor TImageClient.Destroy; begin fStream.Free; inherited; end; function TImageClient.Recieve(var data; len : integer) : boolean; begin fStream.Write(data, len); result := fStream.Size >= fSize; end; end.
unit DebugWindow; {$I GX_CondDefine.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ImgList, Menus, ComCtrls, TrayIcon, ActnList, ToolWin; type TfmDebug = class(TForm) pmuTaskBar: TPopupMenu; mitTrayShutdown: TMenuItem; mitTrayShow: TMenuItem; MainMenu: TMainMenu; mitFile: TMenuItem; mitClearWindow: TMenuItem; mitFileSep1: TMenuItem; mitFileShutdown: TMenuItem; mitFileExit: TMenuItem; mitFileOptions: TMenuItem; ilDebug: TImageList; lvMessages: TListView; mitEdit: TMenuItem; mitCopySelectedLines: TMenuItem; imgMessage: TImage; mitTrayClear: TMenuItem; mitSaveToFile: TMenuItem; dlgSaveLog: TSaveDialog; tbnClear: TToolButton; tbnCopy: TToolButton; tbnSave: TToolButton; tbnSep1: TToolButton; Actions: TActionList; actFileOptions: TAction; actFileShutdown: TAction; actFileHideWindow: TAction; actEditCopySelectedLines: TAction; actEditClearWindow: TAction; actEditSaveToFile: TAction; actViewShow: TAction; actShowItemInDialog: TAction; ToolBar: TToolBar; tbnSep2: TToolButton; tbnOptions: TToolButton; tbnPause: TToolButton; actFilePause: TAction; mitFilePause: TMenuItem; pmuListbox: TPopupMenu; mitListClearWindow: TMenuItem; mitListShowItem: TMenuItem; mitView: TMenuItem; actViewStayOnTop: TAction; actViewToolBar: TAction; mitViewShowToolBar: TMenuItem; mitViewStayOnTop: TMenuItem; actEditSelectAll: TAction; mitEditSelectAll: TMenuItem; mitListSelectAll: TMenuItem; ilImages: TImageList; ilDisabled: TImageList; procedure TrayIconDblClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lvMessagesDblClick(Sender: TObject); procedure actEditCopySelectedLinesExecute(Sender: TObject); procedure actEditClearWindowExecute(Sender: TObject); procedure actEditSaveToFileExecute(Sender: TObject); procedure actFileOptionsExecute(Sender: TObject); procedure actFileShutdownExecute(Sender: TObject); procedure actFileHideWindowExecute(Sender: TObject); procedure actViewShowExecute(Sender: TObject); procedure actShowItemInDialogExecute(Sender: TObject); procedure actShowItemInDialogUpdate(Sender: TObject); procedure actFilePauseExecute(Sender: TObject); procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure actViewToolBarExecute(Sender: TObject); procedure actViewStayOnTopExecute(Sender: TObject); procedure actEditSelectAllExecute(Sender: TObject); private FAllowClose: Boolean; FStayOnTop: Boolean; FTaskIcon: TTrayIcon; procedure SetStayOnTop(OnTop: Boolean); procedure SaveSettings; procedure LoadSettings; procedure ApplicationMsgHandler(var Msg: TMsg; var Handled: Boolean); procedure WMEndSession(var Message: TMessage); message WM_ENDSESSION; procedure WMCopyData(var Message: TWMCopyData); message WM_COPYDATA; procedure WMQueryEndSession(var Message: TMessage); message WM_QUERYENDSESSION; property StayOnTop: Boolean read FStayOnTop write SetStayOnTop; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var fmDebug: TfmDebug; implementation {$R *.dfm} uses Clipbrd, Registry, DebugOptions, GX_GenericUtils; type TDebugType = (dtAnsiMessage, dtUnicodeMessage, dtSQL, dtCommand); TDebugMessage = record DebugType: TDebugType; MessageType: TMsgDlgType; AnsiMsg: AnsiString; UnicodeMsg: TGXUnicodeString; end; const TopMenu = 100; { TfmDebug } procedure TfmDebug.WMCopyData(var Message: TWMCopyData); var NewMsg: TDebugMessage; ListItem: TListItem; procedure AddMessage(MessageType: TMsgDlgType; const MessageText: string); begin if ConfigInfo.Bottom or (lvMessages.Items.Count = 0) then begin ListItem := lvMessages.Items.Add; ListItem.MakeVisible(True); end else ListItem := lvMessages.Items.Insert(0); ListItem.Caption := MessageText; ListItem.ImageIndex := Ord(MessageType); ListItem.SubItems.Add(TimeToStr(Time)); end; procedure GetMessage; const chrDebugTypeANSI = #1; chrDebugTypeSQL = #2; chrClearCommand = #3; chrDebugTypeUnicode = #4; var CData: TCopyDataStruct; MessageContent: PAnsiChar; i: Integer; CharWord: Word; UChar: TGXUnicodeChar; begin CData := Message.CopyDataStruct^; MessageContent := CData.lpData; // TODO: Make this use the passed-in byte count for the payload length if MessageContent[0] = chrClearCommand then begin NewMsg.DebugType := dtCommand; actEditClearWindow.Execute; Exit; end; if MessageContent[0] = chrDebugTypeSQL then NewMsg.DebugType := dtSQL else if MessageContent[0] = chrDebugTypeUnicode then NewMsg.DebugType := dtUnicodeMessage else NewMsg.DebugType := dtAnsiMessage; NewMsg.MessageType := TMsgDlgType(Integer(MessageContent[1]) - 1); i := 2; // Byte 0 = payload, Byte 1 = message type while MessageContent[i] <> #0 do begin if NewMsg.DebugType = dtUnicodeMessage then begin WordRec(CharWord).Lo := Byte(MessageContent[i]); WordRec(CharWord).Hi := Byte(MessageContent[i+1]); UChar := TGXUnicodeChar(CharWord); NewMsg.UnicodeMsg := NewMsg.UnicodeMsg + UChar; // TODO: This is very slow.... Inc(i, 2); end else begin NewMsg.AnsiMsg := NewMsg.AnsiMsg + MessageContent[i]; Inc(i); end; end; end; var OldClientWidth: Integer; begin GetMessage; if actFilePause.Checked then Exit; OldClientWidth := lvMessages.ClientWidth; if NewMsg.DebugType = dtAnsiMessage then AddMessage(NewMsg.MessageType, string(NewMsg.AnsiMsg)) else if NewMsg.DebugType = dtUnicodeMessage then AddMessage(NewMsg.MessageType, NewMsg.UnicodeMsg); // Resize the header when the scrollbar is added if not (lvMessages.ClientWidth = OldClientWidth) then FormResize(Self); if not Visible then FTaskIcon.Icon := imgMessage.Picture.Icon; if ConfigInfo.OnMessage then begin if IsIconic(Application.Handle) then begin ShowWindow(Application.Handle, SW_RESTORE); SetForegroundWindow(Application.Handle); end; Show; end; end; procedure TfmDebug.TrayIconDblClick(Sender: TObject); begin actViewShow.Execute; end; procedure TfmDebug.FormResize(Sender: TObject); begin if lvMessages.ClientWidth > 100 then lvMessages.Column[0].Width := lvMessages.ClientWidth - lvMessages.Column[1].Width; end; procedure TfmDebug.FormShow(Sender: TObject); begin FTaskIcon.Icon := Icon; FormResize(Self); MainMenu.Images := ilImages; end; procedure TfmDebug.SetStayOnTop(OnTop: Boolean); begin FStayOnTop := OnTop; if OnTop then SetWindowPos(Self.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE) else SetWindowPos(Self.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE); end; procedure TfmDebug.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := FAllowClose; if not CanClose then Hide; end; procedure TfmDebug.SaveSettings; var Settings: TRegIniFile; begin Settings := TRegIniFile.Create('Software\GExperts'); try Settings.WriteInteger('Debug', 'Left', Left); Settings.WriteInteger('Debug', 'Top', Top); Settings.WriteInteger('Debug', 'Width', Width); Settings.WriteInteger('Debug', 'Height', Height); Settings.WriteString('Debug', 'SavePath', dlgSaveLog.InitialDir); Settings.WriteBool('Debug', 'ViewToolBar', ToolBar.Visible); Settings.WriteBool('Debug', 'StayOnTop', FStayOnTop); finally FreeAndNil(Settings); end; end; procedure TfmDebug.LoadSettings; var Settings: TRegIniFile; begin Left := (Screen.Width - Width) div 2; Top := (Screen.Height - Height) div 2; Settings := TRegIniFile.Create('Software\GExperts'); try Left := Settings.ReadInteger('Debug', 'Left', Left); Top := Settings.ReadInteger('Debug', 'Top', Top); Width := Settings.ReadInteger('Debug', 'Width', Width); Height := Settings.ReadInteger('Debug', 'Height', Height); ToolBar.Visible := Settings.ReadBool('Debug', 'ViewToolBar', True); StayOnTop := Settings.ReadBool('Debug', 'StayOnTop', False); dlgSaveLog.InitialDir := Settings.ReadString('Debug', 'SavePath', ''); finally FreeAndNil(Settings); end; end; procedure TfmDebug.ApplicationMsgHandler(var Msg: TMsg; var Handled: Boolean); begin if (Msg.Message = WM_SYSCOMMAND) and (Msg.wParam = SC_RESTORE) then Show; end; procedure TfmDebug.WMEndSession(var Message: TMessage); begin FAllowClose := True; Close; inherited; end; procedure TfmDebug.WMQueryEndSession(var Message: TMessage); begin FTaskIcon.Active := False; FAllowClose := True; Close; inherited; end; procedure TfmDebug.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfmDebug.lvMessagesDblClick(Sender: TObject); begin actShowItemInDialog.Execute; end; procedure TfmDebug.actEditCopySelectedLinesExecute(Sender: TObject); var CopyStrings: TStrings; i: Integer; ListItem: TListItem; NewLine: string; begin CopyStrings := TStringList.Create; try for i := 0 to lvMessages.Items.Count - 1 do begin if lvMessages.Items[i].Selected then begin ListItem := lvMessages.Items[i]; NewLine := Format('%d'#9'%s'#9'%s', [ListItem.ImageIndex, ListItem.Caption, ListItem.SubItems[0]]); CopyStrings.Add(NewLine); end; end; Clipboard.AsText := CopyStrings.Text; finally FreeAndNil(CopyStrings); end; end; procedure TfmDebug.actEditClearWindowExecute(Sender: TObject); begin lvMessages.Items.BeginUpdate; try lvMessages.Items.Clear; finally lvMessages.Items.EndUpdate; end; FTaskIcon.Icon := Icon; FormResize(Self); end; procedure TfmDebug.actEditSaveToFileExecute(Sender: TObject); resourcestring SSaveError = 'Error saving messages: %s'; var i: Integer; Messages: TStrings; begin if lvMessages.Items.Count > 0 then begin // Note: this is not part of the IDE, hence we // do not do any "current folder" protection. if dlgSaveLog.Execute then try Messages := TStringList.Create; try for i := 0 to lvMessages.Items.Count - 1 do begin Messages.Add( IntToStr(lvMessages.Items[i].ImageIndex) + #9 + lvMessages.Items[i].Caption + #9 + lvMessages.Items[i].SubItems[0]); end; Messages.SaveToFile(dlgSaveLog.FileName); dlgSaveLog.InitialDir := ExtractFilePath(dlgSaveLog.FileName); finally FreeAndNil(Messages); end; except on E: Exception do MessageDlg(Format(SSaveError, [E.Message]), mtError, [mbOK], 0); end; end; end; procedure TfmDebug.actFileOptionsExecute(Sender: TObject); begin with TfmDebugOptions.Create(nil) do try ShowModal; finally Free; end; end; procedure TfmDebug.actFileShutdownExecute(Sender: TObject); begin FAllowClose := True; Close; end; procedure TfmDebug.actFileHideWindowExecute(Sender: TObject); begin Close; end; procedure TfmDebug.actViewShowExecute(Sender: TObject); begin Show; BringToFront; Application.BringToFront; EnsureFormVisible(Self); end; constructor TfmDebug.Create(AOwner: TComponent); resourcestring SAlwaysFStayOnTop = '&Always On Top'; begin inherited Create(AOwner); SetDefaultFont(Self); SetToolbarGradient(Toolbar); Application.OnMessage := ApplicationMsgHandler; FStayOnTop := False; Application.ShowHint := True; Caption := Application.Title; FTaskIcon := TTrayIcon.Create(Self); FTaskIcon.Icon := Icon; FTaskIcon.Active := True; FTaskIcon.PopupMenu := pmuTaskBar; FTaskIcon.ToolTip := Application.Title; FTaskIcon.OnDblClick := TrayIconDblClick; FAllowClose := False; LoadSettings; end; destructor TfmDebug.Destroy; begin SaveSettings; inherited Destroy; end; procedure TfmDebug.actShowItemInDialogExecute(Sender: TObject); begin if lvMessages.Selected <> nil then MessageDlg(lvMessages.Selected.Caption, mtInformation, [mbOK], 0); end; procedure TfmDebug.actShowItemInDialogUpdate(Sender: TObject); begin (Sender as TCustomAction).Enabled := (lvMessages.Selected <> nil); end; procedure TfmDebug.actFilePauseExecute(Sender: TObject); begin actFilePause.Checked := not actFilePause.Checked; end; procedure TfmDebug.ActionsUpdate(Action: TBasicAction; var Handled: Boolean); begin actViewStayOnTop.Checked := StayOnTop; actViewToolBar.Checked := ToolBar.Visible; end; procedure TfmDebug.actViewToolBarExecute(Sender: TObject); begin ToolBar.Visible := not ToolBar.Visible; end; procedure TfmDebug.actViewStayOnTopExecute(Sender: TObject); begin StayOnTop := not StayOnTop; end; procedure TfmDebug.actEditSelectAllExecute(Sender: TObject); var i: Integer; begin for i := 0 to lvMessages.Items.Count - 1 do lvMessages.Items[i].Selected := True; end; end.
unit UntPadrao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, Vcl.ToolWin, Vcl.Buttons, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TExecutar = (navegacao, sentencaSQL, exibePanels, desabilitaBotoes, habilitaBotoes, exibeBotoes); type TFrmPadrao = class(TForm) ToolBarButtons: TToolBar; ImageListNormal: TImageList; btnPesquisar: TToolButton; btnOrdenar: TToolButton; Separador1: TToolButton; btnPrimeiro: TToolButton; btnAnterior: TToolButton; btnProximo: TToolButton; btnUltimo: TToolButton; Separador2: TToolButton; btnInserir: TToolButton; btnEditar: TToolButton; btnExcluir: TToolButton; Separador3: TToolButton; btnSalvar: TToolButton; btnCancelar: TToolButton; ImageListHot: TImageList; ImageListDisabled: TImageList; Separador4: TToolButton; btnSair: TToolButton; StatusBar1: TStatusBar; PanelEntrada: TPanel; labelStatus: TLabel; Label1: TLabel; ValorCampo: TEdit; btnOk: TSpeedButton; checkHabilita: TDBCheckBox; PanelFicha: TPanel; FDTabela: TFDTable; procedure btnSairClick(Sender: TObject); procedure btnPrimeiroClick(Sender: TObject); procedure btnAnteriorClick(Sender: TObject); procedure btnProximoClick(Sender: TObject); procedure btnUltimoClick(Sender: TObject); procedure btnInserirClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); private FExecutar : TExecutar; procedure SetExecutar (const Value: TExecutar); { Private declarations } public property Executar: TExecutar read FExecutar write SetExecutar ; { Public declarations } end; var FrmPadrao: TFrmPadrao; strSqlAtual : String ; tipoID: integer; strSql: String; nomeTabela: String; operacaoIncluir: Integer ; modoEdicao: String ; nomeJanela: String; valdata1, valdata2, val1, val2: String; tarefa: String; tarefaClick: integer ; mensagem: String; implementation {$R *.dfm} uses UntDM; procedure TFrmPadrao.btnAnteriorClick(Sender: TObject); begin FDTabela.Prior; Executar:= navegacao; Executar:= exibePanels; end; procedure TFrmPadrao.btnCancelarClick(Sender: TObject); begin FDTabela.Cancel; mensagem:= 'A inclusão ou alteração deste registro foi abortada.' ; APPLICATION.MessageBox(Pchar(mensagem), 'Atenção' , MB_OK+MB_ICONerror); Executar:= habilitabotoes; ValorCampo.text:= ''; ValorCampo.Enabled:= true; btnOk.Visible:= True; checkHabilita.Enabled:= False; PanelFicha.Enabled:= False; if FDTabela.FieldByName('STATUS').AsString = 'N' then labelstatus.Visible:= True else labelstatus.Visible:= False; end; procedure TFrmPadrao.btnEditarClick(Sender: TObject); begin FDTabela.Edit; ValorCampo.Enabled:= False; btnOk.Enabled:= False; checkHabilita.Enabled:= False; PanelFicha.Enabled:= True; FDTabela.FieldByName('DATA_ALT').AsDateTime:= Date; Executar:= desabilitaBotoes; STATUSbAR1.Panels[2].Text:= 'Alteração de registro' ; Executar:= exibePanels; end; procedure TFrmPadrao.btnExcluirClick(Sender: TObject); var confExcl: Integer ; begin Beep; confExcl:= Application.MessageBox( 'Confirma a exclusão desse registro? ', 'Atenção', MB_YESNO+MB_DEFBUTTON2+MB_ICONQUESTION) ; if confExcl = IDYES then BEGIN FDTabela.Delete; mensagem:= 'O registro foi excluido com sucesso.' ; Application.MessageBox(Pchar(mensagem) , 'Informação', MB_OK+MB_ICONINFORMATION); END; if confExcl = IDNO then BEGIN mensagem:= 'A exclusão desse registro foi abortada. '; Application.MessageBox(Pchar(mensagem) , 'Informação', MB_OK+MB_ICONINFORMATION); END; end; procedure TFrmPadrao.btnInserirClick(Sender: TObject); begin operacaoIncluir:= 1; if FDTabela.Active = False then begin FDTabela.Open(); end; FDTabela.Insert; ValorCampo.Enabled:= False; btnOk.Enabled:= False; checkHabilita.Enabled:= False; labelStatus.Visible:= False; PanelFicha.Enabled:= True; FDTabela.FieldByName('STATUS') .asString:= 'S'; FDTabela.FieldByName('DATA_INC') .aSDATETIME:= dATE; Executar:= desabilitaBotoes; StatusBar1.Panels[2].Text:= 'Inclusão de um novo registro'; Executar:= exibePanels; operacaoIncluir:= 0; end; procedure TFrmPadrao.btnPrimeiroClick(Sender: TObject); begin FDTabela.First; Executar:= navegacao; Executar:= exibePanels; end; procedure TFrmPadrao.btnProximoClick(Sender: TObject); begin FDTabela.Next; Executar:= navegacao; Executar:= exibePanels; end; procedure TFrmPadrao.btnSairClick(Sender: TObject); begin FDTabela.Close; Close; end; procedure TFrmPadrao.btnSalvarClick(Sender: TObject); begin FDTabela.Post; mensagem:= 'O registro foi incluido ou alterado com sucesso.'; aPPLICATION.MessageBox(Pchar(mensagem), 'Informação' , MB_OK+MB_ICONINFORMATION); ValorCampo.text:= ''; ValorCampo.Enabled:= true; btnOk.Visible:= True; checkHabilita.Enabled:= False; PanelFicha.Enabled:= False; if FDTabela.FieldByName ('STATUS').AsString = 'N' then labelStatus.Visible:= True else labelStatus.Visible:= False; end; procedure TFrmPadrao.btnUltimoClick(Sender: TObject); begin FDTabela.Last; Executar:= navegacao; Executar:= exibePanels; end; procedure TFrmPadrao.SetExecutar(const Value: TExecutar); begin FExecutar := Value ; case value of navegacao: //Habilita os botões de navegação begin if FDTabela.Eof = True then begin btnProximo.Enabled := False ; btnUltimo.Enabled := False ; end else begin btnProximo.Enabled := True ; btnUltimo.Enabled := True ; end; if FDTabela.Bof = True then begin btnPrimeiro.Enabled := False ; btnAnterior.Enabled := False ; end else begin btnPrimeiro.Enabled := True ; btnAnterior.Enabled := True ; end; end; //Desabilita botões ao incluir ou alterar um registro desabilitaBotoes: begin btnPesquisar.Enabled:= False; btnOrdenar.Enabled:=False; BtnPrimeiro.Enabled:= False; BtnAnterior.Enabled:=False; BtnProximo.Enabled:=False; btnUltimo.Enabled:=False; btnInserir.Enabled:= False; BtnEditar.Enabled:= False; BtnExcluir.Enabled:= False; BtnSalvar.Enabled:=True; BtnCancelar.Enabled:=True; BtnSair.Enabled:= False; end; //Executar a sentença SQL sentencaSQL: begin FDTabela.Close ; FDTabela.Open (); if (FDTabela.RecordCount = 0) and (operacaoIncluir = 0) then begin mensagem:= 'Não foi encontrado nenhum registro que' + #13 + 'satisfaça a sua pesquisa.' ; Application.MessageBox(Pchar(mensagem), 'Informação' , MB_OK+MB_ICONINFORMATION); end; end; //Exibe os textos nos paineis de barra de status exibePanels: begin StatusBar1.Panels[0].Text:= 'INC: ' + FDTabela.FieldByName('DATA_INC').AsString; StatusBar1.Panels[1].Text:= 'ALT: ' + FDTabela.FieldByName('ID').AsString; StatusBar1.Panels[3].Text:= 'ID ' + FDTabela.FieldByName('ID').AsString; if (FDTabela.RecordCount = 0) and (operacaoIncluir = 0) then begin StatusBar1.Panels[0].Text:= ''; StatusBar1.Panels[1].Text:= ''; StatusBar1.Panels[3].Text:= ''; end; if FDTabela.FieldByName('STATUS').AsString = 'N' then labelstatus.visible:= True else labelstatus.visible:=False; end; //Habilitar botões ao Salvar ou Cancelar uma inclusão ou alteração HabilitaBotoes: begin if FDTabela.RecordCount > 0 then begin btnPesquisar.Enabled:= True; btnOrdenar.Enabled:= True; end else begin btnPesquisar.Enabled:= False; btnOrdenar.Enabled:= False; end; BtnPrimeiro.Enabled:= True; BtnAnterior.Enabled:=True; BtnProximo.Enabled:=True; btnUltimo.Enabled:=True; btnInserir.Enabled:= True; if FDTabela.RecordCount = 0 then begin btnEditar.Enabled:= False; btnExcluir.Enabled:= False; end else begin btnEditar.Enabled:= True; btnExcluir.Enabled:= True; end; btnSalvar.Enabled:= False; btnCancelar.Enabled:= False; btnSair.Enabled:= True; end; //Exibir botões de edição: exibeBotoes: begin if modoEdicao = 'NNN' then //1 BEGIN btnInserir.Enabled:= False; BtnEditar.Enabled:= False; BtnExcluir.Enabled:= False; BtnSalvar.Enabled:=False; BtnCancelar.Enabled:=False; separador3.Visible:= False; separador4.Visible:= False; END; if modoEdicao = 'NNS' then //2 BEGIN btnInserir.Enabled:= False; BtnEditar.Enabled:= False; BtnExcluir.Enabled:= true; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'NSN' then //3 BEGIN btnInserir.Enabled:= False; BtnEditar.Enabled:= true; BtnExcluir.Enabled:= False; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'NSS' then //4 BEGIN btnInserir.Enabled:= False; BtnEditar.Enabled:= true; BtnExcluir.Enabled:= TRUE; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'SNN' then //5 BEGIN btnInserir.Enabled:= TRUE; BtnEditar.Enabled:= FALSE; BtnExcluir.Enabled:= FALSE; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'SNS' then //6 BEGIN btnInserir.Enabled:= TRUE; BtnEditar.Enabled:= FALSE; BtnExcluir.Enabled:= true; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'SSN' then //7 BEGIN btnInserir.Enabled:= TRUE; BtnEditar.Enabled:= TRUE; BtnExcluir.Enabled:= FALSE; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; if modoEdicao = 'SSS' then //8 BEGIN btnInserir.Enabled:= TRUE; BtnEditar.Enabled:= TRUE; BtnExcluir.Enabled:= true; BtnSalvar.Enabled:=true; BtnCancelar.Enabled:=true; separador3.Visible:= true; separador4.Visible:= true; END; end; end ; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} {.$DEFINE RUCOMMENTS} unit ElProcessUtils; interface uses ElList, ElTools, Windows, SysUtils, Messages, TlHelp32; type TProcessInfo = class ModuleName: string; PID: integer; ThreadCount: integer; PriorityCls: integer; function DiffersFrom(Source : TProcessInfo) : boolean; end; TModuleInformation = class ModuleName: string; ModulePath: string; hModule: THandle; end; procedure FillProcessList(L : TElList); procedure FillModuleList(PID: DWORD; L : TElList); function GetProcessHandle(ModuleName : string) : THandle; function ProcessExists(ModuleName : string) : boolean; procedure CloseProcess(ModuleName : string; Forced : boolean); function IsUsePSAPI: Boolean; implementation var APILoaded : boolean; (* {$ifndef BUILDER_USED} const TH32CS_SNAPHEAPLIST = $00000001; TH32CS_SNAPPROCESS = $00000002; TH32CS_SNAPTHREAD = $00000004; TH32CS_SNAPMODULE = $00000008; TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST or TH32CS_SNAPPROCESS or TH32CS_SNAPTHREAD or TH32CS_SNAPMODULE; TH32CS_INHERIT = $80000000; {$else} const {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_SNAPHEAPLIST} {$ENDIF} TH32CS_SNAPHEAPLIST = $00000001; {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_SNAPPROCESS} {$ENDIF} TH32CS_SNAPPROCESS = $00000002; {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_SNAPTHREAD} {$ENDIF} TH32CS_SNAPTHREAD = $00000004; {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_SNAPMODULE} {$ENDIF} TH32CS_SNAPMODULE = $00000008; {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_SNAPALL} {$ENDIF} TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST or TH32CS_SNAPPROCESS or TH32CS_SNAPTHREAD or TH32CS_SNAPMODULE; {$IFDEF VCL_4_USED} {$EXTERNALSYM TH32CS_INHERIT} {$ENDIF} TH32CS_INHERIT = $80000000; {$endif} *) type {$R-} PProcessIDArray = ^TProcessIDArray; TProcessIDArray = array[0..0] of Integer; PHMODULE = ^HMODULE; TProcessMemoryCounters = record cb:LongInt; // The size of the structure, in bytes PageFaultCount:LongInt; // The number of page faults PeakWorkingSetSize:LongInt; // The peak working set size WorkingSetSize:LongInt; // The current working set size QuotaPeakPagedPoolUsage:LongInt; // The peak paged pool usage QuotaPagedPoolUsage:LongInt; // The current paged pool usage QuotaPeakNonPagedPoolUsage:LongInt; // The peak nonpaged pool usage QuotaNonPagedPoolUsage:LongInt; // The current nonpaged pool usage PagefileUsage:LongInt; // The current pagefile usage PeakPagefileUsage:LongInt; // The peak pagefile usage end; TProcessEntry32 = packed record dwSize: DWORD; cntUsage: DWORD; th32ProcessId: DWORD; // this process th32DefaultHeapId: DWORD; th32ModuleId: DWORD; // associated exe cntThreads: DWORD; th32ParentProcessId: DWORD; // this process's parent process pcPriClassBase: Longint; // Base priority of process's threads dwFlags: DWORD; szExeFile: array[0..MAX_PATH - 1] of Char;// Path end; EnumProcessesProc = function (lpidProcess:PProcessIDArray; cb:LongInt; var cbNeedee:DWORD ):BOOL; stdcall; EnumProcessModulesProc = function(hProcess : THANDLE; lphModule : PHMODULE; cb : DWORD; var cbNeedee: DWORD ): Bool; stdcall; GetModuleFileNameExProc = function (hProcess:THandle; // handle to the process hMoe:HMODULE; // handle to the module lpBaseName:PChar; // buffer that receives the base name nSize: DWORD // size of the buffer ):LongInt; stdcall; GetProcessMemoryInfoProc = function(hProcess:THandle; // handle to the process ppsmemCounters:TProcessMemoryCounters; // structure that receives information cb : DWORD // size of the structure ) : BOOL; stdcall; CreateToolhelp32SnapshotProc = function (dwFlags, th32ProcessIe: DWORD): THandle; stdcall; Process32FirstProc = function (hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; Process32NextProc = function (hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; const EnumProcesses : EnumProcessesProc = nil; EnumProcessModules : EnumProcessModulesProc = nil; GetModuleFileNameEx : GetModuleFileNameExProc = nil; GetProcessMemoryInfo : GetProcessMemoryInfoProc = nil; CreateToolHelp32Snapshot : CreateToolhelp32SnapshotProc = nil; Process32First : Process32FirstProc = nil; Process32Next : Process32NextProc = nil; function IsUsePSAPI: Boolean; begin Result := IsWinNT and (not IsWin2000Up); end; function TProcessInfo.DiffersFrom(Source : TProcessInfo) : boolean; begin result := (ModuleName <> Source.ModuleName) or (Self.PID <> Source.Pid) or (Self.ThreadCount <> Source.ThreadCount) or (Self.PriorityCls <> Source.PriorityCls); end; function GetProcessHandle(ModuleName : string) : THandle; var L: TElList; I: Integer; S: String; begin Result := INVALID_HANDLE_VALUE; L := TElList.Create; try L.AutoClearObjects := true; FillProcessList(L); S := LowerCase(ModuleName); for i := 0 to L.Count - 1 do begin if LowerCase(ExtractFileName(TProcessInfo(L[i]).ModuleName)) = S then begin result := OpenProcess(STANDARD_RIGHTS_REQUIRED, false, TProcessInfo(L[i]).PID); if result = 0 then result := INVALID_HANDLE_VALUE; exit; end; end; finally L.Free; end; end; function ProcessExists(ModuleName : string) : boolean; var L: TElList; I: Integer; S: String; begin L := TElList.Create; try L.AutoClearObjects := true; FillProcessList(L); S := LowerCase(ModuleName); for i := 0 to L.Count - 1 do begin if LowerCase(ExtractFileName(TProcessInfo(L[i]).ModuleName)) = S then begin result := true; exit; end; end; result := false; finally L.Free; end; end; procedure CloseProcess(ModuleName : string; Forced : boolean); var L: TElList; S: String; I, ID : Integer; hProc : THandle; function EnumWindowProc(Wnd : HWND; lParam : integer) : boolean; stdcall; var IID : DWORD; begin GetWindowThreadProcessId(Wnd, @IID); result := true; if Integer(IID) = LParam then begin PostMessage(Wnd, WM_CLOSE, 0, 0); result := false; end; end; begin L := TElList.Create; try L.AutoClearObjects := true; FillProcessList(L); S := LowerCase(ModuleName); for i := 0 to L.Count - 1 do begin if LowerCase(ExtractFileName(TProcessInfo(L[i]).ModuleName)) = S then begin ID := TProcessInfo(L[i]).PID; if Forced then begin hProc := OpenProcess(PROCESS_TERMINATE, false, ID); TerminateProcess(hProc, 0); end else EnumWindows(@EnumWindowProc, ID); end; end; finally L.Free; end; end; procedure FillProcessList(L : TElList); var pidArray : pProcessIDArray; mhArray : array[0..1000] of HMODULE; c : Cardinal; cb : DWORD; i,j : Integer; ph : THandle; buf : array[0..MAX_PATH] of char; Info : TProcessInfo; hSnapshot: THandle; pe32 : TProcessEntry32; begin L.Clear; if not ApiLoaded then exit; if IsUsePSAPI then begin c := 100 * sizeof(Integer); GetMem(pidArray, c); while true do begin if not EnumProcesses(pidArray, c, cb) then exit; if cb <= c then break; FreeMem(pidArray); c := cb; GetMem(pidArray, c); end; j := (cb div sizeof(integer)) - 1; for i := 0 to j do begin Info := TProcessInfo.Create; Info.PID := pidArray[i]; Info.PriorityCls := 0; ph := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,False,pidArray[i]); if ph <> 0 then begin if EnumProcessModules(ph, @mhArray, SizeOf(mhArray), CB) then begin if GetModuleFileNameEx(ph, mhArray[0], Buf, MAX_PATH)>0 then Info.ModuleName := StrPas(@Buf[0]) else Info.ModuleName := ''; Info.PriorityCls := GetPriorityClass(ph); Info.ThreadCount := 0; end; CloseHandle(ph); end; L.Add(Info); end; FreeMem(pidArray); end else begin hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe32.dwSize := sizeof(TProcessEntry32); if Process32First(hSnapshot, pe32) then repeat Info := TProcessInfo.Create; Info.PID := pe32.th32ProcessID; Info.ModuleName := pe32.szExeFile; Info.PriorityCls := pe32.pcPriClassBase; Info.ThreadCount := pe32.cntThreads; L.Add(Info); until not Process32Next(hSnapshot, pe32); CloseHandle(hSnapshot); end; end; procedure FillModuleList(PID: DWORD; L : TElList); var Info: TModuleInformation; // PSAPI.DLL PH: THandle; MODList: array[0..1000] of HMODULE; MODName: array [0..MAX_PATH - 1] of Char; i: Integer; modNeeded : DWORD; // CreateToolhelp32Snapshot me: TModuleEntry32; bOk: Boolean; m_hSnapshot: THandle; begin if L=nil then exit; L.Clear; if not ApiLoaded then exit; if PID=0 then PID := GetCurrentProcessId(); if IsUsePSAPI then begin PH := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if PH <> 0 then try if EnumProcessModules(PH, @MODList,1000, modNeeded) then begin for i := 0 to (modNeeded div SizeOf (HMODULE) - 1) do begin if GetModuleFileNameEx(PH, MODList[i], MODName, SizeOf(MODName)) > 0 then begin Info := TModuleInformation.Create; Info.hModule := MODList[i]; Info.ModuleName := ExtractFileName(MODName); Info.ModulePath := ExtractFilePath(MODName); L.Add(Info); end; end; end; finally CloseHandle(PH); end; end else begin m_hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID); if (m_hSnapshot = INVALID_HANDLE_VALUE) then exit; try FillChar(me, sizeof(me), 0); me.dwSize := sizeof(me); bOK := Module32First(m_hSnapshot, me); while bOk do begin Info := TModuleInformation.Create; Info.hModule := me.hModule; Info.ModuleName := StrPas(PChar(@me.szModule)); Info.ModulePath := ExtractFilePath(StrPas(PChar(@me.szExePath))); L.Add(Info); bOK := Module32Next(m_hSnapshot, me); end; finally CloseHandle(m_hSnapshot); end; end; end; const PsApiDll = 'psapi.dll'; const PsApiDllHandle: THandle = 0; KernelHandle : THandle = 0; Type TProcessBasicInformation = packed record ExitStatus: DWORD; PebBaseAddress: Pointer; AffinityMask: DWORD; BasePriority: DWORD; UniqueProcessId: LongInt; InheritedFromUniqueProcessId: DWORD; end; PProcessBasicInformation = ^TProcessBasicInformation; TNtQueryInformationProcess = function(hProcess: THandle; ProcessInformationClass: Integer; var ProcessInformation; ProcessInformationLength: Integer; var ReturnLength: Integer): Integer; stdcall; TRtlNtStatusToDosError = function (p1: DWORD):DWORD; stdcall; TNtQuerySystemInformation = function (p1, p2, p3, p4: DWORD):DWORD; stdcall; var NtQueryInformationProcess: TNtQueryInformationProcess; RtlNtStatusToDosError: TRtlNtStatusToDosError; NtQuerySystemInformation: TNtQuerySystemInformation; function GetProcessModuleQueryInfoNT4( hProcess: THandle; hModule :HMODULE; lpBuffer: Pointer ): BOOL; stdcall; type TLocalVars = packed record PBI: TProcessBasicInformation; DW1, DW2: DWORD; end; const arg_hProcess = $08; arg_hModule = $0C; arg_lpBuffer = $10; cLocalVarsSize = SizeOf(TLocalVars); cProcessBasicInformationSize = sizeOf(TProcessBasicInformation); asm add esp, -cLocalVarsSize push ebx lea eax, [ebp-cLocalVarsSize].TLocalVars.PBI // = PProcessBasicInformation push esi push edi // NtQueryInformationProcess(hProcess, 0{Class}, var_20{Buff}, $18{BufSize}, 0{ReturnLen}) push 0 // ReturnLength mov esi, [ebp+arg_hProcess] // hProcess push cProcessBasicInformationSize push eax // PProcessBasicInformation push 0 // ProcessInformationClass push esi // hProcess call dword ptr [NtQueryInformationProcess] test eax, eax jge @@NTQIP@TRUE push eax call dword ptr [RtlNtStatusToDosError] push eax jmp @@RET@FALSE@ERROR @@NTQIP@TRUE: cmp dword ptr [ebp+arg_hModule], 0 mov edi, [ebp-cLocalVarsSize].TLocalVars.PBI.TProcessBasicInformation.PebBaseAddress jnz @@NZMEM // ReadProcessMemory push 0 // lpNumberOfBytesRead = nil lea eax, [ebp+arg_hModule] push 4 // Size lea ecx, [edi+arg_hProcess] push eax // Buffer push ecx // lpBaseAddress push esi // hProcess call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE @@NZMEM: // ReadProcessMemory push 0 // lpNumberOfBytesRead = nil lea eax, [ebp-cLocalVarsSize].TLocalVars.DW1 push 4 // Size add edi, $0C // + 14 push eax // Buffer push edi // lpBaseAddress push esi // hProcess call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE mov edi, [ebp-cLocalVarsSize].TLocalVars.DW1 // ReadProcessMemory push 0 // lpNumberOfBytesRead = nil add edi, $14 // + 20 push 4 // Size lea eax, [ebp-cLocalVarsSize].TLocalVars.DW2 push eax // Buffer push edi // lpBaseAddress push esi // hProcess call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE cmp [ebp-cLocalVarsSize].TLocalVars.DW2, edi jz @@RET@FALSE@ERROR6 mov ebx, [ebp+arg_lpBuffer] @@LOOP: // ReadProcessMemory mov eax, [ebp-cLocalVarsSize].TLocalVars.DW2 push 0 // lpNumberOfBytesRead = nil sub eax, $08 push $48 // Size = 72 push ebx // Buffer push eax // lpBaseAddress push esi // hProcess call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE mov eax, [ebp+arg_hModule] cmp [ebx+18h], eax jz @@RET@TRUE mov eax, [ebx+arg_hProcess] mov [ebp-cLocalVarsSize].TLocalVars.DW2, eax cmp eax, edi jnz @@LOOP @@RET@FALSE@ERROR6: push $06 @@RET@FALSE@ERROR: call Windows.SetLastError @@RET@FALSE: xor eax, eax @@RET@00: pop edi pop esi pop ebx mov esp, ebp jmp @@RET @@RET@TRUE: mov eax, 1 jmp @@RET@00 @@RET: end; function GetModuleFileNameExWNT4(hProcess: THandle; hModule: HMODULE; lpFilename: PWideChar; nSize: DWORD): DWORD stdcall; assembler; const arg_hProcess = $08; arg_hModule = $0C; arg_lpFilename = $10; arg_nSize = $14; var_Buffer = -$4C; var_28 = -$28; var_lpBaseAddress = -$24; asm sub esp, 4Ch // GetProcessModuleQueryInfoNT4 lea eax, [ebp+var_Buffer] push eax // Buffer address push dword ptr [ebp+arg_hModule] push dword ptr [ebp+arg_hProcess] // hProcess call GetProcessModuleQueryInfoNT4 test eax, eax jz @@RET@02 mov eax, dword ptr [ebp+arg_nSize] push esi db $0F,$B7,$75,$D8 // movzx esi, [ebp+var_28] add eax, eax inc esi inc esi cmp eax, esi jb @@RET@01 @@LOOP: // ReadProcessMemory push 0 // lpNumberOfBytesRead = nil push esi // ??? ProcesInformationSize ??? push dword ptr [ebp+arg_lpFilename] // lpBuffer push dword ptr [ebp+var_lpBaseAddress] // lpBaseAddress push dword ptr [ebp+arg_hProcess] // hProcess call Windows.ReadProcessMemory test eax, eax jz @@RET@03 db $0F,$B7,$45,$D8 // movzx eax, [ebp+var_28] inc eax inc eax cmp esi, eax jnz @@RET@04 dec esi dec esi @@RET@04: mov eax, esi shr eax, 1 @@RET@03: pop esi @@RET@02: leave ret 10h @@RET@01: mov esi, eax jmp @@LOOP end; function GetModuleFileNameExANT4(hProcess: THandle; hModule: HMODULE; lpFilename: PAnsiChar; nSize: DWORD): DWORD stdcall; var Buff: String; begin Result := 0; if (hProcess=0)or(lpFilename=nil)or(nSize<=0) then exit; SetLength(Buff, nSize*2); Result := GetModuleFileNameExWNT4(hProcess, hModule, PWideChar(PChar(Buff)), nSize*2-2); if Result >0 then begin Result := Windows.WideCharToMultiByte(0,0, PWideChar(PChar(Buff)), Result, lpFilename, Result*2, nil, nil); if Result>0 then PChar(dword(lpFilename)+Result)^:=#0 else lpFilename^ := #0; end else lpFilename^ := #0; if Result > 0 then dec(Result); end; function EnumProcessesNT4(lpidProcess: LPDWORD; cb: DWORD; var cbNeeded: DWORD): BOOL stdcall; begin Result := False; if @NtQueryInformationProcess<>nil then asm mov eax, fs:0 push $0FFFFFFFF push $731B3448 push $731B2E38 push eax mov fs:0, esp add esp, -$14 push ebx push esi push edi mov esi, $8000 xor edi, edi mov [ebp-$18], esp @@LOOP@NTQSI: push esi push edi call Windows.LocalAlloc mov [ebp-$1C], eax cmp eax, edi jz @@RET@FALSE push edi push esi push eax push 5 call dword ptr [NtQuerySystemInformation] cmp eax, $0C0000004 jnz @@NTQSI@FINISH push dword ptr [ebp-$1C] call dword ptr LocalFree add esi, $8000 jmp @@LOOP@NTQSI @@NTQSI@FINISH: test eax, eax jge @@NTQSI@TRUE push eax call dword ptr [RtlNtStatusToDosError] push eax call Windows.SetLastError jmp @@RET@FALSE @@NTQSI@TRUE: xor esi, esi mov edx, [ebp+$0C] shr edx, 2 xor edi, edi mov ecx, [ebp+$08] @@LOOP: mov eax, [ebp-$1C] add eax, esi cmp edi, edx jnb @@CHECK2 mov dword ptr [ebp-4], 0 mov ebx, [eax+$44] mov [ecx+edi*4], ebx inc edi mov dword ptr [ebp-4], $0FFFFFFFF @@CHECK2: mov eax, [eax] add esi, eax test eax, eax jnz @@LOOP mov esi, 1 mov [ebp-4], esi lea ecx, ds:0[edi*4] mov eax, [ebp+$10] mov [eax], ecx mov dword ptr [ebp-4], $0FFFFFFFF push dword ptr [ebp-$1C] call Windows.LocalFree mov eax, esi jmp @@RET @@RET@FALSE: xor eax, eax @@RET: mov Result, eax mov ecx, [ebp-$10] pop edi mov fs:0, ecx pop esi pop ebx mov esp, ebp push ecx end; end; function EnumProcessModulesNT4(hProcess: THandle; lphModule: LPDWORD; cb: DWORD; var lpcbNeeded: DWORD): BOOL stdcall; begin Result := False; if @NtQueryInformationProcess<>nil then asm mov eax, fs:0 push $0FFFFFFFF push $731B3178 push $731B2E38 push eax mov fs:0, esp add esp, -$78 lea eax, [ebp-$40] push ebx push esi push edi mov [ebp-$18], esp push 0 push 18h push eax push 0 push dword ptr [ebp+$08] call dword ptr [NtQueryInformationProcess] test eax, eax jge @@NTQIP@END push eax call dword ptr [RtlNtStatusToDosError] push eax call Windows.SetLastError jmp @@RET@FALSE @@NTQIP@END: push 0 lea eax, [ebp-$28] push 4 push eax mov eax, [ebp-$3C] add eax, 0Ch push eax push dword ptr [ebp+$08] call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE mov esi, [ebp-$28] push 0 add esi, 14h push 4 lea eax, [ebp-$1C] push eax push esi push dword ptr [ebp+$08] call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE mov eax, [ebp+$10] xor edi, edi shr eax, 2 cmp esi, [ebp-$1C] mov [ebp-$24], eax jz @@RPM@END mov ebx, [ebp+$0C] @@LOOP: mov eax, [ebp-$1C] push 0 sub eax, 8 push 48h lea ecx, [ebp-$88] push ecx push eax push dword ptr [ebp+$08] call Windows.ReadProcessMemory test eax, eax jz @@RET@FALSE cmp edi, [ebp-$24] jnb @@CHECK mov dword ptr [ebp-4], 0 mov eax, [ebp-$70] mov [ebx], eax mov dword ptr [ebp-4], $0FFFFFFFF @@CHECK: add ebx, 4 inc edi mov eax, [ebp-$80] mov [ebp-$1C], eax cmp esi, eax jnz @@LOOP @@RPM@END: mov eax, 1 mov [ebp-4], eax lea edx, ds:0[edi*4] mov ecx, [ebp+$14] mov [ecx], edx mov dword ptr [ebp-4], $0FFFFFFFF jmp @@RET @@RET@FALSE: xor eax, eax @@RET: mov Result, eax mov ecx, [ebp-$10] pop edi mov fs:0, ecx pop esi pop ebx mov esp, ebp push ecx end; end; function _LoadNTAPI:Boolean; var hNTDLL: HMODULE; begin Result := False; hNTDLL := LoadLibrary('NTDLL.DLL'); if hNTDLL=0 then exit; try NtQueryInformationProcess := GetProcAddress(hNTDLL, 'NtQueryInformationProcess'); if @NtQueryInformationProcess=nil then exit; RtlNtStatusToDosError := GetProcAddress(hNTDLL, 'RtlNtStatusToDosError'); if @RtlNtStatusToDosError=nil then exit; NtQuerySystemInformation := GetProcAddress(hNTDLL, 'NtQuerySystemInformation'); if @NtQuerySystemInformation=nil then exit; Result := True; finally FreeLibrary(hNTDLL); if not Result then begin NtQueryInformationProcess := nil; RtlNtStatusToDosError := nil; NtQuerySystemInformation := nil; end; end; end; function GetProcessMemoryInfoNT4(hProcess:THandle; ppsmemCounters:TProcessMemoryCounters; cb : DWORD ) : BOOL; stdcall; begin Result := False; end; initialization if IsUsePSAPI then begin PsApiDllHandle := LoadLibrary(PsAPIDll); if PsApiDllHandle <> 0 then begin EnumProcesses := EnumProcessesProc(GetProcAddress(PsApiDllHandle, 'EnumProcesses')); EnumProcessModules := EnumProcessModulesProc(GetProcAddress(PsApiDllHandle, 'EnumProcessModules')); GetModuleFileNameEx := GetModuleFileNameExProc(GetProcAddress(PsApiDllHandle, 'GetModuleFileNameExA')); GetProcessMemoryInfo := GetProcessMemoryInfoProc(GetProcAddress(PsApiDllHandle, 'GetProcessMemoryInfo')); if (@EnumProcesses <> nil) and (@EnumProcessModules <> nil) and (@GetModuleFileNameEx <> nil) and (@GetProcessMemoryInfo <> nil) then ApiLoaded := true; end else if _LoadNTAPI() then begin EnumProcesses := @EnumProcessesNT4; EnumProcessModules := @EnumProcessModulesNT4; GetModuleFileNameEx := @GetModuleFileNameExANT4; GetProcessMemoryInfo := @GetProcessMemoryInfoNT4; ApiLoaded := true; end; end else begin KernelHandle := GetModuleHandle('kernel32.dll'); if KernelHandle <> 0 then begin CreateToolHelp32Snapshot := CreateToolhelp32SnapshotProc(GetProcAddress(KernelHandle, 'CreateToolhelp32Snapshot')); Process32First := Process32FirstProc(GetProcAddress(KernelHandle, 'Process32First')); Process32Next := Process32NextProc(GetProcAddress(KernelHandle, 'Process32Next')); if (@Process32First <> nil) and (@Process32Next <> nil) and (@CreateToolhelp32Snapshot <> nil) then APILoaded := true; end; end; finalization if PsApiDllHandle <> 0 then FreeLibrary(PsApiDllHandle); end.
unit Diction_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Diction/Forms/Diction_Form.pas" // Начат: 01.09.2009 13:14 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMFinalForm::Class>> F1 Встроенные продукты::Diction::View::Diction::Diction$FP::Diction // // Толковый словарь // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Common_FormDefinitions_Controls {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , PrimDictionOptions_Form, vtPanel {$If defined(Nemesis)} , nscContextFilter {$IfEnd} //Nemesis {$If defined(Nemesis)} , nscTreeView {$IfEnd} //Nemesis , Classes {a}, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a}, vcmInterfaces {a}, vcmEntityForm {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TenDiction = {final form} class(TvcmEntityFormRef, DictionFormDef) {* Толковый словарь } Entities : TvcmEntities; end;//TenDiction TDictionForm = TenDiction; {$IfEnd} //not Admin AND not Monitorings implementation {$R *.DFM} {$If not defined(Admin) AND not defined(Monitorings)} uses SysUtils {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type Tkw_Form_Diction = class(TtfwControlString) {* Слово словаря для идентификатора формы Diction ---- *Пример использования*: [code] 'aControl' форма::Diction TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_Diction // start class Tkw_Form_Diction {$If not defined(NoScripts)} function Tkw_Form_Diction.GetString: AnsiString; {-} begin Result := 'enDiction'; end;//Tkw_Form_Diction.GetString {$IfEnd} //not NoScripts type Tkw_Diction_BackgroundPanel_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола BackgroundPanel формы Diction } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_Diction_BackgroundPanel_ControlInstance // start class Tkw_Diction_BackgroundPanel_ControlInstance {$If not defined(NoScripts)} procedure Tkw_Diction_BackgroundPanel_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TenDiction).BackgroundPanel); end;//Tkw_Diction_BackgroundPanel_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_Diction_ContextFilter_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола ContextFilter формы Diction } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_Diction_ContextFilter_ControlInstance // start class Tkw_Diction_ContextFilter_ControlInstance {$If not defined(NoScripts)} procedure Tkw_Diction_ContextFilter_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TenDiction).ContextFilter); end;//Tkw_Diction_ContextFilter_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_Diction_WordsTree_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола WordsTree формы Diction } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_Diction_WordsTree_ControlInstance // start class Tkw_Diction_WordsTree_ControlInstance {$If not defined(NoScripts)} procedure Tkw_Diction_WordsTree_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TenDiction).WordsTree); end;//Tkw_Diction_WordsTree_ControlInstance.DoDoIt {$IfEnd} //not NoScripts {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация фабрики формы Diction fm_enDiction.SetFactory(TenDiction.Make); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Form_Diction Tkw_Form_Diction.Register('форма::Diction', TenDiction); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Diction_BackgroundPanel_ControlInstance TtfwScriptEngine.GlobalAddWord('.TenDiction.BackgroundPanel', Tkw_Diction_BackgroundPanel_ControlInstance); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Diction_ContextFilter_ControlInstance TtfwScriptEngine.GlobalAddWord('.TenDiction.ContextFilter', Tkw_Diction_ContextFilter_ControlInstance); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Diction_WordsTree_ControlInstance TtfwScriptEngine.GlobalAddWord('.TenDiction.WordsTree', Tkw_Diction_WordsTree_ControlInstance); {$IfEnd} //not Admin AND not Monitorings end.
unit SafeDLLPath; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. To provide protection against "DLL preloading" attacks, this unit calls SetDllDirectory('') to prevent LoadLibrary from searching the current directory for DLLs. (Has no effect on Windows versions prior to XP SP1.) It also calls SetSearchPathMode to enable "safe search mode", which causes SearchPath, and callers of SearchPath such as CreateProcess, to search the current directory after the system directories (rather than before). SetSearchPathMode is available in Windows 7, and on previous versions that have the KB959426 update installed. Finally, it calls SetProcessDEPPolicy (where available) to enable DEP for the lifetime of the process. (This has nothing to do with search paths; it's just convenient to put the call here.) This unit should be listed at the top of the program's "uses" clause to ensure that it runs prior to any LoadLibrary calls that other units might make during their initialization. (The System unit will always initialize first, though.) $jrsoftware: issrc/Projects/SafeDLLPath.pas,v 1.3 2010/09/21 03:32:28 jr Exp $ } interface implementation uses Windows; const BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE = $00000001; BASE_SEARCH_PATH_PERMANENT = $00008000; PROCESS_DEP_ENABLE = $00000001; var KernelModule: HMODULE; SetDllDirectoryFunc: function(lpPathName: PWideChar): BOOL; stdcall; SetSearchPathModeFunc: function(Flags: DWORD): BOOL; stdcall; SetProcessDEPPolicyFunc: function(dwFlags: DWORD): BOOL; stdcall; initialization KernelModule := GetModuleHandle(kernel32); SetDllDirectoryFunc := GetProcAddress(KernelModule, PAnsiChar('SetDllDirectoryW')); if Assigned(SetDllDirectoryFunc) then SetDllDirectoryFunc(''); SetSearchPathModeFunc := GetProcAddress(KernelModule, PAnsiChar('SetSearchPathMode')); if Assigned(SetSearchPathModeFunc) then SetSearchPathModeFunc(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE or BASE_SEARCH_PATH_PERMANENT); SetProcessDEPPolicyFunc := GetProcAddress(KernelModule, PAnsiChar('SetProcessDEPPolicy')); if Assigned(SetProcessDEPPolicyFunc) then SetProcessDEPPolicyFunc(PROCESS_DEP_ENABLE); end.
unit HGM.Common.DateUtils; interface uses System.SysUtils, Vcl.Graphics, Vcl.Dialogs, System.DateUtils; type TDatePeriod = record private function GetDaysBetween: Integer; public DateBegin:TDateTime; DateEnd:TDateTime; property DaysBetween:Integer read GetDaysBetween; procedure SetValue(ADateBegin, ADateEnd:TDateTime); class function Create(DateBegin, DateEnd:TDateTime):TDatePeriod; static; end; implementation { TDatePeriod } class function TDatePeriod.Create(DateBegin, DateEnd: TDateTime): TDatePeriod; begin Result.DateBegin:=DateBegin; Result.DateEnd:=DateEnd; end; function TDatePeriod.GetDaysBetween: Integer; begin Result:=System.DateUtils.DaysBetween(DateBegin, DateEnd); end; procedure TDatePeriod.SetValue(ADateBegin, ADateEnd: TDateTime); begin DateBegin:=ADateBegin; DateEnd:=ADateEnd; end; end.
unit StepIntf; interface uses ValidationRuleIntf, StepParamsIntf; type IStep = interface(IInterface) ['{E1A03301-32F2-4A7B-886D-2B4188982A5B}'] function GetDescricao: string; function GetMetodoDeTeste: string; function GetParams: IStepParams; function GetParamsRegex: string; function GetValidationRule: IValidationRule; procedure SetDescricao(const Value: string); procedure SetParamsRegex(const Value: string); property Descricao: string read GetDescricao write SetDescricao; property MetodoDeTeste: string read GetMetodoDeTeste; property ValidationRule: IValidationRule read GetValidationRule; property Params: IStepParams read GetParams; property ParamsRegex: string read GetParamsRegex write SetParamsRegex; end; implementation end.
unit View.ListaRoteirosLivres; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, System.Actions, Vcl.ActnList, cxTextEdit, cxMaskEdit, cxButtonEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxCheckBox, cxImageComboBox, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, DAO.Conexao, FireDAC.Comp.Client, FireDAC.Comp.DataSet, cxFilterControl, cxDBFilterControl, Control.AbrangenciaExpressas; type Tview_ListaRorteirosLivres = class(TForm) dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; labelTitle: TcxLabel; dxLayoutItem1: TdxLayoutItem; dxLayoutGroup1: TdxLayoutGroup; parametro: TcxButtonEdit; dxLayoutItem2: TdxLayoutItem; actionListFiltro: TActionList; actionFiltrar: TAction; actionLimpar: TAction; gridCEPDBTableView1: TcxGridDBTableView; gridCEPLevel1: TcxGridLevel; gridCEP: TcxGrid; dxLayoutItem3: TdxLayoutItem; dsFiltro: TDataSource; gridCEPDBTableView1num_cep_inicial: TcxGridDBColumn; gridCEPDBTableView1num_cep_final: TcxGridDBColumn; gridCEPDBTableView1des_prazo: TcxGridDBColumn; gridCEPDBTableView1cod_tipo: TcxGridDBColumn; gridCEPDBTableView1des_logradouro: TcxGridDBColumn; gridCEPDBTableView1des_bairro: TcxGridDBColumn; dxLayoutGroup2: TdxLayoutGroup; actionOK: TAction; actionCancelar: TAction; cxButton1: TcxButton; dxLayoutItem4: TdxLayoutItem; cxButton2: TcxButton; dxLayoutItem5: TdxLayoutItem; actionMarcarSelecionados: TAction; actionDesmarcarTudo: TAction; PopupMenu: TPopupMenu; MarcarTudo1: TMenuItem; DesmarcarTudo1: TMenuItem; gridCEPDBTableView1id_roteiro: TcxGridDBColumn; actionConfigurarFiltro: TAction; dxLayoutGroup3: TdxLayoutGroup; dxLayoutGroup4: TdxLayoutGroup; dxLayoutGroup5: TdxLayoutGroup; filterRoteiro: TcxDBFilterControl; dxLayoutItem6: TdxLayoutItem; actionAplicarFiltro: TAction; actionCancelarFiltro: TAction; cxButton3: TcxButton; dxLayoutItem7: TdxLayoutItem; cxButton4: TcxButton; dxLayoutItem8: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; procedure FormShow(Sender: TObject); procedure actionOKExecute(Sender: TObject); procedure actionCancelarExecute(Sender: TObject); procedure actionFiltrarExecute(Sender: TObject); procedure actionLimparExecute(Sender: TObject); procedure gridCEPDBTableView1NavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); procedure gridCEPDBTableView1id_roteiroHeaderClick(Sender: TObject); procedure actionMarcarSelecionadosExecute(Sender: TObject); procedure actionDesmarcarTudoExecute(Sender: TObject); procedure actionAplicarFiltroExecute(Sender: TObject); procedure actionConfigurarFiltroExecute(Sender: TObject); procedure actionCancelarFiltroExecute(Sender: TObject); private { Private declarations } procedure StartForm; procedure CloseForm; procedure ClearFilter; procedure ExportData; procedure PesquisaCEP(sFiltro: String); procedure CheckAll; procedure UnCheckAll; procedure SaveSelection; function FormulaFiltro(sTexto: String): String; public { Public declarations } sSQL : String; sWhere: String; FCodigoRoteiro: String; FDescricaoRoteiro: String; end; var view_ListaRorteirosLivres: Tview_ListaRorteirosLivres; FConexao : TConexao; implementation {$R *.dfm} uses Data.SisGeF, Control.RoteirosExpressas, Common.Utils; { Tview_ListaRorteirosLivres } procedure Tview_ListaRorteirosLivres.actionAplicarFiltroExecute(Sender: TObject); begin dxLayoutGroup4.MakeVisible; PesquisaCEP(filterRoteiro.FilterText); end; procedure Tview_ListaRorteirosLivres.actionCancelarExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure Tview_ListaRorteirosLivres.actionCancelarFiltroExecute(Sender: TObject); begin filterRoteiro.Clear; dxLayoutGroup4.MakeVisible; end; procedure Tview_ListaRorteirosLivres.actionConfigurarFiltroExecute(Sender: TObject); begin dxLayoutGroup5.MakeVisible; end; procedure Tview_ListaRorteirosLivres.actionDesmarcarTudoExecute(Sender: TObject); begin UnCheckAll; end; procedure Tview_ListaRorteirosLivres.actionFiltrarExecute(Sender: TObject); begin PesquisaCEP(FormulaFiltro(parametro.Text)); end; procedure Tview_ListaRorteirosLivres.actionLimparExecute(Sender: TObject); begin ClearFilter; end; procedure Tview_ListaRorteirosLivres.actionMarcarSelecionadosExecute(Sender: TObject); begin CheckAll; end; procedure Tview_ListaRorteirosLivres.actionOKExecute(Sender: TObject); begin SaveSelection; ModalResult := mrOk; end; procedure Tview_ListaRorteirosLivres.CheckAll; begin gridCEPDBTableView1.Controller.SelectAllRecords; end; procedure Tview_ListaRorteirosLivres.ClearFilter; begin parametro.Clear; Data_Sisgef.mtbRoteirosLivres.Active := False; end; procedure Tview_ListaRorteirosLivres.CloseForm; begin Data_Sisgef.mtbRoteirosLivres.Active := False; FConexao.Free; end; procedure Tview_ListaRorteirosLivres.ExportData; var fnUtil : Common.Utils.TUtils; sMensagem: String; begin try fnUtil := Common.Utils.TUtils.Create; if Data_Sisgef.mtbRoteirosExpressas.IsEmpty then Exit; if Data_Sisgef.SaveDialog.Execute() then begin if FileExists(Data_Sisgef.SaveDialog.FileName) then begin sMensagem := 'Arquivo ' + Data_Sisgef.SaveDialog.FileName + ' já existe! Sobrepor ?'; if Application.MessageBox(PChar(sMensagem), 'Sobrepor', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit end; fnUtil.ExportarDados(gridCEP,Data_Sisgef.SaveDialog.FileName); end; finally fnUtil.Free; end; end; procedure Tview_ListaRorteirosLivres.FormShow(Sender: TObject); begin StartForm; end; function Tview_ListaRorteirosLivres.FormulaFiltro(sTexto: String): String; var sMensagem: String; sFiltro: String; begin Result := ''; sFiltro := ''; if sTexto = '' then begin sMensagem := 'O campo de texto a pesquisar não foi preenchido!. ' + 'Caso deseje visualizar todos os CEPs disponíveis clique OK, porém, esse processo pode ser lento.'; if Application.MessageBox(PChar(sMensagem), 'Atenção!', MB_OKCANCEL + MB_ICONWARNING) = IDCANCEL then begin sFiltro := 'NONE'; end; end else begin sFiltro := 'num_cep_inicial like ' + '"%' + sTexto + '%"' + ' or num_cep_final like ' + '"%' + sTexto + '%"' + ' or des_logradouro like ' + '"%' + sTexto + '%"' + ' or des_bairro like ' + '"%' + sTexto + '%"'; end; Result := sFiltro; end; procedure Tview_ListaRorteirosLivres.gridCEPDBTableView1id_roteiroHeaderClick(Sender: TObject); begin if Application.MessageBox('Confirma selecionar todos os registros ?', 'Selecionar Todos', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit; CheckAll; end; procedure Tview_ListaRorteirosLivres.gridCEPDBTableView1NavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); begin case AButtonIndex of 16 : ExportData; 17 : CheckAll; 18 : UnCheckAll; end; end; procedure Tview_ListaRorteirosLivres.PesquisaCEP(sFiltro: String); var Abrangencia : TAbrangenciaExpressasControl; aParam : Array of variant; begin try Abrangencia := TAbrangenciaExpressasControl.Create; Data_Sisgef.mtbRoteirosLivres.Active := False; SetLength(aParam, 2); if sFiltro = 'NONE' then aParam := ['FILTRO',''] else aParam := ['FILTRO',sFiltro]; if Abrangencia.Search(aParam) then begin Data_Sisgef.mtbRoteirosLivres.Active := True; Data_Sisgef.mtbRoteirosLivres.CopyDataSet(Abrangencia.Abrangencia.Query); gridCEP.SetFocus; end else begin Application.MessageBox('Nenhum registro encontrado!', 'Atenção', MB_OK + MB_ICONWARNING); end; finally Abrangencia.Abrangencia.Query.Active := False; Abrangencia.Abrangencia.Query.Connection.Connected := False; Abrangencia.Free; end; end; procedure Tview_ListaRorteirosLivres.SaveSelection; var i, iId: Integer; sCEP, sTipo, sCliente, sQuery: String; begin if Data_Sisgef.mtbRoteirosLivres.IsEmpty then Exit; if not Data_Sisgef.mtbRoteirosExpressas.Active then Data_Sisgef.mtbRoteirosExpressas.Active := True; Screen.Cursor := crHourGlass; Data_Sisgef.mtbRoteirosLivres.First; for i := 0 to Pred(gridCEPDBTableView1.Controller.SelectedRowCount) do begin iId := StrToIntDef(gridCEPDBTableView1.Controller.SelectedRows[i].DisplayTexts[0], 0); if Data_Sisgef.mtbRoteirosLivres.Locate('id_registro',iID,[]) then begin sCEP := Data_Sisgef.mtbRoteirosLivres.FieldByName('num_cep').AsString; sTipo := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_tipo').AsString; sCliente := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_cliente').AsString; sQuery := 'num_cep_inicial = ' + QuotedStr(sCEP) + ' and cod_tipo = ' + sTipo + ' and cod_cliente = ' + sCliente; if not Data_Sisgef.mtbRoteirosExpressas.LocateEx(sQuery,[]) then begin Data_Sisgef.mtbRoteirosExpressas.Insert; Data_Sisgef.mtbRoteirosExpressasdom_check.AsInteger := 1; end else begin Data_Sisgef.mtbRoteirosExpressas.Edit; Data_Sisgef.mtbRoteirosExpressasdom_check.AsInteger := 2; end; Data_Sisgef.mtbRoteirosExpressasid_roteiro.AsInteger := Data_Sisgef.mtbRoteirosLivres.FieldByName('id_registro').AsInteger;; Data_Sisgef.mtbRoteirosExpressascod_ccep5.AsString := FCodigoRoteiro; Data_Sisgef.mtbRoteirosExpressasdes_roteiro.AsString := FDescricaoRoteiro; Data_Sisgef.mtbRoteirosExpressasnum_cep_inicial.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('num_cep').AsString; Data_Sisgef.mtbRoteirosExpressasnum_cep_final.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('num_cep_final').AsString; Data_Sisgef.mtbRoteirosExpressasdes_prazo.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('des_prazo').AsString; Data_Sisgef.mtbRoteirosExpressasdom_zona.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('dom_zona').AsString;; Data_Sisgef.mtbRoteirosExpressascod_tipo.AsInteger := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_tipo').AsInteger; Data_Sisgef.mtbRoteirosExpressasdes_logradouro.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('des_logradouro').AsString; Data_Sisgef.mtbRoteirosExpressasdes_bairro.AsString := Data_Sisgef.mtbRoteirosLivres.FieldByName('des_bairro').AsString; Data_Sisgef.mtbRoteirosExpressascod_cliente.AsInteger := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_cliente').AsInteger; Data_Sisgef.mtbRoteirosExpressascod_leve.AsInteger := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_leve').AsInteger; Data_Sisgef.mtbRoteirosExpressascod_pesado.AsInteger := Data_Sisgef.mtbRoteirosLivres.FieldByName('cod_pesado').AsInteger; Data_Sisgef.mtbRoteirosExpressas.Post; end; end; Data_Sisgef.mtbRoteirosLivres.Active := False; filterRoteiro.Clear; Screen.Cursor := crDefault; end; procedure Tview_ListaRorteirosLivres.StartForm; begin labelTitle.Caption := Self.Caption; FConexao := TConexao.Create; Self.Top := Screen.WorkAreaTop; Self.Left := Screen.WorkAreaLeft; Self.Width := Screen.WorkAreaWidth; Self.Height := Screen.WorkAreaHeight; end; procedure Tview_ListaRorteirosLivres.UnCheckAll; begin gridCEPDBTableView1.Controller.ClearSelection; end; end.
unit upd1771; interface uses {$IFDEF WINDOWS}windows,{$else}main_engine,{$ENDIF}timer_engine, sound_engine,vars_hide; const MAX_PACKET_SIZE=$8000; type tack_handler=procedure(state:boolean); upd1771_chip=class(snd_chip_class) constructor create(clock:integer;amp:single); destructor free; public procedure reset; function read:byte; procedure write(valor:byte); procedure change_calls(ack_handler:tack_handler); procedure pcm_write(state:byte); procedure update; function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); private clock,index:dword; nw_tpos:byte; timer,expected_bytes,pc3,t_tpos,state:byte; t_ppos:word; n_value:array[0..2] of byte; n_ppos,n_period:array[0..2] of dword; packet:array[0..(MAX_PACKET_SIZE-1)] of byte; t_volume,t_timbre,t_offset,nw_timbre,nw_volume:byte; nw_ppos,nw_period:dword; n_volume:array[0..2] of word; t_period:word; ack_handler:tack_handler; salida:smallint; end; var upd1771_0:upd1771_chip; implementation const WAVEFORMS:array[0..7,0..31] of shortint=( ( 0, 0,-123,-123, -61, -23, 125, 107, 94, 83,-128,-128,-128, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,-128,-128,-128, 0, 0, 0, 0, 0, 0), ( 37, 16, 32, -21, 32, 52, 4, 4, 33, 18, 60, 56, 0, 8, 5, 16, 65, 19, 69, 16, -2, 19, 37, 16, 97, 19, 0, 87, 127, -3, 1, 2), ( 0, 8, 1, 52, 4, 0, 0, 77, 81,-109, 47, 97, -83,-109, 38, 97, 0, 52, 4, 0, 1, 4, 1, 22, 2, -46, 33, 97, 0, 8, -85, -99), ( 47, 97, 40, 97, -3, 25, 64, 17, 0, 52, 12, 5, 12, 5, 12, 5, 12, 5, 12, 5, 8, 4,-114, 19, 0, 52,-122, 21, 2, 5, 0, 8), ( -52, -96,-118,-128,-111, -74, -37, -5, 31, 62, 89, 112, 127, 125, 115, 93, 57, 23, 0, -16, -8, 15, 37, 54, 65, 70, 62, 54, 43, 31, 19, 0), ( -81,-128, -61, 13, 65, 93, 127, 47, 41, 44, 52, 55, 56, 58, 58, 34, 0, 68, 76, 72, 61, 108, 55, 29, 32, 39, 43, 49, 50, 51, 51, 0), ( -21, -45, -67, -88,-105,-114,-122,-128,-123,-116,-103, -87, -70, -53, -28, -9, 22, 46, 67, 86, 102, 114, 123, 125, 127, 117, 104, 91, 72, 51, 28, 0), ( -78,-118,-128,-102, -54, -3, 40, 65, 84, 88, 84, 80, 82, 88, 94, 103, 110, 119, 122, 125, 122, 122, 121, 123, 125, 126, 127, 127, 125, 118, 82, 0)); NOISE_SIZE=255; noise_tbl:array[0..$ff] of byte=( $1c,$86,$8a,$8f,$98,$a1,$ad,$be,$d9,$8a,$66,$4d,$40,$33,$2b,$23, $1e,$8a,$90,$97,$a4,$ae,$b8,$d6,$ec,$e9,$69,$4a,$3e,$34,$2d,$27, $24,$24,$89,$8e,$93,$9c,$a5,$b0,$c1,$dd,$40,$36,$30,$29,$27,$24, $8b,$90,$96,$9e,$a7,$b3,$c4,$e1,$25,$21,$8a,$8f,$93,$9d,$a5,$b2, $c2,$dd,$dd,$98,$a2,$af,$bf,$d8,$fd,$65,$4a,$3c,$31,$2b,$24,$22, $1e,$87,$8c,$91,$9a,$a3,$af,$c0,$db,$be,$d9,$8c,$66,$4d,$40,$34, $2c,$24,$1f,$88,$90,$9a,$a4,$b2,$c2,$da,$ff,$67,$4d,$3d,$34,$2d, $26,$24,$20,$89,$8e,$93,$9c,$a5,$b1,$c2,$de,$c1,$da,$ff,$67,$4d, $3d,$33,$2d,$26,$24,$20,$89,$8e,$93,$9c,$a5,$b1,$c2,$dd,$a3,$b0, $c0,$d9,$fe,$66,$4b,$3c,$32,$2b,$24,$23,$1e,$88,$8d,$92,$9b,$a4, $b0,$c1,$dc,$ad,$be,$da,$22,$20,$1c,$85,$8a,$8f,$98,$a1,$ad,$be, $da,$20,$1b,$85,$8d,$97,$a1,$af,$bf,$d8,$fd,$64,$49,$3a,$30,$2a, $23,$21,$1d,$86,$8b,$91,$9a,$a2,$ae,$c0,$db,$33,$2b,$24,$1f,$88, $90,$9a,$a4,$b2,$c2,$da,$ff,$67,$4c,$3e,$33,$2d,$25,$24,$1f,$89, $8e,$93,$9c,$a5,$b1,$c2,$de,$85,$8e,$98,$a2,$b0,$c0,$d9,$fe,$64, $4b,$3b,$31,$2a,$23,$22,$1e,$88,$8c,$91,$9b,$a3,$af,$c1,$dc,$dc); STATE_SILENCE=0; STATE_NOISE=1; STATE_TONE=2; STATE_ADPCM=3; procedure ack_callback; begin upd1771_0.ack_handler(true); timers.enabled(upd1771_0.timer,false); end; procedure internal_update; var wlfsr_val:integer; res:array[0..2] of byte; f:byte; temp:integer; begin upd1771_0.salida:=0; case upd1771_0.state of STATE_TONE:begin temp:=WAVEFORMS[upd1771_0.t_timbre][upd1771_0.t_tpos]*upd1771_0.t_volume; if temp>16384 then upd1771_0.salida:=16384 else upd1771_0.salida:=temp; upd1771_0.t_ppos:=upd1771_0.t_ppos+1; if (upd1771_0.t_ppos>=upd1771_0.t_period) then begin upd1771_0.t_tpos:=upd1771_0.t_tpos+1; if (upd1771_0.t_tpos=32) then upd1771_0.t_tpos:=upd1771_0.t_offset; upd1771_0.t_ppos:=0; end; end; STATE_NOISE:begin //"wavetable-LFSR" component wlfsr_val:=noise_tbl[upd1771_0.nw_tpos]-127;//data too wide upd1771_0.nw_ppos:=upd1771_0.nw_ppos+1; if (upd1771_0.nw_ppos>=upd1771_0.nw_period) then begin upd1771_0.nw_tpos:=upd1771_0.nw_tpos+1; upd1771_0.nw_ppos:=0; end; //mix in each of the noise's 3 pulse components for f:=0 to 2 do begin res[f]:=upd1771_0.n_value[f]*127; upd1771_0.n_ppos[f]:=upd1771_0.n_ppos[f]+1; if (upd1771_0.n_ppos[f]>=upd1771_0.n_period[f]) then begin upd1771_0.n_ppos[f]:=0; upd1771_0.n_value[f]:=not(upd1771_0.n_value[f]); end; end; //not quite, but close. temp:=(wlfsr_val*upd1771_0.nw_volume) or (res[0]*upd1771_0.n_volume[0]) or (res[1]*upd1771_0.n_volume[1]) or (res[2]*upd1771_0.n_volume[2]); if temp>32767 then upd1771_0.salida:=32767 else upd1771_0.salida:=temp; end; end; end; constructor upd1771_chip.create(clock:integer;amp:single); begin self.clock:=clock; self.amp:=amp; self.tsample_num:=init_channel; self.timer:=timers.init(sound_status.cpu_num,512,ack_callback,nil,false,0); timers.init(sound_status.cpu_num,sound_status.cpu_clock/(self.clock/4),internal_update,nil,true,0); self.reset; end; destructor upd1771_chip.free; begin end; procedure upd1771_chip.change_calls(ack_handler:tack_handler); begin self.ack_handler:=ack_handler; end; procedure upd1771_chip.reset; var f:byte; begin self.index:=0; self.expected_bytes:=0; self.pc3:=0; self.t_tpos:=0; self.t_ppos:=0; self.state:=0; self.nw_tpos:=0; fillchar(n_value,3,0); for f:=0 to 2 do n_ppos[f]:=0; timers.enabled(self.timer,false); self.salida:=0; end; function upd1771_chip.read:byte; begin read:=$80; end; procedure upd1771_chip.write(valor:byte); begin self.ack_handler(false); if (index<MAX_PACKET_SIZE) then begin packet[index]:=valor; index:=index+1 end else exit; case packet[0] of 0:begin state:=STATE_SILENCE; index:=0; end; 1:if (index=10) then begin state:=STATE_NOISE; index:=0; nw_timbre:=(packet[1] and $e0) shr 5; nw_period:=(packet[2]+1) shl 7; nw_volume:=packet[3] and $1f; //very long clocked periods.. used for engine drones n_period[0]:=(packet[4]+1) shl 7; n_period[1]:=(packet[5]+1) shl 7; n_period[2]:=(packet[6]+1) shl 7; n_volume[0]:=packet[7] and $1f; n_volume[1]:=packet[8] and $1f; n_volume[2]:=packet[9] and $1f; end else timers.enabled(self.timer,true); 2:if (index=4) then begin t_timbre:=(packet[1] and $e0) shr 5; t_offset:=packet[1] and $1f; t_period:=packet[2]; //smaller periods don't all equal to 0x20 if (t_period<$20) then t_period:=$20; t_volume:=packet[3] and $1f; state:=STATE_TONE; index:=0; end else timers.enabled(self.timer,true); $1f:begin //6Khz(ish) DIGI playback //end capture if ((index>=2) and (packet[index-2]=$fe) and (packet[index-1]=0)) then begin //TODO play capture! index:=0; packet[0]:=0; state:=STATE_ADPCM; end else timers.enabled(self.timer,true); end; //garbage: wipe stack else begin state:=STATE_SILENCE; index:=0; end; end; end; procedure upd1771_chip.pcm_write(state:byte); begin //RESET upon HIGH if (state<>pc3) then begin index:=0; packet[0]:=0; end; pc3:=state; end; procedure upd1771_chip.update; begin tsample[self.tsample_num,sound_status.posicion_sonido]:=trunc(salida*amp); if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=trunc(salida*amp); end; function upd1771_chip.save_snapshot(data:pbyte):word; var temp:pbyte; buffer:array[0..64] of byte; size:word; begin temp:=data; copymemory(temp,@self.packet,MAX_PACKET_SIZE); inc(temp,MAX_PACKET_SIZE); copymemory(@buffer[0],@self.clock,4); copymemory(@buffer[4],@self.index,4); buffer[8]:=self.nw_tpos; buffer[9]:=self.expected_bytes; buffer[10]:=self.pc3; buffer[11]:=self.t_tpos; buffer[12]:=self.state; copymemory(@buffer[13],@self.t_ppos,2); copymemory(@buffer[15],@self.n_value,3); copymemory(@buffer[18],@self.n_ppos,4*3); copymemory(@buffer[30],@self.n_period,4*3); buffer[42]:=self.t_volume; buffer[43]:=self.t_timbre; buffer[44]:=self.t_offset; buffer[45]:=self.nw_timbre; buffer[46]:=self.nw_volume; copymemory(@buffer[47],@self.nw_ppos,4); copymemory(@buffer[51],@self.nw_period,4); copymemory(@buffer[55],@self.n_volume,2*3); copymemory(@buffer[61],@self.t_period,2); copymemory(@buffer[63],@self.salida,2); copymemory(temp,@buffer[0],65); save_snapshot:=size+65; end; procedure upd1771_chip.load_snapshot(data:pbyte); var temp:pbyte; buffer:array[0..64] of byte; begin temp:=data; copymemory(@self.packet,temp,MAX_PACKET_SIZE); inc(temp,MAX_PACKET_SIZE); copymemory(@buffer[0],temp,65); copymemory(@self.clock,@buffer[0],4); copymemory(@self.index,@buffer[4],4); self.nw_tpos:=buffer[8]; self.expected_bytes:=buffer[9]; self.pc3:=buffer[10]; self.t_tpos:=buffer[11]; self.state:=buffer[12]; copymemory(@self.t_ppos,@buffer[13],2); copymemory(@self.n_value,@buffer[15],3); copymemory(@self.n_ppos,@buffer[18],4*3); copymemory(@self.n_period,@buffer[30],4*3); self.t_volume:=buffer[42]; self.t_timbre:=buffer[43]; self.t_offset:=buffer[44]; self.nw_timbre:=buffer[45]; self.nw_volume:=buffer[46]; copymemory(@self.nw_ppos,@buffer[47],4); copymemory(@self.nw_period,@buffer[51],4); copymemory(@self.n_volume,@buffer[55],2*3); copymemory(@self.t_period,@buffer[61],2); copymemory(@self.salida,@buffer[63],2); end; end.
unit udmLctoBancarios; interface uses Windows, System.UITypes, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, LibGeral; type TdmLctoBancarios = class(TdmPadrao) qryLocalizacaoBANCO: TStringField; qryLocalizacaoAGENCIA: TStringField; qryLocalizacaoCONTA: TStringField; qryLocalizacaoDT_LANCAMENTO: TDateTimeField; qryLocalizacaoTIPO_DOCUMENTO: TStringField; qryLocalizacaoDOCUMENTO: TFloatField; qryLocalizacaoVL_DOCUMENTO: TFloatField; qryLocalizacaoDC: TStringField; qryLocalizacaoDESCRICAO: TStringField; qryLocalizacaoHISTORICO: TIntegerField; qryLocalizacaoCENTRO_CUSTO: TIntegerField; qryLocalizacaoCONTA_CREDITO: TStringField; qryLocalizacaoCONTA_DEBITO: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoID_TRANSF: TFloatField; qryLocalizacaoFIL_ORIGEM: TStringField; qryLocalizacaoFIL_DEBITO: TStringField; qryLocalizacaoNM_CENTROCUSTOS: TStringField; qryLocalizacaoNM_HISTORICO: TStringField; qryManutencaoBANCO: TStringField; qryManutencaoAGENCIA: TStringField; qryManutencaoCONTA: TStringField; qryManutencaoDT_LANCAMENTO: TDateTimeField; qryManutencaoTIPO_DOCUMENTO: TStringField; qryManutencaoDOCUMENTO: TFloatField; qryManutencaoVL_DOCUMENTO: TFloatField; qryManutencaoDC: TStringField; qryManutencaoDESCRICAO: TStringField; qryManutencaoHISTORICO: TIntegerField; qryManutencaoCENTRO_CUSTO: TIntegerField; qryManutencaoCONTA_CREDITO: TStringField; qryManutencaoCONTA_DEBITO: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoID_TRANSF: TFloatField; qryManutencaoFIL_ORIGEM: TStringField; qryManutencaoFIL_DEBITO: TStringField; qryManutencaoNM_CENTROCUSTOS: TStringField; qryManutencaoNM_HISTORICO: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FNro_Documento: Real; FAgencia: string; FFil_Debito: string; FConta: string; FBanco: string; FFil_Origem: string; FTpo_Documento: string; FDta_Lancamento: TDateTime; FDta_LancamentoI: TDateTime; FDta_LancamentoF: TDateTime; function GetSQL_DEFAULT: string; public function LocalizarLancamentosDia(DataSet: TDataSet = nil): Boolean; function LocalizarPorPeriodo(DataSet: TDataSet = nil): Boolean; overload; function LocalizarPorPeriodo(ADataInicial, ADataFinal: TDateTime; DataSet: TDataSet = nil): Boolean; overload; function LocalizarPorId_Transf(DataSet: TDataSet = nil; Id_Transf: real = 0): Boolean; {RA: 2900} function CalculaSaldo: Double; function CalculaSaldoParcial: Double; function ExcluirLctosPorId_Transf(Id_Transf: real): Boolean; {RA: 2900} function BuscarValorPago: Real; function LocalizarPorFatura(DataSet: TDataSet = nil): Boolean; property Banco: string read FBanco write FBanco; property Agencia: string read FAgencia write FAgencia; property Conta: string read FConta write FConta; property Fil_Origem: string read FFil_Origem write FFil_Origem; property Fil_Debito: string read FFil_Debito write FFil_Debito; property Dta_Lancamento: TDateTime read FDta_Lancamento write FDta_Lancamento; property Dta_LancamentoI: TDateTime read FDta_LancamentoI write FDta_LancamentoI; property Dta_LancamentoF: TDateTime read FDta_LancamentoF write FDta_LancamentoF; property Tpo_Documento: string read FTpo_Documento write FTpo_Documento; property Nro_Documento: Real read FNro_Documento write FNro_Documento; property SQLPadrao: string read GetSQL_DEFAULT; end; const SQL_DEFAULT = ' SELECT ' + ' LB.BANCO, ' + ' LB.AGENCIA, ' + ' LB.CONTA, ' + ' LB.DT_LANCAMENTO, ' + ' LB.TIPO_DOCUMENTO, ' + ' LB.DOCUMENTO, ' + ' LB.VL_DOCUMENTO, ' + ' LB.DC, ' + ' LB.DESCRICAO, ' + ' LB.HISTORICO, ' + ' LB.CENTRO_CUSTO, ' + ' LB.CONTA_CREDITO, ' + ' LB.CONTA_DEBITO, ' + ' LB.DT_ALTERACAO, ' + ' LB.OPERADOR, ' + ' LB.ID_TRANSF, ' + ' LB.FIL_ORIGEM, ' + ' LB.FIL_DEBITO, ' + ' CC.CENTRO_CUSTO NM_CENTROCUSTOS, ' + ' HIS.HISTORICO NM_HISTORICO ' + ' FROM STWCPGTLANB LB ' + ' LEFT JOIN STWCPGTCCUS CC ON CC.CODIGO = LB.CENTRO_CUSTO ' + ' LEFT JOIN STWCPGTHIS HIS ON HIS.CODIGO = LB.HISTORICO '; var dmLctoBancarios: TdmLctoBancarios; implementation uses udmPrincipal, udmSldoBancarios, uMatVars; {$R *.dfm} { TdmLctoBancarios } function TdmLctoBancarios.BuscarValorPago: Real; begin with qryManipulacao do begin Close; SQL.Clear; SQL.Add('SELECT SUM(VL_DOCUMENTO) AS TOTAL FROM STWCPGTLANB'); SQL.Add('WHERE TIPO_DOCUMENTO = :TIPO_DOCUMENTO'); SQL.Add(' AND DOCUMENTO = :DOCUMENTO'); SQL.Add(' AND FIL_ORIGEM = :FIL_ORIGEM'); ParamByName('TIPO_DOCUMENTO').AsString := FTpo_Documento; ParamByName('DOCUMENTO').AsFloat := FNro_Documento; ParamByName('FIL_ORIGEM').AsString := FFil_Origem; Open; if not IsEmpty then Result := FieldByName('TOTAL').AsFloat else Result := 0; end; end; function TdmLctoBancarios.CalculaSaldo: Double; var rTot_Saldo: Real; rCredito: Real; rDebito: Real; dDta_Inicial: TDateTime; dDta_Final: TDateTime; begin dDta_Inicial := FDta_LancamentoI; dDta_Final := FDta_LancamentoF; if not Assigned(dmSldoBancarios) then dmSldoBancarios := TdmSldoBancarios.Create(Application); with dmSldoBancarios do begin Banco := FBanco; Agencia := FAgencia; Conta := FConta; LocalizarSaldosConta; end; FDta_LancamentoF := FDta_LancamentoI; FDta_LancamentoI := dmSldoBancarios.qryLocalizacaoDT_SALDO.AsDateTime + 1; with qryManipulacao do begin Close; SQL.Clear; SQL.Add('SELECT SUM(VL_DOCUMENTO) AS CREDITO FROM STWCPGTLANB WHERE BANCO = :BANCO AND '); SQL.Add('AGENCIA =:AGENCIA AND CONTA =:CONTA AND DT_LANCAMENTO BETWEEN :DT_INICIAL AND :DT_FINAL AND DC =:CREDITO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDateTime := FDta_LancamentoI; Params[4].AsDateTime := FDta_LancamentoF; Params[5].AsString := 'C'; Open; rCredito := FieldByName('CREDITO').AsFloat; end; with qryManipulacao do begin Close; SQL.Clear; SQL.Add('SELECT SUM(VL_DOCUMENTO) AS DEBITO FROM STWCPGTLANB WHERE BANCO = :BANCO AND '); SQL.Add('AGENCIA =:AGENCIA AND CONTA =:CONTA AND DT_LANCAMENTO BETWEEN :DT_INICIAL AND :DT_FINAL AND DC =:DEBITO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDateTime := FDta_LancamentoI; Params[4].AsDateTime := FDta_LancamentoF; Params[5].AsString := 'D'; Open; rDebito := FieldByName('DEBITO').AsFloat; end; rTot_Saldo := rCredito - rDebito; rTot_Saldo := rTot_Saldo + dmSldoBancarios.qryLocalizacaoVL_SALDO.Value; FDta_LancamentoI := dDta_Inicial; FDta_LancamentoF := dDta_Final; Result := rTot_Saldo; end; function TdmLctoBancarios.CalculaSaldoParcial: Double; var rTot_Saldo: Real; rCredito: Real; rDebito: Real; dDta_Inicial: TDateTime; dDta_Final: TDateTime; dataInicial: string; datafinal: string; begin dDta_Inicial := FDta_LancamentoI; dDta_Final := FDta_LancamentoF; if not Assigned(dmSldoBancarios) then dmSldoBancarios := TdmSldoBancarios.Create(Application); with dmSldoBancarios do begin Banco := FBanco; Agencia := FAgencia; Conta := FConta; LocalizarSaldosConta; end; FDta_LancamentoI := dmSldoBancarios.qryLocalizacaoDT_SALDO.AsDateTime + 1; dataInicial := DateToStr(FDta_LancamentoI); datafinal := DateToStr(FDta_LancamentoF); with qryManipulacao do begin Close; SQL.Clear; SQL.Add('SELECT SUM(VL_DOCUMENTO) AS CREDITO FROM STWCPGTLANB WHERE BANCO = :BANCO AND '); SQL.Add('AGENCIA =:AGENCIA AND CONTA =:CONTA AND DT_LANCAMENTO BETWEEN :DT_INICIAL AND :DT_FINAL AND DC =:CREDITO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDateTime := FDta_LancamentoI; Params[4].AsDateTime := FDta_LancamentoF; Params[5].AsString := 'C'; Open; rCredito := FieldByName('CREDITO').AsFloat; end; with qryManipulacao do begin Close; SQL.Clear; SQL.Add('SELECT SUM(VL_DOCUMENTO) AS DEBITO FROM STWCPGTLANB WHERE BANCO = :BANCO AND '); SQL.Add('AGENCIA =:AGENCIA AND CONTA =:CONTA AND DT_LANCAMENTO BETWEEN :DT_INICIAL AND :DT_FINAL AND DC =:DEBITO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDateTime := FDta_LancamentoI; Params[4].AsDateTime := FDta_LancamentoF; Params[5].AsString := 'D'; Open; rDebito := FieldByName('DEBITO').AsFloat; end; rTot_Saldo := TruncNew(rCredito - rDebito, 0); rTot_Saldo := TruncNew(rTot_Saldo + dmSldoBancarios.qryLocalizacaoVL_SALDO.Value, 0); FDta_LancamentoI := dDta_Inicial; FDta_LancamentoF := dDta_Final; Result := TruncNew(rTot_Saldo, 0); end; function TdmLctoBancarios.ExcluirLctosPorId_Transf(Id_Transf: real): Boolean; begin result := False; if not dmPrincipal.ConexaoBanco.InTransaction then dmPrincipal.ConexaoBanco.StartTransaction; with qryManipulacao do begin Close; SQL.Clear; SQL.Add('DELETE FROM STWCPGTLANB'); SQL.Add('WHERE ID_TRANSF = :ID_TRANSF'); ParamByName('ID_TRANSF').AsFloat := Id_Transf; try ExecSQL; dmPrincipal.ConexaoBanco.Commit; result := True; except dmPrincipal.ConexaoBanco.Rollback; end; end; end; function TdmLctoBancarios.GetSQL_DEFAULT: string; begin Result := SQL_DEFAULT; end; function TdmLctoBancarios.LocalizarLancamentosDia(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.BANCO = :BANCO'); SQL.Add(' AND LB.AGENCIA = :AGENCIA'); SQL.Add(' AND LB.CONTA = :CONTA'); SQL.Add(' AND LB.DT_LANCAMENTO = :DT_LANCAMENTO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDate := FDta_Lancamento; Open; Result := not IsEmpty; end; end; function TdmLctoBancarios.LocalizarPorFatura(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryManutencao; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.BANCO = :BANCO'); SQL.Add(' AND LB.AGENCIA = :AGENCIA'); SQL.Add(' AND LB.CONTA = :CONTA'); SQL.Add(' AND LB.TIPO_DOCUMENTO = :TIPO_DOCUMENTO'); SQL.Add(' AND LB.DOCUMENTO = :DOCUMENTO'); SQL.Add('ORDER BY LB.BANCO, LB.AGENCIA, LB.CONTA, LB.DT_LANCAMENTO, LB.TIPO_DOCUMENTO, LB.DOCUMENTO'); ParamByName('BANCO').AsString := FBanco; ParamByName('AGENCIA').AsString := FAgencia; ParamByName('CONTA').AsString := FConta; ParamByName('TIPO_DOCUMENTO').AsString := FTpo_Documento; ParamByName('DOCUMENTO').Value := FNro_Documento; Open; Result := not IsEmpty; end; end; function TdmLctoBancarios.LocalizarPorId_Transf(DataSet: TDataSet; Id_Transf: real): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.ID_TRANSF = :ID_TRANSF'); ParamByName('ID_TRANSF').AsFloat := Id_Transf; Open; Result := not IsEmpty; end; end; function TdmLctoBancarios.LocalizarPorPeriodo(ADataInicial, ADataFinal: TDateTime; DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.DT_LANCAMENTO BETWEEN :DT_LANCAMENTOI AND :DT_LANCAMENTOF'); Sql.Add('ORDER BY LB.DT_LANCAMENTO, LB.BANCO, LB.AGENCIA, LB.CONTA, LB.TIPO_DOCUMENTO, LB.DOCUMENTO'); Params[0].AsDate := ADataInicial; Params[1].AsDate := ADataFinal; Open; Result := not IsEmpty; end; end; function TdmLctoBancarios.LocalizarPorPeriodo(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.BANCO = :BANCO'); SQL.Add(' AND LB.AGENCIA = :AGENCIA'); SQL.Add(' AND LB.CONTA = :CONTA'); SQL.Add(' AND (LB.DT_LANCAMENTO BETWEEN :DT_LANCAMENTOI AND :DT_LANCAMENTOF)'); Sql.Add('ORDER BY LB.DT_LANCAMENTO, LB.BANCO, LB.AGENCIA, LB.CONTA, LB.TIPO_DOCUMENTO, LB.DOCUMENTO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDate := FDta_LancamentoI; Params[4].AsDate := FDta_LancamentoF; Open; Result := not IsEmpty; end; end; procedure TdmLctoBancarios.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE LB.BANCO = :BANCO'); SQL.Add(' AND LB.AGENCIA = :AGENCIA'); SQL.Add(' AND LB.CONTA = :CONTA'); SQL.Add(' AND LB.DT_LANCAMENTO = :DT_LANCAMENTO'); SQL.Add(' AND LB.TIPO_DOCUMENTO = :TIPO_DOCUMENTO'); SQL.Add(' AND LB.DOCUMENTO = :DOCUMENTO'); SQL.Add(' AND LB.FIL_ORIGEM = :FIL_ORIGEM'); SQL.Add('ORDER BY LB.BANCO, LB.AGENCIA, LB.CONTA, LB.DT_LANCAMENTO, LB.TIPO_DOCUMENTO, LB.DOCUMENTO'); Params[0].AsString := FBanco; Params[1].AsString := FAgencia; Params[2].AsString := FConta; Params[3].AsDate := FDta_Lancamento; Params[4].AsString := FTpo_Documento; Params[5].AsFloat := FNro_Documento; Params[6].AsString := FFil_Origem; end; end; procedure TdmLctoBancarios.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); if FiltrarComMes then begin SQL.Add('WHERE LB.DT_LANCAMENTO BETWEEN :DT_INICIO AND :DT_FIM'); ParamByName('DT_INICIO').AsDate := IncMonth(pegarDataServidor, iQtdMesFiltro); ParamByName('DT_FIM').AsDateTime := pegarDataServidor + StrToTime('23:59:59'); end; SQL.Add('ORDER BY LB.BANCO, LB.AGENCIA, LB.CONTA, LB.DT_LANCAMENTO, LB.TIPO_DOCUMENTO, LB.DOCUMENTO'); end; end; end.
unit YWEvents; interface uses System.SysUtils, System.Classes, System.Generics.Collections; type TEventReciever = class; TEventSender = class(TComponent) private { Private declarations } protected { Protected declarations } RecieverList : TList<TEventReciever>; public { Public declarations } function DataModule : TDataModule; constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure AddReciever(R : TEventReciever); procedure RemoveReciever(R : TEventReciever); procedure BoardcastEvent(Sender : TObject=nil); published { Published declarations } end; TEventReciever = class(TComponent) private FEventSender: TEventSender; FOnCall: TNotifyEvent; procedure SetEventSender(const Value: TEventSender); procedure SetOnCall(const Value: TNotifyEvent); public destructor Destroy; override; published property EventSender : TEventSender read FEventSender write SetEventSender; property OnCall : TNotifyEvent read FOnCall write SetOnCall; end; implementation { TEventSender } procedure TEventSender.AddReciever(R: TEventReciever); begin if assigned(R) then if not RecieverList.Contains(R) then RecieverList.Add(R); end; procedure TEventSender.BoardcastEvent(Sender : TObject); var i : integer; begin for i := 0 to RecieverList.Count-1 do try if assigned(RecieverList[i].OnCall) then RecieverList[i].OnCall(Sender); except on E: Exception do end; end; constructor TEventSender.Create(AOwner: TComponent); begin inherited; RecieverList := TList<TEventReciever>.Create; end; function TEventSender.DataModule: TDataModule; begin if self.Owner is TDataModule then Result := Owner as TDataModule else Result := nil; end; destructor TEventSender.Destroy; var i : integer; begin for i := 0 to RecieverList.Count-1 do try RecieverList[i].FEventSender := nil; except on E: Exception do end; RecieverList.Free; inherited; end; procedure TEventSender.RemoveReciever(R: TEventReciever); begin if assigned(R) then begin R.FEventSender := nil; RecieverList.Remove(R); end; end; { TEventReciever } destructor TEventReciever.Destroy; begin if assigned(FEventSender) then FEventSender.RemoveReciever(self); inherited; end; procedure TEventReciever.SetEventSender(const Value: TEventSender); begin if assigned(FEventSender) then FEventSender.RemoveReciever(self); FEventSender := Value; if assigned(Value) then Value.AddReciever(self); end; procedure TEventReciever.SetOnCall(const Value: TNotifyEvent); begin FOnCall := Value; end; end.
unit RemoteAdm; interface uses Windows, Classes; function GetProcessList : TStringList; function StartProgram( filename : string; out ProcId : THandle ) : boolean; overload; function StopProgram( ProcId : THandle; TimeOut : integer ) : boolean; //function Reboot : boolean; implementation uses SysUtils, PSAPI; function GetProcessList : TStringList; const MaxProcess = 300; MaxModule = 300; MaxNameLength = 100; var processes : array[0..MaxProcess] of THandle; modules : array[0..MaxModule] of THandle; name : string; procUsed : integer; procHandle : THandle; modUsed : integer; i : integer; begin result := TStringList.Create; try if EnumProcesses( @processes, sizeof(processes), procUsed ) then begin procUsed := procUsed div sizeof(processes[0]); for i := 0 to pred(procUsed) do begin procHandle := OpenProcess( PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, processes[i] ); if (procHandle <> 0) and (EnumProcessModules( procHandle, @modules, sizeof(modules), modUsed )) then begin modUsed := modUsed div sizeof(modules[0]); if modUsed > 0 then begin SetLength( name, MaxNameLength ); if GetModuleBaseName( procHandle, modules[0], pchar(name), length(name) ) > 0 then result.AddObject( Trim(name), TObject(processes[i]) ); end; end; end; end; except end; end; function StartProgram( filename : string; out ProcId : THandle ) : boolean; overload; { const cWinStationDesktop : pchar = 'WinSta0\Default'; } var StartupInfo : TStartupInfo; ProcessInfo : TProcessInformation; begin try fillchar(StartupInfo, sizeof(StartupInfo), 0); StartupInfo.cb := sizeof(StartupInfo); //StartupnInfo.lpDesktop := cWinStationDesktop; StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_SHOW or SW_NORMAL; result := CreateProcess(nil, pchar(filename), nil, nil, false, 0, nil, nil, StartupInfo, ProcessInfo); if result then begin //WaitForInputIdle(ProcessInfo.hProcess, INFINITE); ProcId := ProcessInfo.dwProcessId; CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); end else ProcId := 0; except result := false; end; end; function StopProgram( ProcId : THandle; TimeOut : integer ) : boolean; var hProc : THandle; begin try hProc := OpenProcess( SYNCHRONIZE or PROCESS_TERMINATE, false, ProcId ); if hProc <> 0 then begin result := TerminateProcess( hProc, 0 ); if result then WaitForSingleObject( hProc, TimeOut ); end else result := false; except result := false; end; end; {function Reboot : boolean; var hToken : THandle; tkp : TTokenPrivileges; prevtkp : TTokenPrivileges; retlen : integer; begin // Get a token for this process. if OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin // Get the LUID for the shutdown privilege. if LookupPrivilegeValue(nil, pchar('SeShutdownPrivilege'), tkp.Privileges[0].Luid) then begin tkp.PrivilegeCount := 1; // one privilege to set tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. if AdjustTokenPrivileges(hToken, false, tkp, sizeof(prevtkp), prevtkp, retlen) then begin // Cannot test the return value of AdjustTokenPrivileges. if GetLastError = ERROR_SUCCESS then // Shut down the system and force all applications to close. if ExitWindowsEx(EWX_REBOOT or EWX_FORCE, 0) then Result := true else Result := false else Result := false; end else Result := false; end else Result := false; end else Result := false; end;} end.
unit RealState.House.Repository; interface uses Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.SysUtils, System.Classes, RealState.Repository; type THouseRepository = class(TDataModule) HousesQuery: TFDQuery; HousesQueryID: TLargeintField; HousesQueryFavorite: TBooleanField; HousesQueryAddress: TWideStringField; HousesQueryCity: TWideStringField; HousesQueryState: TWideStringField; HousesQueryZipCode: TWideStringField; HousesQueryBeds: TIntegerField; HousesQueryBaths: TIntegerField; HousesQueryHouseSize: TIntegerField; HousesQueryLotSize: TFMTBCDField; HousesQueryPrice: TCurrencyField; HousesQueryCoordinates: TWideStringField; HousesQueryFeatures: TWideMemoField; HousesQueryYearBuilt: TIntegerField; HousesQueryType: TSmallintField; HousesQueryStatus: TSmallintField; HousesQueryImage: TWideStringField; HousesQueryAgentId: TLargeintField; procedure DataModuleCreate(Sender: TObject); private fRepository: TRepository; procedure BindConnection; protected function Connection: TFDConnection; public function GetHouses: TDataSet; procedure SetFavorite(id: Int64; favorite: boolean); end; var HouseRepository: THouseRepository; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure THouseRepository.BindConnection; begin HousesQuery.Connection := Connection; end; function THouseRepository.Connection: TFDConnection; begin Result := fRepository.Connection; end; procedure THouseRepository.DataModuleCreate(Sender: TObject); begin fRepository := TRepository.Create(Self); BindConnection; end; function THouseRepository.GetHouses: TDataSet; begin Result := TFDMemTable.Create(nil); HousesQuery.Open; TFDTable(Result).CopyDataSet(HousesQuery, [coStructure, coRestart, coAppend]); end; procedure THouseRepository.SetFavorite(id: Int64; favorite: boolean); const UPDATE_FAVORITE_SQL = 'update "House" set "Favorite" = :p0 where "ID" = :p1 and "Favorite" <> :p2'; begin Connection.ExecSQL(UPDATE_FAVORITE_SQL, [favorite, id, favorite]); end; end.
unit osSQLDataSetProvider; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Provider, db, dbclient, variants, sqlexpr, osCustomDataSetProvider; type TosSQLDataSetProvider = class(TosCustomDataSetProvider) private FInternalDataset: TSQLDataset; function GetInternalDataset: TSQLDataset; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {** Dataset interno utilizado para submeter atualizações customizadas e Executar métodos internos do DataRequest } property InternalDataset: TSQLDataset read GetInternalDataset; {** Implementa o método interno (DataRequest) GET_OIDHIGH } function GetIDHigh(const PSeqName: string = 'Geral'): OleVariant; override; published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('OS Server', [TosSQLDataSetProvider]); end; { TccDataSetProvider } constructor TosSQLDataSetProvider.Create(AOwner: TComponent); begin inherited; FInternalDataset := TSQLDataset.Create(Self); end; destructor TosSQLDataSetProvider.Destroy; begin FInternalDataset.Free; inherited; end; function TosSQLDataSetProvider.GetInternalDataset: TSQLDataset; begin if Assigned(Dataset) then begin if Assigned(FInternalDataset.SQLConnection) then Result := FInternalDataset else if (Dataset is TSQLDataset) then begin FInternalDataset.SQLConnection := TSQLDataset(Dataset).SQLConnection; Result := FInternalDataset; end else raise Exception.Create('O Dataset deve ser dbExpress'); end else raise Exception.Create('Dataset não informado'); end; function TosSQLDataSetProvider.GetIDHigh(const PSeqName: string = 'Geral'): OleVariant; begin Result := 0; with InternalDataset do begin if Active then Close; CommandType := ctStoredProc; CommandText := 'OS_GETIDHIGH'; Params.Clear; with Params.CreateParam(ftstring, 'SEQNAME', ptInput) do AsString := PSeqName; Params.CreateParam(ftInteger, 'HIGHVALUE', ptOutput); ExecSQL; Result := Params.ParamByName('HighValue').Value; end; end; end.
//====================================================================================================================// //======================================= THE COMMON PASCAL AST PARSER CLASS =========================================// //====================================================================================================================// unit AST.Pascal.Parser; interface {$I compilers.inc} uses SysUtils, Math, Classes, StrUtils, Types, IOUtils, Generics.Collections, AST.Lexer.Delphi, AST.Delphi.Classes, AST.Delphi.DataTypes, AST.Lexer, AST.Delphi.Operators, AST.Parser.Utils, AST.Parser.Messages, AST.Parser.Contexts, AST.Delphi.Contexts, AST.Classes, AST.Parser.Options, AST.Project; type TNPUnit = class; TUnitSection = (usInterface, usImplementation); {parse members context - контекст парсинга выражений вид a.b.c или a[1, 2, 3].b...} TPMContext = record private FCnt: Integer; // кол-во элементов в выражении FItems: TIDExpressions; // элементы цепочки function GetLast: TIDExpression; inline; public ID: TIdentifier; // текущий идентификатор ItemScope: TScope; // текущий scope DataType: TIDType; // результатирующий тип цепочки выражений property Items: TIDExpressions read FItems; property Count: Integer read FCnt; property Last: TIDExpression read GetLast; procedure Init; inline; procedure Add(const Expr: TIDExpression); procedure Clear; end; TUnits = TList<TObject>; TTypes = TList<TIDType>; TIDDeclarationList = TList<TIDDeclaration>; TCondIFValue = (condIFFalse, condIfTrue, condIFUnknown); TNPUnit = class(TASTModule) type TVarModifyPlace = (vmpAssignment, vmpPassArgument); TIdentifiersPool = TPool<TIdentifier>; private FID: Integer; // ID модуля в пакете fLexer: TDelphiLexer; FIntfScope: TScope; // interface scope FImplScope: TScope; // implementation scope FIntfImportedUnits: TUnitList; FImplImportedUnits: TUnitList; FMessages: ICompilerMessages; FVarSpace: TVarSpace; FProcSpace: TProcSpace; FTypeSpace: TTypeSpace; FConsts: TConstSpace; // список нетривиальных констант (массивы, структуры) FCompiled: Boolean; function GetMessagesText: string; protected fUnitName: TIdentifier; // the Unit declaration name ////////////////////////////////////////////////////////////////////////////////////////////////////////// function GetModuleName: string; override; procedure SetUnitName(const Name: string); public class function IsConstValueInRange(Value: TIDExpression; RangeExpr: TIDRangeConstant): Boolean; static; class function IsConstRangesIntersect(const Left, Right: TIDRangeConstant): Boolean; static; class function IsConstEqual(const Left, Right: TIDExpression): Boolean; static; //====================================================================================================================================== procedure AddType(const Decl: TIDType); inline; procedure AddConstant(const Decl: TIDConstant); inline; public property Lexer: TDelphiLexer read fLexer; public //////////////////////////////////////////////////////////////////////////// constructor Create(const Project: IASTProject; const FileName: string; const Source: string = ''); override; destructor Destroy; override; //////////////////////////////////////////////////////////////////////////// procedure SaveConstsToStream(Stream: TStream); // сохраняет сложные константы модуля procedure SaveMethodBodies(Stream: TStream); // сохраняет тела всех методов модуля procedure SaveDeclToStream(Stream: TStream); // сохраняет все декларации модуля procedure SaveBodyToStream(Stream: TStream); // сохраняет тела всех глобальных процедур модуля procedure SaveTypesToStream(Stream: TStream); // сохраняет все типы модуля function Compile(RunPostCompile: Boolean = True): TCompilerResult; virtual; function CompileIntfOnly: TCompilerResult; virtual; function UsedUnit(const UnitName: string): Boolean; function GetDefinesAsString: string; property _ID: TIdentifier read FUnitName; property UnitID: Integer read FID write FID; property Name: string read FUnitName.Name; property Messages: ICompilerMessages read FMessages; property MessagesText: string read GetMessagesText; property IntfScope: TScope read FIntfScope; // Interface section scope property ImplScope: TScope read FImplScope; // Implementation section scope property IntfImportedUnits: TUnitList read fIntfImportedUnits; property ImplImportedUnits: TUnitList read fImplImportedUnits; property Compiled: Boolean read FCompiled; property TypeSpace: TTypeSpace read FTypeSpace; property VarSpace: TVarSpace read FVarSpace; property ProcSpace: TProcSpace read FProcSpace; property ConstSpace: TConstSpace read FConsts; end; implementation { TCompiler } uses AST.Delphi.System, AST.Parser.Errors, AST.Pascal.ConstCalculator; procedure TNPUnit.SetUnitName(const Name: string); begin FUnitName.Name := Name; end; function TNPUnit.Compile(RunPostCompile: Boolean = True): TCompilerResult; begin Result := TCompilerResult.CompileFail; end; function TNPUnit.CompileIntfOnly: TCompilerResult; begin Result := TCompilerResult.CompileFail; end; constructor TNPUnit.Create(const Project: IASTProject; const FileName: string; const Source: string = ''); begin inherited Create(Project, FileName, Source); fLexer := TDelphiLexer.Create(Source); FMessages := TCompilerMessages.Create; //FVisibility := vPublic; FIntfScope := TScope.Create(stGlobal, @FVarSpace, @FProcSpace, nil, Self); {$IFDEF DEBUG}FIntfScope.Name := 'unit_intf_scope';{$ENDIF} FImplScope := TImplementationScope.Create(FIntfScope, nil); {$IFDEF DEBUG}FImplScope.Name := 'unit_impl_scope';{$ENDIF} FIntfImportedUnits := TUnitList.Create; FImplImportedUnits := TUnitList.Create; //FBENodesPool := TBENodesPool.Create(16); if Assigned(SYSUnit) then begin FTypeSpace.Initialize(SYSUnit.SystemTypesCount); // добовляем system в uses FIntfImportedUnits.AddObject('system', SYSUnit); end; // FOptions := TCompilerOptions.Create(Package.Options); // // fCondStack := TSimpleStack<Boolean>.Create(0); // fCondStack.OnPopError := procedure begin ERROR_INVALID_COND_DIRECTIVE() end; end; destructor TNPUnit.Destroy; begin FIntfScope.Free; FImplScope.Free; fLexer.Free; FIntfImportedUnits.Free; FImplImportedUnits.Free; inherited; end; function TNPUnit.UsedUnit(const UnitName: string): Boolean; var i: Integer; begin i := FIntfImportedUnits.IndexOf(UnitName); if i > 0 then Exit(True); i := FImplImportedUnits.IndexOf(UnitName); if i > 0 then Exit(True) else Exit(False); end; class function TNPUnit.IsConstValueInRange(Value: TIDExpression; RangeExpr: TIDRangeConstant): Boolean; var Expr: TIDExpression; begin Expr := ProcessConstOperation(Value, RangeExpr.Value.LBExpression, opLess); if TIDBooleanConstant(Expr.Declaration).Value then Exit(False); Expr := ProcessConstOperation(Value, RangeExpr.Value.HBExpression, opLessOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end; class function TNPUnit.IsConstRangesIntersect(const Left, Right: TIDRangeConstant): Boolean; var Expr, LeftLB, LeftHB, RightLB, RightHB: TIDExpression; begin LeftLB := Left.Value.LBExpression; LeftHB := Left.Value.HBExpression; RightLB := Right.Value.LBExpression; RightHB := Right.Value.HBExpression; Expr := ProcessConstOperation(LeftLB, RightLB, opLess); // если Left.Low < Right.Low if TIDBooleanConstant(Expr.Declaration).Value then begin Expr := ProcessConstOperation(LeftHB, RightLB, opGreaterOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end else begin Expr := ProcessConstOperation(RightHB, LeftLB, opGreaterOrEqual); Result := TIDBooleanConstant(Expr.Declaration).Value; end; end; procedure TNPUnit.AddConstant(const Decl: TIDConstant); var Item: TIDConstant; begin Item := FConsts.First; while Assigned(Item) do begin if Item = Decl then Exit else Break; Item := TIDConstant(Item.NextItem); end; FConsts.Add(Decl); end; procedure TNPUnit.AddType(const Decl: TIDType); begin if not (Decl is TIDAliasType) and not Decl.IsPooled then begin FTypeSpace.Add(Decl); Decl.IsPooled := True; end; end; function TNPUnit.GetMessagesText: string; begin Result := FMessages.GetAsString; end; function TNPUnit.GetModuleName: string; begin Result := fUnitName.Name; end; class function TNPUnit.IsConstEqual(const Left, Right: TIDExpression): Boolean; var RExpr: TIDExpression; begin RExpr := ProcessConstOperation(Left, Right, opEqual); Result := TIDBooleanConstant(RExpr.Declaration).Value; end; {parser methods} procedure TNPUnit.SaveConstsToStream(Stream: TStream); begin Assert(False); end; procedure TNPUnit.SaveMethodBodies(Stream: TStream); begin Assert(False); end; procedure TNPUnit.SaveTypesToStream(Stream: TStream); begin Assert(False); end; procedure TNPUnit.SaveDeclToStream(Stream: TStream); begin Assert(False); end; procedure TNPUnit.SaveBodyToStream(Stream: TStream); begin Assert(False); end; { TPMContext } procedure TPMContext.Add(const Expr: TIDExpression); begin SetLength(FItems, FCnt + 1); FItems[FCnt] := Expr; Inc(FCnt); end; procedure TPMContext.Clear; begin FItems := nil; FCnt := 0; end; function TPMContext.GetLast: TIDExpression; begin if FCnt > 0 then Result := FItems[FCnt - 1] else Result := nil; end; procedure TPMContext.Init; begin FCnt := 0; DataType := nil; end; function TNPUnit.GetDefinesAsString: string; begin // Result := FDefines.Text; end; initialization FormatSettings.DecimalSeparator := '.'; end.
unit RemoteControlMethods; interface uses SysUtils, Classes, Messages, Rtti, AppEvnts, SyncObjs, CommunicationTypes; type {$METHODINFO ON} TRemoteControlMethods = class(TComponent) private function Sync_ExecuteRemoteFunction( const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList): TVariantList; function SearchComponent(aParent: TComponent; aRemoteObject: TObjectStruct): TComponent; function Sync_RemoteControlExists( const aRemoteObjectTree: TObjectStructList): Boolean; procedure Sync_PostRemoteMessage(const aRemoteObjectTree: TObjectStructList; const aMessage, aWParam, aLParam: Int64); protected FAppEvents: TApplicationEvents; FAppIsIdle: TEvent; procedure AppIdle(Sender: TObject; var Done: Boolean); public procedure AfterConstruction;override; destructor Destroy;override; function ExecuteRemoteFunction(const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList; const aTimeout: integer = 0): TVariantList; procedure ExecuteRemoteFunction_Async(const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList; const aTimeout: integer = 0); procedure PostRemoteMessage(const aRemoteObjectTree: TObjectStructList; const aMessage: Integer; const aWParam: Integer; const aLParam: Integer; const aTimeout: integer = 0); function RemoteControlExists(const aRemoteObjectTree: TObjectStructList; const aTimeout: integer = 0): Boolean; end; {$METHODINFO OFF} TSimpleMainformSync = class protected type PSynchronizeRecord = ^TSynchronizeRecord; TSynchronizeRecord = record FMethod : TThreadMethod; FProcedure: TThreadProcedure; end; protected FAsyncMessageHandle: THandle; procedure WndProc(var aMsg: TMessage); public procedure Queue(aProc: TThreadProcedure); procedure AfterConstruction;override; end; implementation uses Windows, Controls, Forms; const WM_ASYNC_EXECUTE = WM_USER + 1; var _SimpleMainformSync: TSimpleMainformSync; RttiCache: TRttiContext; function SimpleMainformSync: TSimpleMainformSync; begin if _SimpleMainformSync = nil then _SimpleMainformSync := TSimpleMainformSync.Create; //todo: not threadsafe Result := _SimpleMainformSync; end; { TRemoteControlMethods } procedure TRemoteControlMethods.AfterConstruction; begin inherited; FAppIsIdle := TEvent.Create; FAppIsIdle.ResetEvent; FAppEvents := TApplicationEvents.Create(nil); FAppEvents.OnIdle := Self.AppIdle; end; procedure TRemoteControlMethods.AppIdle(Sender: TObject; var Done: Boolean); begin FAppIsIdle.SetEvent; end; destructor TRemoteControlMethods.Destroy; begin FAppEvents.Free; FAppIsIdle.Free; inherited; end; function TRemoteControlMethods.ExecuteRemoteFunction( const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList; const aTimeout: integer = 0): TVariantList; var vResult: TVariantList; begin if (aTimeout > 0) and (FAppIsIdle.WaitFor(aTimeout) = wrTimeout) then raise Exception.CreateFmt('GUI not idle after %d msec',[aTimeout]); TThread.Synchronize( TThread.CurrentThread, procedure begin vResult := Sync_ExecuteRemoteFunction(aRemoteObjectTree, aRemoteFunction, aArguments); end); Result := vResult; FAppIsIdle.ResetEvent; end; procedure TRemoteControlMethods.ExecuteRemoteFunction_Async( const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList; const aTimeout: integer = 0); begin if (aTimeout > 0) and (FAppIsIdle.WaitFor(aTimeout) = wrTimeout) then raise Exception.CreateFmt('GUI not idle after %d msec',[aTimeout]); //TThread.Queue( TThread.CurrentThread, -> sometimes lock if you do a .queue direct after a .synchronize, so we made our own message based queue... SimpleMainformSync.Queue( procedure begin // try Sync_ExecuteRemoteFunction(aRemoteObjectTree, aRemoteFunction, aArguments); // finally // remoteObjectTree.Free; // arguments.Free; // end; end); FAppIsIdle.ResetEvent; end; procedure TRemoteControlMethods.PostRemoteMessage( const aRemoteObjectTree: TObjectStructList; const aMessage, aWParam, aLParam: Integer; const aTimeout: integer = 0); begin if (aTimeout > 0) and (FAppIsIdle.WaitFor(aTimeout) = wrTimeout) then raise Exception.CreateFmt('GUI not idle after %d msec',[aTimeout]); TThread.Synchronize( TThread.CurrentThread, procedure begin Sync_PostRemoteMessage(aRemoteObjectTree, aMessage, aWParam, aLParam); end); FAppIsIdle.ResetEvent; end; function TRemoteControlMethods.RemoteControlExists( const aRemoteObjectTree: TObjectStructList; const aTimeout: integer = 0): Boolean; var bResult: Boolean; begin if (aTimeout > 0) and (FAppIsIdle.WaitFor(aTimeout) = wrTimeout) then raise Exception.CreateFmt('GUI not idle after %d msec',[aTimeout]); TThread.Synchronize( TThread.CurrentThread, procedure begin bResult := Sync_RemoteControlExists(aRemoteObjectTree); end); Result := bResult; end; function TRemoteControlMethods.SearchComponent(aParent: TComponent; aRemoteObject: TObjectStruct): TComponent; var tempcomp: TComponent; begin Result := aParent.FindComponent(aRemoteObject.ObjectName); //check topmost form (of same type) if (Result <> nil) then begin if (Result is TCustomForm) then begin if Screen.ActiveCustomForm is Result.ClassType then Result := Screen.ActiveCustomForm; end; end else //if Result = nil then begin for tempcomp in aParent do begin if tempcomp.ClassName = aRemoteObject.ObjectClass then begin if Result <> nil then Assert(False, '2 or more components found of same class!'); Result := tempcomp; end; if Result = nil then Result := SearchComponent(tempcomp, aRemoteObject); if Result <> nil then Break; end; if (Result = nil) and (Screen.ActiveCustomForm <> nil) and ( (Screen.ActiveCustomForm.Name = aRemoteObject.ObjectName) or (Screen.ActiveCustomForm.ClassName = aRemoteObject.ObjectClass) ) then Result := Screen.ActiveCustomForm; end; end; function TRemoteControlMethods.Sync_ExecuteRemoteFunction(const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList): TVariantList; var childcomponent: TComponent; rttimethod: TRttiMethod; rttitype: TRttiType; rttiprop: TRttiProperty; i: Integer; remoteobject: TObjectStruct; args: array of TValue; tvResult, tvCast: TValue; sFullPath: string; begin Result := TVariantList.Create; childcomponent := Forms.Application; sFullPath := childcomponent.Name; for i := aRemoteObjectTree.Count - 1 downto 0 do begin remoteobject := aRemoteObjectTree.Objects[i]; sFullPath := sFullPath + '.' + remoteobject.ObjectName; end; for i := aRemoteObjectTree.Count - 1 downto 0 do //for remoteobject in aRemoteObjectTree.InnerArray do begin remoteobject := aRemoteObjectTree.Objects[i]; if remoteobject = nil then Continue; if remoteobject.ObjectName = '' then Continue; //= Forms.Application Assert(childcomponent <> nil); childcomponent := SearchComponent(childcomponent, remoteobject); if childcomponent = nil then raise Exception.CreateFmt('Remote error: cannot find object "%s" (full path = "%s")', [remoteobject.ObjectName, sFullPath]); end; Assert(childcomponent <> nil); rttitype := RttiCache.GetType( childcomponent.ClassType ); Assert(rttitype <> nil); rttimethod := rttitype.GetMethod(aRemoteFunction); if rttimethod <> nil then begin SetLength(args, aArguments.Count); for i := 0 to aArguments.Count - 1 do args[i] := TValue.FromVariant( aArguments.Variants[i].Value ); tvResult := rttimethod.Invoke(childcomponent, args); end else begin Assert( aArguments.Count <= 1); rttiprop := rttitype.GetProperty(aRemoteFunction); Assert(rttiprop <> nil); if aArguments.Count = 1 then rttiprop.SetValue(childcomponent, TValue.FromVariant( aArguments.Variants[0].Value )); tvResult := rttiprop.GetValue(childcomponent); end; if not tvResult.IsEmpty then begin if tvResult.TryCast(TypeInfo(Variant), tvCast) then Result.Add( tvCast.AsVariant ) else if tvResult.TypeInfo = TypeInfo(Boolean) then Result.Add( tvResult.AsBoolean ) else raise Exception.CreateFmt('Unsupported type: %s', [tvResult.TypeInfo.Name]); // Result := tvCast.AsOrdinal // Result := tvCast.AsInteger // Result := tvCast.AsExtended // Result := tvCast.AsInt64 // Result := tvCast.AsString // Result := tvCast.AsCurrency end end; function TRemoteControlMethods.Sync_RemoteControlExists( const aRemoteObjectTree: TObjectStructList): Boolean; var childcomponent: TComponent; i: Integer; remoteobject: TObjectStruct; sFullPath: string; begin childcomponent := Forms.Application; sFullPath := childcomponent.Name; for i := aRemoteObjectTree.Count - 1 downto 0 do begin remoteobject := aRemoteObjectTree.Objects[i]; sFullPath := sFullPath + '.' + remoteobject.ObjectName; end; for i := aRemoteObjectTree.Count - 1 downto 0 do begin remoteobject := aRemoteObjectTree.Objects[i]; if remoteobject = nil then Continue; if remoteobject.ObjectName = '' then Continue; //= Forms.Application if childcomponent = nil then Break; childcomponent := SearchComponent(childcomponent, remoteobject); end; Result := (childcomponent <> nil); end; procedure TRemoteControlMethods.Sync_PostRemoteMessage( const aRemoteObjectTree: TObjectStructList; const aMessage, aWParam, aLParam: Int64); var childcomponent: TComponent; i: Integer; remoteobject: TObjectStruct; sFullPath: string; begin remoteobject := nil; childcomponent := Forms.Application; Assert(aRemoteObjectTree.Count > 0, 'Empty object list!'); sFullPath := childcomponent.Name; for i := aRemoteObjectTree.Count - 1 downto 0 do begin remoteobject := aRemoteObjectTree.Objects[i]; sFullPath := sFullPath + '.' + remoteobject.ObjectName; end; for i := aRemoteObjectTree.Count - 1 downto 0 do begin remoteobject := aRemoteObjectTree.Objects[i]; if remoteobject = nil then Continue; if remoteobject.ObjectName = '' then Continue; //= Forms.Application Assert(childcomponent <> nil); childcomponent := SearchComponent(childcomponent, remoteobject); if childcomponent = nil then raise Exception.CreateFmt('Remote error: cannot find object "%s" (full path = "%s")', [remoteobject.ObjectName, sFullPath]); end; if childcomponent.InheritsFrom(TWinControl) then PostMessage( (childcomponent as TWinControl).Handle, aMessage, aWParam, aLParam) else raise Exception.CreateFmt('Remote error: cannot send message to object "%s": is not a TWinControl (full path = "%s")', [remoteobject.ObjectName, sFullPath]); end; { TSimpleMainformSync } procedure TSimpleMainformSync.AfterConstruction; begin inherited; TThread.Synchronize(nil, procedure begin //do this in mainthread! FAsyncMessageHandle := Classes.AllocateHWnd(WndProc); end); end; procedure TSimpleMainformSync.Queue(aProc: TThreadProcedure); var LSynchronize: PSynchronizeRecord; begin New(LSynchronize); LSynchronize.FMethod := nil; LSynchronize.FProcedure := aProc; PostMessage(Self.FAsyncMessageHandle, WM_ASYNC_EXECUTE, WPARAM(LSynchronize), 0); end; procedure TSimpleMainformSync.WndProc(var aMsg: TMessage); var LSynchronize: PSynchronizeRecord; begin if FAsyncMessageHandle = 0 then Exit; if aMsg.Msg >= WM_USER then begin LSynchronize := PSynchronizeRecord(aMsg.WParam); if LSynchronize <> nil then try if Assigned(LSynchronize.FProcedure) then LSynchronize.FProcedure() else if Assigned(LSynchronize.FMethod) then LSynchronize.FMethod(); finally Dispose(LSynchronize); end; end else aMsg.Result := DefWindowProc(FAsyncMessageHandle, aMsg.Msg, aMsg.WParam, aMsg.LParam); end; initialization RttiCache := TRttiContext.Create; finalization RttiCache.Free; end.
//Exercicio 49: Faça um algoritmo que conte de 1 a 100 e a cada múltiplo de 10 emita uma mensagem: "Múltiplo de 10". { Solução em Portugol Algoritmo Exercicio 49; Var numero,contador: inteiro; Inicio exiba("Programa que exibe múltiplos de 10."); para contador <- 1 até 100 faça se(resto(contador,10) = 0) então exiba(contador," : Múltiplo de 10.") fimse; fimpara; Fim. } // Solução em Pascal Program Exercicio49; uses crt; var numero,contador: integer; begin clrscr; writeln('Programa que exibe múltiplos de 10.'); for contador := 1 to 100 do Begin if((contador mod 10) = 0) then writeln(contador,' : Múltiplo de 10.'); End; repeat until keypressed; end.
unit Rule_CYHT2; interface uses BaseRule, BaseRuleData, Rule_LLV, Rule_EMA, Rule_HHV; type TRule_CYHT_Price_Data = record ParamN: Word; ParamEMASK: Word; ParamEMASD: Word; Var1_Float: PArray; Var2_LLV: TRule_LLV; Var3_HHV: TRule_HHV; Var4_Float: PArray; Ret_SK_EMA: TRule_EMA; Ret_SD_EMA: TRule_EMA; end; PRule_CYHT_Result_Day = ^TRule_CYHT_Result_Day; TRule_CYHT_Result_Day = record SK: double; SD: double; end; TRule_CYHT_Price = class(TBaseStockRule) protected fCYHT_Price_Data: TRule_CYHT_Price_Data; function GetSKValue(AIndex: integer): double; function GetSDValue(AIndex: integer): double; function GetParamN1: Word; procedure SetParamN1(const Value: Word); function GetParamEMASK: Word; procedure SetParamEMASK(const Value: Word); function GetParamEMASD: Word; procedure SetParamEMASD(const Value: Word); function DoGetSKData(AIndex: integer): double; function DoGetSDData(AIndex: integer): double; public constructor Create(ADataType: TRuleDataType = dtNone); override; destructor Destroy; override; procedure Execute; override; // 中间过程 property FloatVar1: PArray read fCYHT_Price_Data.Var1_Float; property FloatVar4: PArray read fCYHT_Price_Data.Var4_Float; property LLV: TRule_LLV read fCYHT_Price_Data.Var2_LLV; property HHV: TRule_HHV read fCYHT_Price_Data.Var3_HHV; property EMA_SK: TRule_EMA read fCYHT_Price_Data.Ret_SK_EMA; property EMA_SD: TRule_EMA read fCYHT_Price_Data.Ret_SD_EMA; // 结果 property SK[AIndex: integer]: double read GetSKValue; property SD[AIndex: integer]: double read GetSDValue; // 34 property ParamN1: Word read GetParamN1 write SetParamN1; // 13 property ParamEMASK: Word read GetParamEMASK write SetParamEMASK; // 3 property ParamEMASD: Word read GetParamEMASD write SetParamEMASD; end; implementation (*// VAR1:=(2*CLOSE+HIGH+LOW+OPEN)/5; VAR2:=LLV(LOW,34); VAR3:=HHV(HIGH,34); SK: EMA((VAR1-VAR2)/(VAR3-VAR2)*100,13); SD: EMA(SK,3); //*) (* 做一点 小创新 把 时间轴 挪动一天 可能更准确 指标具有滞后性 前挪动 ? 后挪动 ? *) { TRule_CYHT } constructor TRule_CYHT_Price.Create(ADataType: TRuleDataType = dtNone); begin inherited; FillChar(fCYHT_Price_Data, SizeOf(fCYHT_Price_Data), 0); fCYHT_Price_Data.ParamN := 34; fCYHT_Price_Data.ParamEMASK := 13; fCYHT_Price_Data.ParamEMASD := 3; fCYHT_Price_Data.Var2_LLV := TRule_LLV.Create(dtDouble); fCYHT_Price_Data.Var3_HHV := TRule_HHV.Create(dtDouble); fCYHT_Price_Data.Ret_SK_EMA := TRule_EMA.Create(dtDouble); fCYHT_Price_Data.Ret_SD_EMA := TRule_EMA.Create(dtDouble); end; destructor TRule_CYHT_Price.Destroy; begin CheckInArray(fCYHT_Price_Data.Var1_Float); CheckInArray(fCYHT_Price_Data.Var4_Float); fCYHT_Price_Data.Var2_LLV.Free; fCYHT_Price_Data.Var3_HHV.Free; fCYHT_Price_Data.Ret_SK_EMA.Free; fCYHT_Price_Data.Ret_SD_EMA.Free; inherited; end; procedure TRule_CYHT_Price.Execute; var i: integer; tmpV: double; begin if Assigned(OnGetDataLength) then begin fBaseRuleData.DataLength := OnGetDataLength; if fBaseRuleData.DataLength > 0 then begin // ----------------------------------- if nil = fCYHT_Price_Data.Var1_Float then fCYHT_Price_Data.Var1_Float := CheckOutArrayDouble; SetArrayLength(fCYHT_Price_Data.Var1_Float, fBaseRuleData.DataLength); // ----------------------------------- if nil = fCYHT_Price_Data.Var4_Float then fCYHT_Price_Data.Var4_Float := CheckOutArrayDouble; SetArrayLength(fCYHT_Price_Data.Var4_Float, fBaseRuleData.DataLength); // ----------------------------------- //tmpVar1_FloatNode := fCYHT_Price_Data.Var1_Float.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin // (2*CLOSE+HIGH+LOW+OPEN)/5; tmpV := 2 * OnGetPriceClose(i); tmpV := tmpV + OnGetPriceHigh(i); tmpV := tmpV + OnGetPriceLow(i); tmpV := tmpV + OnGetPriceOpen(i); tmpV := tmpV / 5; SetArrayDoubleValue(fCYHT_Price_Data.Var1_Float, i, tmpV); end; end; end; fCYHT_Price_Data.Var2_LLV.ParamN := fCYHT_Price_Data.ParamN; fCYHT_Price_Data.Var2_LLV.OnGetDataLength := Self.OnGetDataLength; fCYHT_Price_Data.Var2_LLV.OnGetDataF := Self.OnGetPriceLow; fCYHT_Price_Data.Var2_LLV.Execute; fCYHT_Price_Data.Var3_HHV.ParamN := fCYHT_Price_Data.ParamN; fCYHT_Price_Data.Var3_HHV.OnGetDataLength := Self.OnGetDataLength; fCYHT_Price_Data.Var3_HHV.OnGetDataF := Self.OnGetPriceHigh; fCYHT_Price_Data.Var3_HHV.Execute; //tmpVar1_FloatNode := fCYHT_Price_Data.Var1_Float.FirstValueNode; //tmpVar4_FloatNode := fCYHT_Price_Data.Var4_Float.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpV := (GetArrayDoubleValue(fCYHT_Price_Data.Var1_Float, i) - fCYHT_Price_Data.Var2_LLV.ValueF[i]); tmpV := tmpV * 100; if fCYHT_Price_Data.Var3_HHV.valueF[i] <> fCYHT_Price_Data.Var2_LLV.ValueF[i] then begin tmpV := tmpV / (fCYHT_Price_Data.Var3_HHV.valueF[i] - fCYHT_Price_Data.Var2_LLV.ValueF[i]); end else begin tmpV := $FFFFFFFF; end; //**tmpV := Round(tmpV * 100) / 100; SetArrayDoubleValue(fCYHT_Price_Data.Var4_Float, i, tmpV); end; fCYHT_Price_Data.Ret_SK_EMA.ParamN := fCYHT_Price_Data.ParamEMASK; fCYHT_Price_Data.Ret_SK_EMA.OnGetDataLength := Self.OnGetDataLength; fCYHT_Price_Data.Ret_SK_EMA.OnGetDataF := Self.DoGetSKData; fCYHT_Price_Data.Ret_SK_EMA.Execute; fCYHT_Price_Data.Ret_SD_EMA.ParamN := fCYHT_Price_Data.ParamEMASD; fCYHT_Price_Data.Ret_SD_EMA.OnGetDataLength := Self.OnGetDataLength; fCYHT_Price_Data.Ret_SD_EMA.OnGetDataF := Self.DoGetSDData; fCYHT_Price_Data.Ret_SD_EMA.Execute; end; function TRule_CYHT_Price.DoGetSKData(AIndex: integer): double; var tmpV: double; begin // (VAR1-VAR2)/(VAR3-VAR2)*100, //tmpVar1_FloatNode := fCYHT_Price_Data.Var1_Float.FirstValueNode; tmpV := (GetArrayDoubleValue(fCYHT_Price_Data.Var1_Float, AIndex) - fCYHT_Price_Data.Var2_LLV.ValueF[AIndex]); tmpV := tmpV * 100; if fCYHT_Price_Data.Var3_HHV.valueF[AIndex] <> fCYHT_Price_Data.Var2_LLV.ValueF[AIndex] then begin tmpV := tmpV / (fCYHT_Price_Data.Var3_HHV.valueF[AIndex] - fCYHT_Price_Data.Var2_LLV.ValueF[AIndex]); end else begin tmpV := $FFFFFFFF; end; //**tmpV := Round(tmpV * 100) / 100; Result := tmpV; end; function TRule_CYHT_Price.GetSKValue(AIndex: integer): double; begin Result := fCYHT_Price_Data.Ret_SK_EMA.valueF[AIndex]; end; function TRule_CYHT_Price.GetSDValue(AIndex: integer): double; begin Result := fCYHT_Price_Data.Ret_SD_EMA.valueF[AIndex]; end; function TRule_CYHT_Price.DoGetSDData(AIndex: integer): double; begin Result := fCYHT_Price_Data.Ret_SK_EMA.ValueF[AIndex]; end; function TRule_CYHT_Price.GetParamN1: Word; begin Result := fCYHT_Price_Data.ParamN; end; procedure TRule_CYHT_Price.SetParamN1(const Value: Word); begin if Value > 0 then begin fCYHT_Price_Data.ParamN := Value; end; end; function TRule_CYHT_Price.GetParamEMASK: Word; begin Result := fCYHT_Price_Data.ParamEMASK; end; procedure TRule_CYHT_Price.SetParamEMASK(const Value: Word); begin if Value > 0 then begin fCYHT_Price_Data.ParamEMASK := Value; end; end; function TRule_CYHT_Price.GetParamEMASD: Word; begin Result := fCYHT_Price_Data.ParamEMASD; end; procedure TRule_CYHT_Price.SetParamEMASD(const Value: Word); begin if Value > 0 then begin fCYHT_Price_Data.ParamEMASD := Value; end; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdMessage, IdSMTPBase, IdSMTP, IdSASL, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdIntercept, IdGlobal, Data.Bind.Components, Data.Bind.ObjectScope, REST.Client, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, REST.Authenticator.OAuth, IdContext, IdSASLCollection, IdSASLXOAUTH, IdOAuth2Bearer, Vcl.ExtCtrls, IdPOP3, IniFiles, Globals ; type TEnhancedOAuth2Authenticator = class (TOAuth2Authenticator) private procedure RequestAccessToken; public IDToken : string; procedure ChangeAuthCodeToAccesToken; procedure RefreshAccessTokenIfRequired; end; TAuthType = class of TIdSASL; TProviderInfo = record AuthenticationType : TAuthType; AuthorizationEndpoint : string; AccessTokenEndpoint : string; ClientID : String; ClientSecret : string; ClientAccount : string; Scopes : string; SmtpHost : string; SmtpPort : Integer; PopHost : string; PopPort : Integer; AuthName : string; TLS : TIdUseTLS; end; TForm2 = class(TForm) IdSMTP1: TIdSMTP; IdSSLIOHandlerSocketSMTP: TIdSSLIOHandlerSocketOpenSSL; Memo1: TMemo; IdConnectionInterceptSMTP: TIdConnectionIntercept; btnAuthenticate: TButton; btnSendMsg: TButton; IdHTTPServer1: TIdHTTPServer; rgEmailProviders: TRadioGroup; IdPOP3: TIdPOP3; btnCheckMsg: TButton; IdConnectionPOP: TIdConnectionIntercept; IdSSLIOHandlerSocketPOP: TIdSSLIOHandlerSocketOpenSSL; btnClearAuthToken: TButton; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnAuthenticateClick(Sender: TObject); procedure btnSendMsgClick(Sender: TObject); procedure btnCheckMsgClick(Sender: TObject); procedure btnClearAuthTokenClick(Sender: TObject); procedure IdConnectionInterceptSMTPReceive(ASender: TIdConnectionIntercept; var ABuffer: TIdBytes); procedure IdConnectionInterceptSMTPSend(ASender: TIdConnectionIntercept; var ABuffer: TIdBytes); procedure IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure rgEmailProvidersClick(Sender: TObject); private { Private declarations } OAuth2_Enhanced : TEnhancedOAuth2Authenticator; IniSettings : TIniFile; procedure SetupAuthenticator; public { Public declarations } end; const Providers : array[0..1] of TProviderInfo = ( ( AuthenticationType : TIdOAuth2Bearer; AuthorizationEndpoint : 'https://accounts.google.com/o/oauth2/auth'; AccessTokenEndpoint : 'https://accounts.google.com/o/oauth2/token'; ClientID : google_clientid; ClientSecret : google_clientsecret; ClientAccount : google_clientAccount; // your @gmail.com email address Scopes : 'https://mail.google.com/ openid'; SmtpHost : 'smtp.gmail.com'; SmtpPort : 465; PopHost : 'pop.gmail.com'; PopPort : 995; AuthName : 'Google'; TLS : utUseImplicitTLS ), ( AuthenticationType : TIdSASLXOAuth; AuthorizationEndpoint : 'https://login.live.com/oauth20_authorize.srf'; AccessTokenEndpoint : 'https://login.live.com/oauth20_token.srf'; ClientID : microsoft_clientid; ClientSecret : ''; ClientAccount : microsoft_clientAccount; // your @live.com or @hotmail.com email address Scopes : 'wl.imap offline_access'; SmtpHost : 'smtp.office365.com'; SmtpPort : 587; PopHost : 'outlook.office365.com'; PopPort : 995; AuthName : 'Microsoft'; TLS : utUseImplicitTLS ) ); const clientredirect = 'http://localhost:2132'; var Form2: TForm2; implementation {$R *.dfm} uses System.NetEncoding, System.Net.URLClient, REST.Utils, Winapi.ShellAPI, REST.Consts, REST.Types, System.DateUtils ; const SClientIDNeeded = 'An ClientID is needed before a token can be requested'; SRefreshTokenNeeded = 'An Refresh Token is needed before an Access Token can be requested'; procedure TEnhancedOAuth2Authenticator.RefreshAccessTokenIfRequired; begin if AccessTokenExpiry < now then begin RequestAccessToken; end; end; procedure TEnhancedOAuth2Authenticator.RequestAccessToken; var LClient: TRestClient; LRequest: TRESTRequest; LToken: string; LIntValue: int64; begin // we do need an clientid here, because we want // to send it to the servce and exchange the code into an // access-token. if ClientID = '' then raise EOAuth2Exception.Create(SClientIDNeeded); if RefreshToken = '' then raise EOAuth2Exception.Create(SRefreshTokenNeeded); LClient := TRestClient.Create(AccessTokenEndpoint); try LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it. LRequest.Method := TRESTRequestMethod.rmPOST; LRequest.AddAuthParameter('refresh_token', RefreshToken, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_id', ClientID, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_secret', ClientSecret, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('grant_type', 'refresh_token', TRESTRequestParameterKind.pkGETorPOST); LRequest.Execute; if LRequest.Response.GetSimpleValue('access_token', LToken) then AccessToken := LToken; if LRequest.Response.GetSimpleValue('refresh_token', LToken) then RefreshToken := LToken; if LRequest.Response.GetSimpleValue('id_token', LToken) then IDToken := LToken; // detect token-type. this is important for how using it later if LRequest.Response.GetSimpleValue('token_type', LToken) then TokenType := OAuth2TokenTypeFromString(LToken); // if provided by the service, the field "expires_in" contains // the number of seconds an access-token will be valid if LRequest.Response.GetSimpleValue('expires_in', LToken) then begin LIntValue := StrToIntdef(LToken, -1); if (LIntValue > -1) then AccessTokenExpiry := IncSecond(Now, LIntValue) else AccessTokenExpiry := 0.0; end; // an authentication-code may only be used once. // if we succeeded here and got an access-token, then // we do clear the auth-code as is is not valid anymore // and also not needed anymore. if (AccessToken <> '') then begin AuthCode := ''; end; finally LClient.DisposeOf; end; end; // This function is basically a copy of the ancestor... but is need so we can also get the id_token value. procedure TEnhancedOAuth2Authenticator.ChangeAuthCodeToAccesToken; var LClient: TRestClient; LRequest: TRESTRequest; LToken: string; LIntValue: int64; begin // we do need an authorization-code here, because we want // to send it to the servce and exchange the code into an // access-token. if AuthCode = '' then raise EOAuth2Exception.Create(SAuthorizationCodeNeeded); LClient := TRestClient.Create(AccessTokenEndpoint); try LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it. LRequest.Method := TRESTRequestMethod.rmPOST; // LRequest.Client := LClient; // unnecessary since the client "owns" the request it will assign the client LRequest.AddAuthParameter('code', AuthCode, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_id', ClientID, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_secret', ClientSecret, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('redirect_uri', RedirectionEndpoint, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('grant_type', 'authorization_code', TRESTRequestParameterKind.pkGETorPOST); LRequest.Execute; if LRequest.Response.GetSimpleValue('access_token', LToken) then AccessToken := LToken; if LRequest.Response.GetSimpleValue('refresh_token', LToken) then RefreshToken := LToken; if LRequest.Response.GetSimpleValue('id_token', LToken) then IDToken := LToken; // detect token-type. this is important for how using it later if LRequest.Response.GetSimpleValue('token_type', LToken) then TokenType := OAuth2TokenTypeFromString(LToken); // if provided by the service, the field "expires_in" contains // the number of seconds an access-token will be valid if LRequest.Response.GetSimpleValue('expires_in', LToken) then begin LIntValue := StrToIntdef(LToken, -1); if (LIntValue > -1) then AccessTokenExpiry := IncSecond(Now, LIntValue) else AccessTokenExpiry := 0.0; end; // an authentication-code may only be used once. // if we succeeded here and got an access-token, then // we do clear the auth-code as is is not valid anymore // and also not needed anymore. if (AccessToken <> '') then AuthCode := ''; finally LClient.DisposeOf; end; end; procedure TForm2.FormDestroy(Sender: TObject); begin FreeAndNil(IniSettings); FreeAndNil(OAuth2_Enhanced); end; procedure TForm2.FormCreate(Sender: TObject); var LFilename : string; begin LFilename := ChangeFileExt(ParamStr(0),'.ini'); IniSettings := TIniFile.Create(LFilename); OAuth2_Enhanced := TEnhancedOAuth2Authenticator.Create(nil); SetupAuthenticator; end; procedure TForm2.btnAuthenticateClick(Sender: TObject); var uri : TURI; begin uri := TURI.Create(OAuth2_Enhanced.AuthorizationRequestURI); if rgEmailProviders.ItemIndex = 0 then uri.AddParameter('access_type', 'offline'); // For Google to get refresh_token ShellExecute(Handle, 'open', PChar(uri.ToString), nil, nil, 0 ); end; procedure TForm2.btnSendMsgClick(Sender: TObject); var IdMessage: TIdMessage; xoauthSASL : TIdSASLListEntry; begin IdSMTP1.AuthType := satNone; // if we only have refresh_token or access token has expired // request new access_token to use with request OAuth2_Enhanced.RefreshAccessTokenIfRequired; Memo1.Lines.Add('refresh_token=' + OAuth2_Enhanced.RefreshToken); Memo1.Lines.Add('access_token=' + OAuth2_Enhanced.AccessToken); if OAuth2_Enhanced.AccessToken.Length = 0 then begin Memo1.Lines.Add('Failed to authenticate properly'); Exit; end; IdSMTP1.Host := Providers[rgEmailProviders.ItemIndex].SmtpHost; IdSMTP1.Port := Providers[rgEmailProviders.ItemIndex].SmtpPort; IdSMTP1.UseTLS := Providers[rgEmailProviders.ItemIndex].TLS; xoauthSASL := IdSMTP1.SASLMechanisms.Add; xoauthSASL.SASL := Providers[rgEmailProviders.ItemIndex].AuthenticationType.Create(nil); if xoauthSASL.SASL is TIdOAuth2Bearer then begin TIdOAuth2Bearer(xoauthSASL.SASL).Token := OAuth2_Enhanced.AccessToken; TIdOAuth2Bearer(xoauthSASL.SASL).Host := IdSMTP1.Host; TIdOAuth2Bearer(xoauthSASL.SASL).Port := IdSMTP1.Port; TIdOAuth2Bearer(xoauthSASL.SASL).User := Providers[rgEmailProviders.ItemIndex].ClientAccount; end else if xoauthSASL.SASL is TIdSASLXOAuth then begin TIdSASLXOAuth(xoauthSASL.SASL).Token := OAuth2_Enhanced.AccessToken; TIdSASLXOAuth(xoauthSASL.SASL).User := Providers[rgEmailProviders.ItemIndex].ClientAccount; end; IdSMTP1.Connect; IdSMTP1.AuthType := satSASL; IdSMTP1.Authenticate; IdMessage := TIdMessage.Create(Self); IdMessage.From.Address := Providers[rgEmailProviders.ItemIndex].ClientAccount; IdMessage.From.Name := clientname; IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address; IdMessage.Recipients.Add.Text := clientsendtoaddress; IdMessage.Subject := 'Hello World'; IdMessage.Body.Text := 'Hello Body'; IdSMTP1.Send(IdMessage); IdSMTP1.Disconnect; end; procedure TForm2.btnCheckMsgClick(Sender: TObject); var xoauthSASL : TIdSASLListEntry; msgCount : Integer; begin Memo1.Lines.Add('refresh_token=' + OAuth2_Enhanced.RefreshToken); Memo1.Lines.Add('access_token=' + OAuth2_Enhanced.AccessToken); if OAuth2_Enhanced.AccessToken.Length = 0 then begin Memo1.Lines.Add('Failed to authenticate properly'); Exit; end; IdPOP3.Host := Providers[rgEmailProviders.ItemIndex].PopHost; IdPOP3.Port := Providers[rgEmailProviders.ItemIndex].PopPort; IdPOP3.UseTLS := Providers[rgEmailProviders.ItemIndex].TLS; xoauthSASL := IdPOP3.SASLMechanisms.Add; xoauthSASL.SASL := Providers[rgEmailProviders.ItemIndex].AuthenticationType.Create(nil); if xoauthSASL.SASL is TIdOAuth2Bearer then begin TIdOAuth2Bearer(xoauthSASL.SASL).Token := OAuth2_Enhanced.AccessToken; TIdOAuth2Bearer(xoauthSASL.SASL).Host := IdPOP3.Host; TIdOAuth2Bearer(xoauthSASL.SASL).Port := IdPOP3.Port; TIdOAuth2Bearer(xoauthSASL.SASL).User := Providers[rgEmailProviders.ItemIndex].ClientAccount; end else if xoauthSASL.SASL is TIdSASLXOAuth then begin TIdSASLXOAuth(xoauthSASL.SASL).Token := OAuth2_Enhanced.AccessToken; TIdSASLXOAuth(xoauthSASL.SASL).User := Providers[rgEmailProviders.ItemIndex].ClientAccount; end; IdPOP3.AuthType := patSASL; IdPOP3.Connect; IdPOP3.CAPA; IdPOP3.Login; msgCount := IdPOP3.CheckMessages; ShowMessage(msgCount.ToString + ' Messages available for download'); IdPOP3.Disconnect; end; procedure TForm2.btnClearAuthTokenClick(Sender: TObject); var LTokenName : string; begin // Delete persistent Refresh_token. Note // - This probably should have a logout function called on it // - The token should be stored in an encrypted way ... but this is just a demo. LTokenName := Providers[rgEmailProviders.ItemIndex].AuthName + 'Token'; IniSettings.DeleteKey('Authentication', LTokenName); SetupAuthenticator; end; procedure TForm2.IdConnectionInterceptSMTPReceive(ASender: TIdConnectionIntercept; var ABuffer: TIdBytes); begin Memo1.Lines.Add('R:' + TEncoding.ASCII.GetString(ABuffer)); end; procedure TForm2.IdConnectionInterceptSMTPSend(ASender: TIdConnectionIntercept; var ABuffer: TIdBytes); begin Memo1.Lines.Add('S:' + TEncoding.ASCII.GetString(ABuffer)); end; procedure TForm2.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LCode: string; LURL : TURI; LTokenName : string; begin if ARequestInfo.QueryParams = '' then Exit; LURL := TURI.Create('https://localhost/?' + ARequestInfo.QueryParams); try LCode := LURL.ParameterByName['code']; except Exit; end; OAuth2_Enhanced.AuthCode := LCode; OAuth2_Enhanced.ChangeAuthCodeToAccesToken; LTokenName := Providers[rgEmailProviders.ItemIndex].AuthName + 'Token'; IniSettings.WriteString('Authentication', LTokenName, OAuth2_Enhanced.RefreshToken); Memo1.Lines.Add('Authenticated via OAUTH2'); SetupAuthenticator; end; procedure TForm2.rgEmailProvidersClick(Sender: TObject); begin SetupAuthenticator; end; procedure TForm2.SetupAuthenticator; var LTokenName : string; begin OAuth2_Enhanced.ClientID := Providers[rgEmailProviders.ItemIndex].ClientID; OAuth2_Enhanced.ClientSecret := Providers[rgEmailProviders.ItemIndex].Clientsecret; OAuth2_Enhanced.Scope := Providers[rgEmailProviders.ItemIndex].Scopes; OAuth2_Enhanced.RedirectionEndpoint := clientredirect; OAuth2_Enhanced.AuthorizationEndpoint := Providers[rgEmailProviders.ItemIndex].AuthorizationEndpoint; OAuth2_Enhanced.AccessTokenEndpoint := Providers[rgEmailProviders.ItemIndex].AccessTokenEndpoint; LTokenName := Providers[rgEmailProviders.ItemIndex].AuthName + 'Token'; OAuth2_Enhanced.RefreshToken := IniSettings.ReadString('Authentication', LTokenName, ''); LTokenName := Providers[rgEmailProviders.ItemIndex].AuthName + 'Token'; btnAuthenticate.Enabled := IniSettings.ReadString('Authentication', LTokenName, '').Length = 0; btnClearAuthToken.Enabled := not btnAuthenticate.Enabled; end; end.
unit GX_IdeDeskForm; interface {$UNDEF DoNotCompileThis} {$IFDEF DoNotCompileThis} uses SysUtils, Windows, Messages, Classes, Controls, Forms, Menus, DsgnIntf, IniFiles; type TDesktopForm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FAutoSave: Boolean; FDeskSection: string; FLocked: Boolean; FLoadedFromDesktop: Boolean; FSaveStateNecessary: Boolean; FWindowPlacement: TWindowPlacement; FWindowPlacementDirty: Boolean; procedure MainFormMadeVisible(Sender: TObject); procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; protected FLastLoadedBounds: TRect; procedure DoMainFormShown; dynamic; function LoadDockClients(DeskTop: TMemIniFile; const Section: string; DockSite: TWinControl): Boolean; virtual; procedure LoadDockStream(DeskTop: TMemIniFile; const Section: string; DockSite: TWinControl); virtual; procedure SaveDockClients(DeskTop: TMemIniFile; const Section: string; DockSite: TWinControl); virtual; procedure SaveDockStream(DeskTop: TMemIniFile; const Section: string; DockSite: TWinControl); virtual; procedure UnlockUpdates; dynamic; property SaveStateNecessary: Boolean read FSaveStateNecessary write FSaveStateNecessary; procedure ZoomWindow; virtual; procedure Repaint; override; public constructor Create(AOwner: TComponent); override; procedure EditAction(Action: TEditAction); virtual; procedure GetEditState(var EditState: TEditState); virtual; procedure SaveWindowState(Desktop: TMemIniFile; isProject: Boolean); virtual; procedure LoadWindowState(Desktop: TMemIniFile); virtual; procedure LockUpdates; dynamic; property DeskSection: string read FDeskSection write FDeskSection; property AutoSave: Boolean read FAutoSave write FAutoSave; property LoadedFromDesktop: Boolean read FLoadedFromDesktop; end; TDesktopFormClass = class of TDesktopForm; TInitializeForm = procedure(Ident: TComponent); var InitializeForm: TInitializeForm; RegisterMenu: procedure (AMenu: TMenu) of object = nil; UnregisterMenu: procedure (AMenu: TMenu) of object = nil; RegisterMainFormShown: procedure (Event: TNotifyEvent) = nil; UnregisterMainFormShown: procedure (Event: TNotifyEvent) = nil; GetDockable: function (const DeskSection: string): Boolean = nil; LoadedDesktopFormInstances: TStringList; procedure BeginDesktopUpdate; procedure EndDesktopUpdate; function IsDesktopLocked: Boolean; {$ENDIF DoNotCompileThis} implementation {$R *.dfm} end.
unit atDocumentUnderControlOperation; // Модуль: "w:\quality\test\garant6x\AdapterTest\Operations\atDocumentUnderControlOperation.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatDocumentUnderControlOperation" MUID: (504F1A8B004B) interface uses l3IntfUses , atOperationBase ; type OpType = ( SET_CONTROL , UNSET_CONTROL , INVERT_CONTROL , RESET_CONTROL_STATUS );//OpType TatDocumentUnderControlOperation = class(TatOperationBase) protected procedure ExecuteSelf; override; procedure InitParamList; override; end;//TatDocumentUnderControlOperation implementation uses l3ImplUses , SysUtils , UnderControlUnit , atLogger , DocumentUnit , atControlStatusConverter , TypInfo , l3Base //#UC START# *504F1A8B004Bimpl_uses* //#UC END# *504F1A8B004Bimpl_uses* ; type _EnumType_ = OpType; {$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atEnumConverter.imp.pas} TatOpTypeConverter = class(_atEnumConverter_) public class function Instance: TatOpTypeConverter; {* Метод получения экземпляра синглетона TatOpTypeConverter } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TatOpTypeConverter var g_TatOpTypeConverter: TatOpTypeConverter = nil; {* Экземпляр синглетона TatOpTypeConverter } procedure TatOpTypeConverterFree; {* Метод освобождения экземпляра синглетона TatOpTypeConverter } begin l3Free(g_TatOpTypeConverter); end;//TatOpTypeConverterFree {$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atEnumConverter.imp.pas} class function TatOpTypeConverter.Instance: TatOpTypeConverter; {* Метод получения экземпляра синглетона TatOpTypeConverter } begin if (g_TatOpTypeConverter = nil) then begin l3System.AddExitProc(TatOpTypeConverterFree); g_TatOpTypeConverter := Create; end; Result := g_TatOpTypeConverter; end;//TatOpTypeConverter.Instance class function TatOpTypeConverter.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TatOpTypeConverter <> nil; end;//TatOpTypeConverter.Exists procedure TatDocumentUnderControlOperation.ExecuteSelf; //#UC START# *48089F460352_504F1A8B004B_var* var l_OpTypeStr, l_Str : String; l_OpType : OpType; l_Doc : IDocument; l_Controllable : IControllable; //#UC END# *48089F460352_504F1A8B004B_var* begin //#UC START# *48089F460352_504F1A8B004B_impl* ExecutionContext.GblAdapterWorker.ControlManager.UpdateStatus(false); l_OpTypeStr := Parameters['op_type'].AsStr; try l_OpType := TatOpTypeConverter.Instance.ToValueCI(l_OpTypeStr); except on ex : EConvertError do begin Logger.Error('Неизвестная операция: %s', [l_OpTypeStr]); Exit; end; end; l_Doc := ExecutionContext.UserWorkContext.CurrDoc; if l_Doc = nil then begin Logger.Error('Нет открытого документа'); Exit; end; l_Controllable := l_Doc as IControllable; if l_Controllable.GetControlled then Logger.Info('Обрабатываем документ %d, он на контроле и его статус "%s"', [l_Doc.GetInternalId, TatControlStatusConverter.Instance.ToValues(l_Controllable.GetControlStatus, '; ')]) else Logger.Info('Обрабатываем документ %d, он не на контроле', [l_Doc.GetInternalId]); with l_Controllable do begin case l_OpType of SET_CONTROL: begin if NOT GetCanSetToControl then begin Logger.Error('Нельзя ставить на контроль!'); Exit; end; Logger.Info('Ставии документ на контроль'); if NOT GetControlled then SetControlled(true); end; UNSET_CONTROL: begin Logger.Info('Снимаем документ с контроля'); if GetControlled then SetControlled(false); end; INVERT_CONTROL: begin if (NOT GetControlled) AND (NOT GetCanSetToControl) then begin Logger.Error('Нельзя ставить на контроль!'); Exit; end; Logger.Info('Изменяем признак контроля на противоположный'); SetControlled(NOT GetControlled); end; RESET_CONTROL_STATUS: begin Logger.Info('Сбрасываем статус измененности'); if GetControlled then ResetControlStatus; end; end; // if GetControlled then l_Str := '' else l_Str := 'не '; Logger.Info('Документ в состоянии "%s" и его статус "%s"', [l_Str + 'на контроле', TatControlStatusConverter.Instance.ToValues(GetControlStatus, '; ')]); end; //#UC END# *48089F460352_504F1A8B004B_impl* end;//TatDocumentUnderControlOperation.ExecuteSelf procedure TatDocumentUnderControlOperation.InitParamList; //#UC START# *48089F3701B4_504F1A8B004B_var* //#UC END# *48089F3701B4_504F1A8B004B_var* begin //#UC START# *48089F3701B4_504F1A8B004B_impl* inherited; with f_ParamList do begin Add( ParamType.Create('op_type', 'Что делать') ); end; //#UC END# *48089F3701B4_504F1A8B004B_impl* end;//TatDocumentUnderControlOperation.InitParamList initialization {$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atEnumConverter.imp.pas} end.
unit UCoreObjects; { Copyright (c) 2018 by PascalCoin Project Contains common types for Core module. Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. Acknowledgements: Herman Schoenfeld <herman@sphere10.com>: unit creator } {$mode delphi} interface uses Classes, SysUtils, UCrypto, UAccounts, UBlockChain, UWallet, UCommon, Generics.Collections, Generics.Defaults; type { TBalanceSummary } TBalanceSummary = record TotalPASC : UInt64; TotalPASA : Cardinal; end; { TExecuteOperationsModel } TExecuteOperationsModel = class(TComponent) public type { TExecuteOperationType } TExecuteOperationType = (omtAccount, omtSendPasc, omtChangeKey, omtTransferAccount, omtChangeAccountPrivateKey, omtAddKey, omtEnlistAccountForSale); { TPayloadEncryptionMode } TPayloadEncryptionMode = (akaEncryptWithSender, akaEncryptWithReceiver, akaEncryptWithPassword, akaNotEncrypt); { TOperationSigningMode } TOperationSigningMode = (akaPrimary, akaSecondary); { TChangeKeyMode } TChangeKeyMode = (akaTransferAccountOwnership, akaChangeAccountPrivateKey); { TSendPASCMode } TSendPASCMode = (akaAllBalance, akaSpecifiedAmount); { TAccountSaleMode } TAccountSaleMode = (akaPublicSale, akaPrivateSale); { TOperationExecuteResultHandler } TOperationExecuteResultHandler = procedure(const ASourceAccount: TAccount; AOpType: TExecuteOperationType; const AOpText: ansistring; Result: boolean; const Message: ansistring) of object; { TAccountModel } TAccountModel = class(TComponent) public SelectedAccounts: TArray<TAccount>; end; { TSendPASCModel } TSendPASCModel = class(TComponent) public SingleAmountToSend: int64; DestinationAccount: TAccount; SendPASCMode: TSendPASCMode; end; { TChangeKeyModel } TChangeKeyModel = class(TComponent) public ChangeKeyMode: TChangeKeyMode; end; { TTransferAccountModel } TTransferAccountModel = class(TComponent) public AccountKey: TAccountKey; end; { TChangeAccountPrivateKeyModel } TChangeAccountPrivateKeyModel = class(TComponent) public SelectedIndex: integer; NewWalletKey: TWalletKey; end; { TWIZEnlistAccountForSaleModel } TEnlistAccountForSaleModel = class(TComponent) public SalePrice: int64; NewOwnerPublicKey: TAccountKey; LockedUntilBlock: cardinal; SellerAccount: TAccount; AccountSaleMode: TAccountSaleMode; end; { TFeeModel } TFeeModel = class(TComponent) public DefaultFee, SingleOperationFee: int64; end; { TSignerModel } TSignerModel = class(TComponent) public OperationSigningMode: TOperationSigningMode; SignerAccount: TAccount; SignerCandidates: TArray<TAccount>; SelectedIndex: integer; end; { TPayloadModel } TPayloadModel = class(TComponent) public HasPayload: boolean; Content, Password: string; PayloadEncryptionMode: TPayloadEncryptionMode; EncodedBytes: TRawBytes; end; private FExecuteOperationType: TExecuteOperationType; FAccount: TAccountModel; FSendPASC: TSendPASCModel; FChangeKey: TChangeKeyModel; FTransferAccount: TTransferAccountModel; FChangeAccountPrivateKey: TChangeAccountPrivateKeyModel; FEnlistAccountForSale: TEnlistAccountForSaleModel; FFee: TFeeModel; FSigner: TSignerModel; FPayload: TPayloadModel; public constructor Create(AOwner: TComponent; AType: TExecuteOperationType); overload; property ExecuteOperationType: TExecuteOperationType read FExecuteOperationType; property Account: TAccountModel read FAccount; property SendPASC: TSendPASCModel read FSendPASC; property ChangeKey: TChangeKeyModel read FChangeKey; property TransferAccount: TTransferAccountModel read FTransferAccount; property ChangeAccountPrivateKey: TChangeAccountPrivateKeyModel read FChangeAccountPrivateKey; property EnlistAccountForSale: TEnlistAccountForSaleModel read FEnlistAccountForSale; property Fee: TFeeModel read FFee; property Signer: TSignerModel read FSigner; property Payload: TPayloadModel read FPayload; end; const CT_BalanceSummary_Nil : TBalanceSummary = ( TotalPASC : 0; TotalPASA : 0; ); implementation constructor TExecuteOperationsModel.Create(AOwner: TComponent; AType: TExecuteOperationsModel.TExecuteOperationType); begin inherited Create(AOwner); FExecuteOperationType := AType; FAccount := TAccountModel.Create(Self); FSendPASC := TSendPASCModel.Create(Self); FChangeKey := TChangeKeyModel.Create(Self); FTransferAccount := TTransferAccountModel.Create(Self); FChangeAccountPrivateKey := TChangeAccountPrivateKeyModel.Create(Self); FEnlistAccountForSale := TEnlistAccountForSaleModel.Create(Self); FFee := TFeeModel.Create(Self); FSigner := TSignerModel.Create(Self); FPayload := TPayloadModel.Create(Self); end; end.
unit MFSL.Master; interface uses SysUtils, Classes, MSFL; type IMasterInfo = interface ['{CD53C1EF-8933-4BCE-8862-4EAED7425A3B}'] function GetFileName: string; end; TAbstractMasterInfo = class abstract(TInterfacedObject, IMasterInfo) protected class function GetPrefix: string; virtual; abstract; class function GetSuffix: string; virtual; abstract; public constructor Create(Stream: TStream); virtual; abstract; function GetFileName: string; virtual; end; TMasterInfo = class(TAbstractMasterInfo) private RecordInfo: TMasterRecordInfo; protected class function GetPrefix: string; override; class function GetSuffix: string; override; public constructor Create(Stream: TStream); override; end; implementation { TAbstractMasterInfo } function TAbstractMasterInfo.GetFileName: string; begin Result := GetPrefix + GetSuffix; end; { TMasterInfo } constructor TMasterInfo.Create(Stream: TStream); begin Stream.Read(RecordInfo, SizeOf(RecordInfo)); case RecordInfo.CT_V2_8_Flag of 42: ; // autorun 89: ; // v28 end; end; class function TMasterInfo.GetPrefix: string; begin Result := 'F'; end; class function TMasterInfo.GetSuffix: string; begin Result := '.DAT'; end; end.
unit souConverterForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, k2TagGen, l3Interfaces, l3Filer, StdCtrls, ComCtrls, ddCmdLineUtils, AppEvnts; type TsouCmdLine = class(TddBaseCmdLine) private f_DestFolder: string; f_SrcFolder: string; f_SubDir: Boolean; protected procedure Init; override; procedure SetDefault; override; end; TsouMainForm = class(TForm) LabelFile: TLabel; LabelFOlder: TLabel; ProgressBar: TProgressBar; ProgressLabel: TLabel; ApplicationEvents1: TApplicationEvents; procedure FormDestroy(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); private f_Abort: Boolean; f_CmdLine: TsouCmdLine; f_InFiler: Tl3DOSFiler; f_OutFiler: Tl3DOSFiler; f_Reader: Tk2TagGenerator; procedure ConvertFiles; procedure Dowork; function GetAutolinkFileName: string; function GetKTFileName: string; function GetMisspelsFileName: string; function pm_GetgDestinationFolder: String; function pm_GetgSourceFolder: string; function pm_GetgWithSubDirs: Boolean; procedure UpdateProgress(Sender: TObject; aTotalPercent: Integer); procedure WrongWordFound(aTopicID: Integer; aWrongWord: Il3CString); { Private declarations } public property gDestinationFolder: String read pm_GetgDestinationFolder; property gSourceFolder: string read pm_GetgSourceFolder; property gWithSubDirs: Boolean read pm_GetgWithSubDirs; { Public declarations } end; procedure SetDefault; var SouMainForm: TsouMainForm; implementation uses ddNsrc_r, ddNsrc_w, ddSpellCheckFilter, ddKTExtractor, ddAutoLinkFilter, dd_lcMisspellFilter, ddFileIterator, ddProgressObj, l3Base, l3FileUtils, l3Types, ddUtils, dt_Serv, dt_Const, ddHTInit, ddCmdLineDlg, EvSimpleTextPainter; {$R *.dfm} procedure SetDefault; begin // TODO -cMM: TddCmdLine.SetDefault default body inserted end; procedure TsouMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(f_CmdLine) end; procedure TsouMainForm.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin Application.OnIdle:= nil; if f_CmdLine.NeedHelp then begin ShowCmdHelpMessage(Application.Title, f_CmdLine.HelpText); Application.Terminate; end else DoWork; end; procedure TsouMainForm.FormCreate(Sender: TObject); begin f_CmdLine:= TsouCmdLine.Create(true); end; procedure TsouMainForm.ConvertFiles; var l_Filer : TevDOSFiler; l_Filer2: TevDOSFiler; l_Files: TddFileIterator; i: Integer; l_Start: TDateTime; l_Prg: TddProgressObject; l_Gen: Tk2TagGenerator; l_ExMasks: TStrings; procedure BuildPipe; begin l_Gen:= nil; TddNSRCGenerator.SetTo(l_Gen); TddNSRCGenerator(l_Gen).Filer:= l_Filer2; TevSimpleTextPainter.SetTo(l_Gen); TddKTExtractorFilter.SetTo(l_Gen, GetKTFileName); TddAutoLinkFilter.SetTo(l_Gen, nil, GetAutolinkFileName); TddSpellCheckFilter.SetTo(l_Gen{, WrongWordFound}); Tdd_lcMisspellFilter.SetTo(l_Gen, GetMisspelsFileName); TCustomNSRCReader.SetTo(l_Gen); TCustomNSRCReader(l_Gen).Filer:= l_Filer; end; function lp_WorkFile(const FileName: String): Boolean; var l_FileName: String; l_GZFilename: string; begin l3System.Msg2Log(FileName); l_GZFilename := ExtractFileName(FileName); labelFile.Caption:= l_GZFilename; l_Filer.Filename := Filename; l_FileName:= ConcatDirName(gDestinationFolder, ChangeFileExt(l_GZFilename, '.nsr')); l_Filer2.FileName:= l_FileName; try try TCustomNSRCReader(l_Gen).Execute; except on E: Exception do begin l3System.Msg2Log('ОШИБКА ПРИ ЧТЕНИИ!'); l_Filer.Close; l_Filer2.Close; FreeAndNil(l_Gen); BuildPipe; end; end; except on E: Exception do begin l3System.Exception2Log(E); end; end; labelFile.Caption:= ''; Result:= not f_Abort; end; // lp_WorkFile begin ForceDirectories(gDestinationFolder); l_Files:= TddFileIterator.Make(gSourceFolder, '*.nsr', nil, gWithSubDirs); try l_Files.LoadFiles; if not l_Files.Empty then begin l_Filer:= TevDOSFiler.Create; try l_Filer.Mode:= l3_fmRead; l_Filer2:= TevDOSFiler.Create; try l_Filer2.Mode:= l3_fmFullShareCreateReadWrite; l_Start:= Now; try BuildPipe; LabelFolder.Caption:= gSourceFolder; l_Prg:= TddProgressObject.Create(nil); try l_Prg.OnUpdate:= UpdateProgress; l_Prg.Start(l_Files.FileList.Count); l3System.Msg2Log('Начато преобразование %d файлов', [l_Files.FileList.Count]); f_Abort:= False; l_Filer.NeedProcessMessages:= True; l_Filer.Indicator.NeedProgressProc:= True; l_Filer.Indicator.OnProgressProc:= l_Prg.ProcessUpdate; for i:= 0 to l_Files.FileList.Count-1 do begin if f_Abort then break; lp_WorkFile(l_Files.FileList[i]); l_Prg.ProcessUpdate(i); end; // for i finally l_Prg.Stop; l3System.Msg2Log('Преобразование закончено за '+ CalcElapsedTime(l_Start, Now)); l3Free(l_Prg); end; LabelFolder.Caption:= ''; finally FreeAndNil(l_Gen); end; finally l3Free(l_Filer2); end; finally l3Free(l_Filer); end; end; finally l3Free(l_Files); end; end; procedure TsouMainForm.Dowork; var l_Ok: Boolean; begin with f_CmdLine do begin if BaseRoot <> '' then l_Ok:= InitBaseEngine(BaseRoot, User, Password) else l_ok:= InitBaseEngine(serverIP, ServerPort, User, Password); if l_Ok then try ConvertFiles; finally DoneClientBaseEngine; end; Close; end; end; procedure TsouMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin f_Abort:= True; end; function TsouMainForm.GetAutolinkFileName: string; begin if GlobalHtServer <> nil then Result := ConcatDirName(GlobalHtServer.FamilyTbl.FamilyPath(CurrentFamily), 'autolink.dat') else Result:= ''; end; function TsouMainForm.GetKTFileName: string; begin if GlobalHtServer <> nil then Result := ConcatDirName(GlobalHtServer.FamilyTbl.FamilyPath(CurrentFamily), 'kthemes.zip') else Result:= ''; end; function TsouMainForm.GetMisspelsFileName: string; begin Result := GetAppFolderFileName('TypicalErrors.txt'); end; function TsouMainForm.pm_GetgDestinationFolder: String; begin Result := f_CmdLine.f_DestFolder; if Result = '' then Result:= ConcatDirname(gSourceFolder, 'result'); end; function TsouMainForm.pm_GetgSourceFolder: string; begin Result := f_CmdLine.f_SrcFolder; end; function TsouMainForm.pm_GetgWithSubDirs: Boolean; begin Result := f_CmdLine.f_SubDir; end; procedure TsouMainForm.UpdateProgress(Sender: TObject; aTotalPercent: Integer); begin ProgressBar.Position:= aTotalPercent; ProgressLabel.Caption:= 'До окончания осталось: '+ TddProgressObject(Sender).TotalRemainingTimeAsString; Application.ProcessMessages; end; procedure TsouMainForm.WrongWordFound(aTopicID: Integer; aWrongWord: Il3CString); begin end; procedure TsouCmdLine.Init; begin inherited Init; AddFolder('src', 'Папка с исходными файлами', '', f_SrcFolder); AddString('dest', 'Папка для обработанных файлов', '', f_DestFolder); AddBool('r', 'Обрабатывать подпапки', '', f_SubDir); end; procedure TsouCmdLine.SetDefault; begin inherited SetDefault; f_SubDir:= False; f_DestFolder:= ''; f_SrcFolder:= ''; end; end.
unit ConnectedBlock; interface uses Kernel, Protocol, Circuits, Collection, BackupInterfaces, TransportInterfaces; type TCargoArray = array[TCargoKind] of ICargoPoint; type TConnectedBlock = class( TBlock ) protected constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override; public destructor Destroy; override; private fRoads : TCollection; fCargo : TCargoArray; protected procedure SetCargoValue( CargoKind : TCargoKind; CargoValue : single ); override; procedure DelCargoValue( CargoKind : TCargoKind ); override; function GetCircuits( CircuitId : TCircuitId ) : TCollection; override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses MathUtils; constructor TConnectedBlock.Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); begin inherited; fRoads := TCollection.Create( 0, rkUse ); end; destructor TConnectedBlock.Destroy; var kind : TCargoKind; begin for kind := low(kind) to high(kind) do DelCargoValue( kind ); fRoads.Free; inherited; end; procedure TConnectedBlock.SetCargoValue( CargoKind : TCargoKind; CargoValue : single ); var CargoSystem : ICargoSystem; CargoLayer : ICargoLayer; value : TCargoValue; begin if fCargo[CargoKind] = nil then begin CargoSystem := Facility.Town.RoadHandler.GetCargoSystem( cirRoads ); CargoLayer := CargoSystem.GetLayer( ord(CargoKind) ); fCargo[CargoKind] := CargoLayer.CreatePoint( Facility.XPos, Facility.YPos ); end; value := min( high(value), round(CargoValue) ); fCargo[CargoKind].setValue( value ); end; procedure TConnectedBlock.DelCargoValue( CargoKind : TCargoKind ); var CargoSystem : ICargoSystem; CargoLayer : ICargoLayer; begin if fCargo[CargoKind] <> nil then begin CargoSystem := Facility.Town.RoadHandler.GetCargoSystem( cirRoads ); CargoLayer := CargoSystem.GetLayer( ord(CargoKind) ); CargoLayer.DelPoint( Facility.XPos, Facility.YPos ); end; end; function TConnectedBlock.GetCircuits( CircuitId : TCircuitId ) : TCollection; begin if CircuitId = cirRoads then result := fRoads else result := nil; end; procedure TConnectedBlock.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'NearRoads', fRoads, nil ); if fRoads = nil then fRoads := TCollection.Create( 0, rkUse ); end; procedure TConnectedBlock.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObject( 'NearRoads', nil ); //Writer.WriteObject( 'NearRoads', fRoads ); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TConnectedBlock ); end; end.
unit unitPoly; interface uses Types; type TPoly = class(TObject) private { Private declarations } public { Public declarations } p1, p2, p3, p4: TPoint; priority: integer; trigger: string; caption : String; constructor Create(ncaption: String); end; implementation constructor TPoly.Create(ncaption: String); begin inherited Create; caption := ncaption; priority := 0; trigger := ''; p1.X := 0; p1.Y := 0; p2.X := 0; p2.Y := 0; p3.X := 0; p3.Y := 0; p4.X := 0; p4.Y := 0; end; end.
unit JunoApi4Delphi.Interfaces; interface uses System.Generics.Collections, Document, EventType, Webhook, CompanyType, Banks, Charge, Data.DB; type iDataService = interface; iChargeService = interface; iBalanceService = interface; iPaymentService = interface; iDocumentService = interface; iTransferService = interface; iCreditCardService = interface; iBillPaymentService = interface; iCredentialsService = interface; iNotificationService = interface; iDigitalAccountService = interface; iPlans = interface; iSubscriptions = interface; iJunoApi4DelphiConig = interface function ClientId(Value : String) : iJunoApi4DelphiConig; overload; function ClientId : String; overload; function ClientSecret(Value : String) : iJunoApi4DelphiConig; overload; function ClientSecret : String; overload; function ResourceToken(Value : String) : iJunoApi4DelphiConig; overload; function ResourceToken : String; overload; function PublicToken(Value : String) : iJunoApi4DelphiConig; overload; function PublicToken : String; overload; function TokenTimeout : Integer; function AuthorizationEndpoint : String; function ResourceEndpoint : String; function Sandbox : iJunoApi4DelphiConig; function Production :iJunoApi4DelphiConig; end; iEnvironment = interface function AuthorizationServerEndpoint : String; function ResourceServerEndpoint : String; end; iAuthorizationService = interface function Token : String; function AuthorizationHeader : String; end; iJunoApi4DelphiResources = interface function DataService : iDataService; function ChargeService : iChargeService; function BalanceService : iBalanceService; function PaymentService : iPaymentService; function DocumentService : iDocumentService; function TransferService : iTransferService; function CreditCardService : iCreditCardService; function BillPaymentService : iBillPaymentService; function CredentialsService : iCredentialsService; function NotificationService : iNotificationService; function AuthorizationService : iAuthorizationService; function DigitalAccountService : iDigitalAccountService; function PlansService : iPlans; function Subscriptions : iSubscriptions; end; iJunoApi4DelphiManager = interface function ContentTypeHeader : String; function ContentEncodingHeader : String; function XResourceToken : String; function XApiVersion : String; function Config : iJunoApi4DelphiConig; function Resources : iJunoApi4DelphiResources; end; iDataService = interface function Banks : TObjectList<TBanks>; function CompanyTypes : String; function BusinessAreas : String; end; iBalanceService = interface function Balance : String; end; iPaymentService = interface function Payment : String; function RefundPayment : String; function Capture : String; end; iDocumentService = interface function Document : String; function ListDocument : TObjectList<TDocument>; function UploadFile : String; function UploadStream : String; end; iTransferService = interface end; iCreditCardService = interface function Tokenize : String; end; iBillPaymentService = interface function RegisterBillPayment : String; end; iCredentialsService = interface function PublicCredentials : String; end; iNotificationService = interface function ListaEventTypes : TObjectList<TEventTypes>; function ListaWebhooks : TObjectList<TWebhook>; function CreateWebhook : String; end; iChargeService = interface function CreateCharge : iChargeService; function ChargeDescription(Value : String) : iChargeService; function ChargeReferences(Value : String) : iChargeService; function ChargeAmount(Value : Double) : iChargeService; function ChargeDueDate(Value : String) : iChargeService; function ChargeInstallments(Value : Integer) : iChargeService; function ChargeMaxOverdueDays(Value : Integer) : iChargeService; function ChargeFine(Value : Integer) : iChargeService; function ChargeInterest(Value : String) : iChargeService; function ChargeDiscountAmount(Value : String) : iChargeService; function ChargeDiscountDays(Value : Integer) : iChargeService; function ChargePaymentTypes(Value : String) : iChargeService; function ChargePaymentAdvance(Value : Boolean) : iChargeService; function BillingName(Value : String) : iChargeService; function BillingDocument(Value : String) : iChargeService; function BillingEmail(Value : String) : iChargeService; function BillingSecondaryEmail(Value : String) : iChargeService; function BillingPhone(Value : String) : iChargeService; function BillingBirthDate(Value : String) : iChargeService; function BillingNotify(Value : Boolean) : iChargeService; function &End : String; function ListCharge : iChargeService; overload; function GetCharge : String; function createdOnStart(Value : String) : iChargeService; overload; function createdOnStart : String;overload; function createdOnEnd(Value : String) : iChargeService; overload; function createdOnEnd : String; overload; function dueDateStart(Value : String) : iChargeService; overload; function dueDateStart : String; overload; function paymentDateStart(Value : String) : iChargeService; overload; function paymentDateStart : String; overload; function paymentDateEnd(Value : String) : iChargeService; overload; function paymentDateEnd : String; overload; function showUnarchived(Value : Boolean) : iChargeService; overload; function showUnarchived : Boolean; overload; function showArchived(Value : Boolean) : iChargeService; overload; function showArchived : Boolean; overload; function showDue(Value : Boolean) : iChargeService; overload; function showDue : Boolean; overload; function showNotDue(Value : Boolean) : iChargeService; overload; function showNotDue : Boolean; overload; function showPaid(Value : Boolean) : iChargeService; overload; function showPaid : Boolean; overload; function showNotPaid(Value : Boolean) : iChargeService; overload; function showNotPaid : Boolean; overload; function showCancelled(Value : Boolean) : iChargeService; overload; function showCancelled : Boolean; overload; function showNotCancelled(Value : Boolean) : iChargeService; overload; function showNotCancelled : Boolean; overload; function showManualReconciliation(Value : Boolean) : iChargeService; overload; function showManualReconciliation : Boolean; overload; function showNotManualReconciliation(Value : Boolean) : iChargeService; overload; function showNotManualReconciliation : Boolean; overload; function showNotFailed(Value : Boolean) : iChargeService; overload; function showNotFailed : Boolean; overload; function orderBy(Value : String) : iChargeService; overload; function orderBy : String; overload; function orderAsc(Value : Boolean) : iChargeService; overload; function orderAsc : Boolean; overload; function pageSize(Value : Integer) : iChargeService; overload; function pageSize : Integer; overload; function page(Value : Integer) : iChargeService; overload; function page : Integer; overload; function firstObjectId(Value : String) : iChargeService; overload; function firstObjectId : String; overload; function firstValue(Value : String) : iChargeService; overload; function firstValue : String; overload; function lastObjectId(Value : String) : iChargeService; overload; function lastObjectId : String; overload; function lastValue(Value : String) : iChargeService; overload; function lastValue : String; overload; function &ListEnd : String; function GetFirstCharge(Value : String) : String; function CancelCharge(Value : String) : String; function UpdateSplit(Value : String) : String; end; iDigitalAccountService = interface end; iCardHash = interface function CardNumber(Value : String) : iCardHash; function holderName(Value : String) : iCardHash; function securityCode(Value : String) : iCardHash; function expirationMonth(Value : String) : iCardHash; function expirationYear(Value : String) : iCardHash; function cardHash : String; end; iPlans = interface function CratePlan : iPlans; function Name(Value : String) : iPlans; function Amount(Value : Double) : iPlans; function EndCreatePlan(Value : TDataSet) : iPlans; overload; function EndCreatePlan : String; overload; function GetPlans(Value : TDataSet) : iPlans; overload; function GetPlans : String; overload; function GetPlan(Value : String; dtValue : TDataSet): iPlans; overload; function GetPlan(Value : String) : String; overload; function DeactivePlan(Value : String; dtValue : TDataSet) : iPlans; overload; function DeactivePlan(Value : String) : String; overload; function ActivePlan(Value : String; dtValue : TDataSet) : iPlans; overload; function ActivePlan(Value : String) : String; overload; end; iBilling<T> = interface function Email(Value : String) : iBilling<T>; overload; function Email : String; overload; function Name(Value : String) : iBilling<T>; overload; function Name : String; overload; function Document(Value : String) : iBilling<T>; overload; function Document : String; overload; function Street(Value : String) : iBilling<T>; overload; function Street : String; overload; function Number(Value : String) : iBilling<T>; overload; function Number : String; overload; function Complement(Value : String) : iBilling<T>; overload; function Complement : String; overload; function Neighborhood(Value : String) : iBilling<T>; overload; function Neighborhood : String; overload; function City(Value : String) : iBilling<T>; overload; function City : String; overload; function State(Value : String) : iBilling<T>; overload; function State : String; overload; function PostCode(Value : String) : iBilling<T>; overload; function PostCode : String; overload; function &End : T; end; iSplit<T> = interface function recipientToken(Value : String) : iSplit<T>; overload; function recipientToken : String; overload; function amount(Value : Double) : iSplit<T>; overload; function amount : Double; overload; function percentage(Value : Double) : iSplit<T>; overload; function percentage : Double; overload; function amountRemainder(Value : Boolean) : iSplit<T>; overload; function amountRemainder : Boolean; overload; function chargeFee(Value : Boolean) : iSplit<T>; overload; function chargeFee : Boolean; overload; function &End : T; end; iSubscriptions = interface function CreateSubscription : iSubscriptions; function DueDay(Value : Integer) : iSubscriptions; function PlanId(Value : String) : iSubscriptions; function ChargeDescription(Value : String): iSubscriptions; function CreditCardDetails(Value : String) : iSubscriptions; function Billing : iBilling<iSubscriptions>; function Split : iSplit<iSubscriptions>; function &End(Value : TDataSet) : iSubscriptions; overload; function &End : String; overload; function GetSubscriptions(Value : TDataSet) : iSubscriptions; overload; function GetSubscriptions : String; overload; function GetSubscription(Value : String; dtValue : TDataSet) : iSubscriptions; overload; function GetSubscription(Value : String) : String; overload; function DeactiveSubscription(Value : String) : String; function ActiveSubscription(Value : String) : String; function CancelationSubscription(Value : String) : String; end; implementation end.
unit StockInstantData_Get_Sina; interface uses define_stock_quotes_instant, UtilsHttp, win.iobuffer, BaseApp; type PInstantArray = ^TInstantArray; TInstantArray = record Data: array[0..10 - 1] of PRT_InstantQuote; end; procedure DataGet_InstantArray_Sina(App: TBaseApp; AInstantArray: PInstantArray; AHttpClientSession: PHttpClientSession; AHttpData: PIOBuffer); implementation uses Sysutils, Classes, Define_Price, define_dealItem, define_datasrc, Define_DealStore_File, DB_DealItem, DB_DealItem_Load; const // 及时报价 BaseSinaInstantUrl1 = 'http://hq.sinajs.cn/list='; // + sh601003,sh601001 // 分钟线 BaseSinaRealMinuteUrl1 = 'http://vip.stock.finance.sina.com.cn/quotes_service/view/vML_DataList.php?'; //'asc=j&symbol=sh600100&num=240'; function DataParse_Instant_Sina(AInstant: PRT_InstantQuote; AResultData: string): Boolean; var tmpRows: TStringList; tmpRowData: string; tmpRowStrs: TStringList; i: integer; begin Result := False; tmpRows := TStringList.Create; tmpRowStrs := TStringList.Create; try tmpRows.Text := AResultData; for i := 0 to tmpRows.Count - 1 do begin tmpRowData := Trim(tmpRows[i]); if '' <> tmpRowData then begin tmpRowStrs.text := StringReplace(tmpRowData, ',', #13#10, [rfReplaceAll]); if (31 < tmpRowStrs.Count) and (35 > tmpRowStrs.Count) then begin // 33 if 0 < Pos(AInstant.item.scode, tmpRowStrs[0]) then begin trySetRTPricePack(@AInstant.PriceRange.PriceOpen, tmpRowStrs[1]); trySetRTPricePack(@AInstant.PriceRange.PriceClose, tmpRowStrs[3]); trySetRTPricePack(@AInstant.PriceRange.PriceHigh, tmpRowStrs[4]); trySetRTPricePack(@AInstant.PriceRange.PriceLow, tmpRowStrs[5]); AInstant.Volume := tryGetInt64Value(tmpRowStrs[8]); AInstant.Amount := tryGetInt64Value(tmpRowStrs[9]); // 2008-01-11 //AInstant.Day := Trunc(StrToDateDef(tmpRowStrs[30], 0)); end; end; end; end; finally tmpRows.Free; tmpRowStrs.Free; end; end; procedure DataGet_Instant_Sina(App: TBaseApp; AInstant: PRT_InstantQuote; ANetSession: PHttpClientSession; AHttpData: PIOBuffer); var tmpUrl: string; tmpRetData: PIOBuffer; tmpHttpParse: THttpHeadParseSession; begin tmpUrl := BaseSinaInstantUrl1 + GetStockCode_Sina(AInstant.Item); tmpRetData := GetHttpUrlData(tmpUrl, ANetSession, AHttpData); if nil <> tmpRetData then begin try FillChar(tmpHttpParse, SizeOf(tmpHttpParse), 0); HttpBufferHeader_Parser(tmpRetData, @tmpHttpParse); if 200 = tmpHttpParse.RetCode then begin if 0 < tmpHttpParse.HeadEndPos then begin // parse result data DataParse_Instant_Sina(AInstant, PAnsiChar(@PIOBufferX(tmpRetData).Data[tmpHttpParse.HeadEndPos + 1])); end; end; finally CheckInIOBuffer(tmpRetData); end; end; end; function DataParse_InstantArray_Sina(AInstantArray: PInstantArray; AResultData: string): Boolean; var tmpRows: TStringList; tmpRowData: string; tmpRowStrs: TStringList; i: integer; j: integer; tmpInstant: PRT_InstantQuote; begin Result := False; tmpRows := TStringList.Create; tmpRowStrs := TStringList.Create; try tmpRows.Text := AResultData; for i := 0 to tmpRows.Count - 1 do begin tmpRowData := Trim(tmpRows[i]); if '' <> tmpRowData then begin tmpRowStrs.text := StringReplace(tmpRowData, ',', #13#10, [rfReplaceAll]); if (31 < tmpRowStrs.Count) and (35 > tmpRowStrs.Count) then begin tmpInstant := nil; for j := Low(AInstantArray.Data) to High(AInstantArray.Data) do begin if nil <> AInstantArray.Data[j] then begin if nil <> AInstantArray.Data[j].item then begin if 0 < Pos(AInstantArray.Data[j].item.scode, tmpRowStrs[0]) then begin tmpInstant := AInstantArray.Data[j]; end; end; end; end; // 33 if nil <> tmpInstant then begin if '' = tmpInstant.Item.Name then begin tmpRowData := tmpRowStrs[0]; j := Pos('=', tmpRowData); if j > 0 then begin tmpRowData := Copy(tmpRowData, j + 1, maxint); tmpRowData := StringReplace(tmpRowData, '"', '', [rfReplaceAll]); tmpInstant.Item.Name := tmpRowData; end; end; trySetRTPricePack(@tmpInstant.PriceRange.PriceOpen, tmpRowStrs[1]); trySetRTPricePack(@tmpInstant.PriceRange.PriceClose, tmpRowStrs[3]); trySetRTPricePack(@tmpInstant.PriceRange.PriceHigh, tmpRowStrs[4]); trySetRTPricePack(@tmpInstant.PriceRange.PriceLow, tmpRowStrs[5]); tmpInstant.Volume := tryGetInt64Value(tmpRowStrs[8]); tmpInstant.Amount := tryGetInt64Value(tmpRowStrs[9]); // 2008-01-11 //AInstant.Day := Trunc(StrToDateDef(tmpRowStrs[30], 0)); end; end; end; end; finally tmpRows.Free; tmpRowStrs.Free; end; end; procedure DataGet_InstantArray_Sina(App: TBaseApp; AInstantArray: PInstantArray; AHttpClientSession: UtilsHttp.PHttpClientSession; AHttpData: PIOBuffer); var tmpUrl: string; tmpRetData: PIOBuffer; tmpHttpParse: THttpHeadParseSession; i: integer; begin tmpUrl := ''; for i := Low(AInstantArray.Data) to High(AInstantArray.Data) do begin if (nil <> AInstantArray.Data[i]) then begin if nil <> AInstantArray.Data[i].Item then begin if '' <> tmpUrl then tmpUrl := tmpUrl + ','; tmpUrl := tmpUrl + GetStockCode_Sina(AInstantArray.Data[i].Item); end; end; end; if '' <> tmpUrl then begin tmpUrl := BaseSinaInstantUrl1 + tmpUrl; tmpRetData := GetHttpUrlData(tmpUrl, AHttpClientSession, AHttpData); if nil <> tmpRetData then begin try FillChar(tmpHttpParse, SizeOf(tmpHttpParse), 0); HttpBufferHeader_Parser(tmpRetData, @tmpHttpParse); if 200 = tmpHttpParse.RetCode then begin if 0 < tmpHttpParse.HeadEndPos then begin DataParse_InstantArray_Sina(AInstantArray, PAnsiChar(@PIOBufferX(tmpRetData).Data[tmpHttpParse.HeadEndPos + 1])); end; end; finally CheckInIOBuffer(tmpRetData); end; end; end; end; end.
unit LUX.Color.Map.D1; interface //#################################################################### ■ uses System.UITypes, FMX.Graphics, LUX, LUX.Color, LUX.Map.D1; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGradation1D TGradation1D = class private protected _Colors :TArray<TSingleRGBA>; _ColorsN :Integer; ///// アクセス function GetColors( const I_:Integer ) :TSingleRGBA; procedure SetColors( const I_:Integer; const Colors_:TSingleRGBA ); procedure SetColorsN( const ColorsN_:Integer ); public constructor Create; overload; constructor Create( const FileName_:String ); overload; destructor Destroy; override; ///// プロパティ property Colors[ const I_:Integer ] :TSingleRGBA read GetColors write SetColors; property ColorsN :Integer read _ColorsN write SetColorsN; ///// メソッド procedure LoadFromBitmap( const Bitmap_:TBitmap ); procedure LoadFromFile( const FileName_:String ); function Interp( const X_:Single ) :TSingleRGBA; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.Math; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGradation1D //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TGradation1D.GetColors( const I_:Integer ) :TSingleRGBA; begin Result := _Colors[ I_ ]; end; procedure TGradation1D.SetColors( const I_:Integer; const Colors_:TSingleRGBA ); begin _Colors[ I_ ] := Colors_; end; procedure TGradation1D.SetColorsN( const ColorsN_:Integer ); begin _ColorsN := ColorsN_; SetLength( _Colors, _ColorsN ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGradation1D.Create; begin inherited; end; constructor TGradation1D.Create( const FileName_:String ); begin Create; LoadFromFile( FileName_ ); end; destructor TGradation1D.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGradation1D.LoadFromBitmap( const Bitmap_:TBitmap ); var B :TBitmapData; I :Integer; P :PAlphaColor; begin Bitmap_.Map( TMapAccess.Read, B ); ColorsN := Bitmap_.Width; P := B.GetScanline( 0 ); for I := 0 to _ColorsN-1 do begin _Colors[ I ] := P^; Inc( P ); end; Bitmap_.Unmap( B ); end; procedure TGradation1D.LoadFromFile( const FileName_:String ); var B :TBitmap; begin B := TBitmap.Create; B.LoadFromFile( FileName_ ); LoadFromBitmap( B ); B.Free; end; function TGradation1D.Interp( const X_:Single ) :TSingleRGBA; var Xi :Integer; X, Xd :Single; C0, C1 :TSingleRGBA; begin if X_ <= 0 then Result := _Colors[ 0 ] else if X_ >= 1 then Result := _Colors[ _ColorsN-1 ] else begin X := ( _ColorsN-1 ) * X_; Xi := Floor( X ); Xd := X - Xi; C0 := _Colors[ Xi ]; C1 := _Colors[ Xi+1 ]; Result := ( C1 - C0 ) * Xd + C0; end; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 10/26/2004 10:49:20 PM JPMugaas Updated ref. Rev 1.4 16/05/2004 18:56:16 CCostelloe New TIdText/TIdAttachment processing Rev 1.3 2004.02.03 5:44:34 PM czhower Name changes Rev 1.2 10/17/03 12:06:50 PM RLebeau Updated Assign() to copy all available header values rather than select ones. Rev 1.1 10/17/2003 1:11:14 AM DSiders Added localization comments. Rev 1.0 11/13/2002 08:03:00 AM JPMugaas 2002-08-30 Andrew P.Rubin - extract charset & IsBodyEncodingRequired (true = 8 bit) } unit IdText; interface {$i IdCompilerDefines.inc} uses Classes, IdMessageParts; type TIdText = class(TIdMessagePart) protected FBody: TStrings; procedure SetBody(const AStrs : TStrings); virtual; public constructor Create(Collection: TIdMessageParts; ABody: TStrings = nil); reintroduce; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function IsBodyEncodingRequired: Boolean; class function PartType: TIdMessagePartType; override; // property Body: TStrings read FBody write SetBody; end; implementation uses IdGlobal, IdGlobalProtocols, SysUtils; { TIdText } procedure TIdText.Assign(Source: TPersistent); begin if Source is TIdText then begin Body.Assign((Source as TIdText).Body); end; // allow TIdMessagePart to copy the headers inherited Assign(Source); end; constructor TIdText.Create(Collection: TIdMessageParts; ABody: TStrings = nil); begin inherited Create(Collection); FBody := TStringList.Create; TStringList(FBody).Duplicates := dupAccept; if ABody <> nil then begin FBody.Assign(ABody); end; end; destructor TIdText.Destroy; begin FreeAndNil(FBody); inherited Destroy; end; function TIdText.IsBodyEncodingRequired: Boolean; var i, j: Integer; S: String; begin Result := False;//7bit for i := 0 to FBody.Count-1 do begin S := FBody[i]; for j := 1 to Length(S) do begin if S[j] > #127 then begin Result := True; Exit; end; end; end; end; class function TIdText.PartType: TIdMessagePartType; begin Result := mptText; end; procedure TIdText.SetBody(const AStrs: TStrings); begin FBody.Assign(AStrs); end; initialization // RegisterClasses([TIdText]); end.
unit akPrint; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, tntclasses, jclunicode; type THeaderFooterProc = procedure(aCanvas: TCanvas; aPageCount: Integer; aTextrect: TRect; var continue: bytebool) of object; { Prototype for a callback method that PrintString will call when it is time to print a header or footer on a page. The parameters that will be passed to the callback are: aCanvas : the canvas to output on aPageCount: page number of the current page, counting from 1 aTextRect : output rectangle that should be used. This will be the area available between non-printable margin and top or bottom margin, in device units (dots). Output is not restricted to this area, though. continue : will be passed in as True. If the callback sets it to false the print job will be aborted. } function PrintStrings(lines: TTNTStrings; const leftmargin, rightmargin, topmargin, bottommargin: Single; // const linesPerInch: single; aFont: TFont; measureonly: bytebool; OnPrintheader, OnPrintfooter: THeaderFooterProc): Integer; implementation uses Printers; {+------------------------------------------------------------ | Function PrintStrings | | Parameters : | lines: | contains the text to print, already formatted into | lines of suitable length. No additional wordwrapping | will be done by this routine and also no text clipping | on the right margin! | leftmargin, topmargin, rightmargin, bottommargin: | define the print area. Unit is inches, the margins are | measured from the edge of the paper, not the printable | area, and are positive values! The margin will be adjusted | if it lies outside the printable area. | linesPerInch: | used to calculate the line spacing independent of font | size. | aFont: | font to use for printout, must not be Nil. | measureonly: | If true the routine will only count pages and not produce any | output on the printer. Set this parameter to false to actually | print the text. | OnPrintheader: | can be Nil. Callback that will be called after a new page has | been started but before any text has been output on that page. | The callback should be used to print a header and/or a watermark | on the page. | OnPrintfooter: | can be Nil. Callback that will be called after all text for one | page has been printed, before a new page is started. The callback | should be used to print a footer on the page. | Returns: | number of pages printed. If the job has been aborted the return | value will be 0. | Description: | Uses the Canvas.TextOut function to perform text output in | the rectangle defined by the margins. The text can span | multiple pages. | Nomenclature: | Paper coordinates are relative to the upper left corner of the | physical page, canvas coordinates (as used by Delphis Printer.Canvas) | are relative to the upper left corner of the printable area. The | printorigin variable below holds the origin of the canvas coordinate | system in paper coordinates. Units for both systems are printer | dots, the printers device unit, the unit for resolution is dots | per inch (dpi). | Error Conditions: | A valid font is required. Margins that are outside the printable | area will be corrected, invalid margins will raise an EPrinter | exception. | Created: 13.05.99 by P. Below +------------------------------------------------------------} function PrintStrings(lines: TTNTStrings; const leftmargin, rightmargin, topmargin, bottommargin: Single; // const linesPerInch: single; aFont: TFont; measureonly: bytebool; OnPrintheader, OnPrintfooter: THeaderFooterProc): Integer; var continuePrint: bytebool; { continue/abort flag for callbacks } pagecount: Integer; { number of current page } textrect: TRect; { output area, in canvas coordinates } headerrect: TRect; { area for header, in canvas coordinates } footerrect: TRect; { area for footes, in canvas coordinates } // lineheight: Integer; { line spacing in dots } charheight: Integer; { font height in dots } textstart: Integer; { index of first line to print on current page, 0-based. } { Calculate text output and header/footer rectangles. } procedure CalcPrintRects; var X_resolution: Integer; { horizontal printer resolution, in dpi } Y_resolution: Integer; { vertical printer resolution, in dpi } pagerect: TRect; { total page, in paper coordinates } printorigin: TPoint; { origin of canvas coordinate system in paper coordinates. } { Get resolution, paper size and non-printable margin from printer driver. } procedure GetPrinterParameters; begin with Printer.Canvas do begin X_resolution := GetDeviceCaps(handle, LOGPIXELSX); Y_resolution := GetDeviceCaps(handle, LOGPIXELSY); printorigin.X := GetDeviceCaps(handle, PHYSICALOFFSETX); printorigin.Y := GetDeviceCaps(handle, PHYSICALOFFSETY); pagerect.Left := 0; pagerect.Right := GetDeviceCaps(handle, PHYSICALWIDTH); pagerect.Top := 0; pagerect.Bottom := GetDeviceCaps(handle, PHYSICALHEIGHT); end; { With } end; { GetPrinterParameters } { Calculate area between the requested margins, paper-relative. Adjust margins if they fall outside the printable area. Validate the margins, raise EPrinter exception if no text area is left. } procedure CalcRects; var max: Integer; begin with textrect do begin { Figure textrect in paper coordinates } left := Round(leftmargin * X_resolution); if left < printorigin.x then left := printorigin.x; top := Round(topmargin * Y_resolution); if top < printorigin.y then top := printorigin.y; { Printer.PageWidth and PageHeight return the size of the printable area, we need to add the printorigin to get the edge of the printable area in paper coordinates. } right := pagerect.right - Round(rightmargin * X_resolution); max := Printer.PageWidth + printorigin.X; if right > max then right := max; bottom := pagerect.bottom - Round(bottommargin * Y_resolution); max := Printer.PageHeight + printorigin.Y; if bottom > max then bottom := max; { Validate the margins. } if (left >= right) or (top >= bottom) then raise EPrinter.Create( 'PrintString: the supplied margins are too large, there ' + 'is no area to print left on the page.'); end; { With } { Convert textrect to canvas coordinates. } OffsetRect(textrect, -printorigin.X, -printorigin.Y); { Build header and footer rects. } headerrect := Rect(textrect.left, 0, textrect.right, textrect.top); footerrect := Rect(textrect.left, textrect.bottom, textrect.right, Printer.PageHeight); end; { CalcRects } begin { CalcPrintRects } GetPrinterParameters; CalcRects; // lineheight := round(Y_resolution / linesPerInch); end; { CalcPrintRects } { Print a page with headers and footers. } procedure PrintPage; procedure FireHeaderFooterEvent(event: THeaderFooterProc; r: TRect); begin if Assigned(event) then begin event( Printer.Canvas, pagecount, r, ContinuePrint); { Revert to our font, in case event handler changed it. } Printer.Canvas.Font := aFont; end; { If } end; { FireHeaderFooterEvent } procedure DoHeader; begin FireHeaderFooterEvent(OnPrintHeader, headerrect); end; { DoHeader } procedure DoFooter; begin FireHeaderFooterEvent(OnPrintFooter, footerrect); end; { DoFooter } procedure DoPage; var y: Integer; trec: TRect; stre, str: widestring; thispage: Integer; fs: TFontStyles; fschanged: bytebool; begin y := textrect.top; thispage := 0; while (textStart < lines.count) and (y <= (textrect.bottom - charheight)) do begin str := lines[textStart]; fschanged := false; if Copy(str, 1, 5) = '##$>>' then begin fschanged := true; fs := printer.canvas.Font.Style; printer.canvas.Font.Style := [fsBold]; str := Copy(str, 6, maxint); end; try if WideTrim(str) = '' then stre := 'W' else stre := str; trec := Rect(textrect.left, y, textrect.right, textrect.Bottom * 100); DrawTextW(printer.canvas.Handle, PWideChar(stre), -1, trec, DT_CALCRECT or DT_WORDBREAK); if (trec.Bottom <= textrect.Bottom) or (thispage = 0) then begin inc(thispage); DrawTextW(printer.canvas.Handle, PWideChar(str), -1, trec, DT_WORDBREAK); Inc(textStart); Inc(y, trec.Bottom - trec.Top); end else break; finally if fschanged then printer.canvas.Font.Style := fs; end; end; { While } end; { DoPage } begin { PrintPage } DoHeader; if ContinuePrint then begin DoPage; DoFooter; if (textStart < lines.count) and ContinuePrint then begin Inc(pagecount); Printer.NewPage; end; { If } end; end; { PrintPage } begin { PrintStrings } Assert(Assigned(afont), 'PrintString: requires a valid aFont parameter!'); continuePrint := True; pagecount := 1; textstart := 0; Printer.Title := 'Note'; Printer.BeginDoc; try CalcPrintRects; {$IFNDEF WIN32} { Fix for Delphi 1 bug. } Printer.Canvas.Font.PixelsPerInch := Y_resolution; {$ENDIF } Printer.Canvas.Font := aFont; charheight := printer.canvas.TextHeight('Ay'); while (textstart < lines.count) and ContinuePrint do PrintPage; finally if continuePrint and not measureonly then Printer.EndDoc else begin Printer.Abort; end; end; if continuePrint then Result := pagecount else Result := 0; end; { PrintStrings } end.
{ ZIP archive handler } unit fszip; interface uses fs, fsarchive, SysUtils, Classes; type TEndOfCentralDir = packed record dwSignature : longword; wDiskNumber : word; wCentralDirDiskNumber : word; wTotalEntriesOnDisk : word; wTotalEntries : word; dwCentralDirSize : longword; dwCentralDirOffset : longword; wCommentLength : word; Comment : record end; end; TCentralFileHeader = packed record dwSignature : longword; wVersionMade : word; wVersionNeeded : word; wGeneralPurposeFlags : word; wCompressionMethod : word; dwLastModDateTime : longword; dwCRC32 : longword; dwCompressedSize : longword; dwUncompressedSize : longword; wFilenameLength : word; wExtraFieldLength : word; wFileCommentLength : word; wStartDiskNumber : word; wInternalFileAttributes : word; dwExternalFileAttributes : longword; dwLocalHeaderOffset : longword; end; TZIPHandler = class(TArchiveFSHandler) private eocdr:TEndOfCentralDir; public procedure OpenFS(const url:string);override; procedure readItems;override; procedure readVolumeInfo;override; class function canHandle(const url:string):boolean;override; class function getName:string;override; end; implementation uses Dialogs; { TFSZIPHandler } const sigZIP = $04034b50; sigEOCDR = $06054b50; sigCFH = $02014b50; procedure TZIPHandler.OpenFS; begin inherited OpenFS(url); with Info do begin VolumeName := ExtractFileName(url); FileSystem := 'ZIP'; VolumeType := vtArchive; end; Stream.Seek(-SizeOf(eocdr),soFromEnd); Stream.Read(eocdr,SizeOf(eocdr)); with eocdr do begin if eocdr.dwSignature <> sigEOCDR then raise EFSException.Create('Invalid EOCDR sig'); if eocdr.wDiskNumber <> eocdr.wCentralDirDiskNumber then raise EFSException.Create('Multiple volume ZIPs not supported'); end; end; class function TZIPHandler.canHandle; var T:TFileStream; dw:longword; begin Result := false; if not FileExists(url) then exit; try T := TFileStream.Create(url,fmOpenRead); except exit; end; try T.Position := 0; T.Read(dw,SizeOf(dw)); Result := dw = sigZIP; finally T.Free; end; end; procedure TZIPHandler.readItems; var rec:TCentralFileHeader; item:TFSItem; sp:string; fn:string; n,attr:integer; begin with Info,Info.Items do begin Clear; VolumeSize := 0; sp := UpperCase(StringReplace(System.copy(Path,length(Base)+2,length(Path)),'\','/',[rfReplaceAll])); Stream.Seek(eocdr.dwCentralDirOffset,soFromBeginning); repeat try Stream.Read(rec,SizeOf(rec)); except break; end; if rec.dwSignature = sigCFH then begin SetLength(fn,rec.wFilenameLength); inc(VolumeSize,rec.dwUncompressedSize); Stream.Read(fn[1],length(fn)); Stream.Seek(rec.wExtraFieldLength,soFromCurrent); if (sp = '') or (pos(sp,UpperCase(fn))=1) then begin n := pos('/',fn); if n > length(sp) then begin fn := System.copy(fn,length(sp)+1,n-length(sp)-1); end; item := TFSItem.Create; item.Name := ExtractFileName(StringReplace(fn,'/','\',[rfReplaceAll])); item.Date := FileDateToDateTime(rec.dwLastModDateTime); item.Size := rec.dwUncompressedSize; attr := Lo(rec.dwExternalFileAttributes); if attr and faDirectory > 0 then attr := attr or faBrowseable; item.Flags := attr; Add(item); end; end; until rec.dwSignature = sigEOCDR; addParentDir; end; end; procedure TZIPHandler.readVolumeInfo; begin // inherited; end; class function TZIPHandler.getName: string; begin Result := 'ZIP'; end; end.
unit UUsersDialog; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, System.Generics.Collections, Math, FMX.Dialogs, FMX.StdCtrls, UDialog, FMX.Objects; type TUsersDialog = class(TDialogFrame) btnpagedown: TButton; btnpageup: TButton; Button3: TButton; Button1: TButton; Button2: TButton; Button6: TButton; Button5: TButton; Button4: TButton; Button7: TButton; Button8: TButton; Button9: TButton; procedure ButtonClick(Sender: TObject); procedure btnpagedownClick(Sender: TObject); procedure btnpageupClick(Sender: TObject); private { Private declarations } currentpage: integer; maxpage: integer; Users: TStringList; UserBtnList: TList<TButton>; function getCurrentpageUsers(curpage: integer): TStringList; public { Public declarations } constructor Create(ParentForm: TForm; ParentPanel: TPanel; CallBackProc: IProcessDialogResult;UserNames :TStringList); end; //var // UsersDialog: TUsersDialog; implementation {$R *.fmx} procedure TUsersDialog.btnpagedownClick(Sender: TObject); begin // inherited; if currentpage < maxpage then currentpage := currentpage + 1; getCurrentpageUsers(currentpage); end; procedure TUsersDialog.btnpageupClick(Sender: TObject); begin // inherited; if currentpage > 1 then begin currentpage := currentpage - 1; getCurrentpageUsers(currentpage); end; end; procedure TUsersDialog.ButtonClick(Sender: TObject); var username : string; begin //inherited; username := (Sender as TButton).Text; if username <> '' then begin ReturnString := username; DialogResult := mrOK; FProcessDialogResult.ProcessDialogResult; end; end; constructor TUsersDialog.Create(ParentForm: TForm; ParentPanel: TPanel; CallBackProc: IProcessDialogResult;usernames : TStringList); var I: integer; j: integer; //page: integer; begin inherited Create(ParentForm, ParentPanel, CallBackProc); currentpage := 1; UserBtnList := TList<TButton>.Create; Users := usernames;//(ParentForm as TLoginForm).loginusers; maxpage := Users.Count div 9; if (Users.Count mod 9) > 0 then inc(maxpage); UserBtnList.Add(Button1); UserBtnList.Add(Button2); UserBtnList.Add(Button3); UserBtnList.Add(Button4); UserBtnList.Add(Button5); UserBtnList.Add(Button6); UserBtnList.Add(Button7); UserBtnList.Add(Button8); UserBtnList.Add(Button9); j := Min(UserBtnList.Count - 1, Users.Count - 1); for I := 0 to j do begin UserBtnList.Items[I].Text := Users[I]; end; end; function Tusersdialog.getCurrentpageUsers(curpage: integer): TStringList; var I: integer; j: integer; begin for I := 0 to UserBtnList.Count - 1 do begin UserBtnList.Items[I].Text := ''; end; if curpage <> maxpage then j := UserBtnList.Count - 1 else j := (Users.Count mod 9) - 1; for I := 0 to j do begin UserBtnList.Items[I].Text := Users[(curpage - 1) * 9 + I]; end; end; end.
unit daJournal; // Модуль: "w:\common\components\rtl\Garant\DA\daJournal.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaJournal" MUID: (559A3BD901CC) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , l3Tree , daTypes , l3Date , l3Tree_TLB ; type TdaJournal = class(Tl3ProtoObject, IdaJournal, IdaComboAccessJournalHelper) private f_CurUser: TdaUserID; f_CurStatTree: Tl3Tree; f_Factory: IdaTableQueryFactory; f_CurSessionID: TdaSessionID; private function GetNewSessionID: TdaSessionID; procedure AnalyseLog(const aLog: IdaResultSet); procedure LogEvent(aOperation: TdaJournalOperation; aFamilyID: TdaFamilyID; aExtID: LongInt; aData: LongInt); protected procedure DoLogEvent(aOperation: TdaJournalOperation; aFamilyID: TdaFamilyID; aExtID: LongInt; aData: LongInt); virtual; abstract; procedure CheckUser(anUserID: TdaUserID); virtual; abstract; procedure UserChanged(anUserID: TdaUserID); virtual; abstract; procedure SessionChanged; virtual; abstract; procedure DoStartCaching; virtual; abstract; procedure DoStopCaching; virtual; abstract; function MakeResultSet(const FromDate: TStDate; const ToDate: TStDate; aDocID: TdaDocID; UserOrGroupID: TdaUserID; UserGr: Boolean): IdaResultSet; virtual; abstract; procedure CorrectDates(var FromDate: TStDate; var ToDate: TStDate); function NeedLogSessionBegin: Boolean; virtual; function NeedLogSessionEnd: Boolean; virtual; function Get_CurStatisticTreeRoot: Il3RootNode; procedure CalcStatistics(const FromDate: TStDate; const ToDate: TStDate; aDocID: TdaDocID; UserOrGroupID: TdaUserID; UserGr: Boolean); procedure LogExport(aFamilyID: TdaFamilyID; aCount: LongInt); procedure LogImport(aFamilyID: TdaFamilyID); procedure LogPause(aLength: LongInt); procedure LogPrintDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); procedure LogSaveDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); procedure LogEditDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID; aEditType: TdaDocEditType; anOperation: TdaEditOperation = daTypes.da_eoNone); overload; procedure LogEditDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID; aEditType: TdaDocEditType; aDictType: TdaDictionaryType); overload; procedure LogDeleteDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); procedure LogEditDict(aFamilyID: TdaFamilyID; aDictType: TdaDictionaryType; anOperation: TdaEditOperation = daTypes.da_eoNone); procedure LogCreateDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); procedure LogAutoClass(aFamilyID: TdaFamilyID; aCount: LongInt); procedure LogOpenDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); function Get_UserID: TdaUserID; procedure Set_UserID(aValue: TdaUserID); procedure StartCaching; procedure StopCaching; procedure SessionDone; procedure SetAlienData(anUserID: TdaUserID; aSessionID: TdaSessionID); procedure LogAlienEvent(aOperation: TdaJournalOperation; aFamilyID: TdaFamilyID; aExtID: LongInt; aData: LongInt); function MakeAlienResultSet(const FromDate: TStDate; const ToDate: TStDate; aDocID: TdaDocID; UserOrGroupID: TdaUserID; UserGr: Boolean): IdaResultSet; function Get_CurSessionID: TdaSessionID; function IsSessionActive: Boolean; procedure AlienCheckUser(anUserID: TdaUserID); procedure AlienUserChanged(anUserID: TdaUserID); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(const aFactory: IdaTableQueryFactory); reintroduce; protected property CurStatTree: Tl3Tree read f_CurStatTree; property Factory: IdaTableQueryFactory read f_Factory; property CurSessionID: TdaSessionID read f_CurSessionID; end;//TdaJournal implementation uses l3ImplUses , l3Base , daScheme , SysUtils , TypInfo , daDataProvider , l3Nodes , l3TreeInterfaces , daUtils //#UC START# *559A3BD901CCimpl_uses* //#UC END# *559A3BD901CCimpl_uses* ; constructor TdaJournal.Create(const aFactory: IdaTableQueryFactory); //#UC START# *559A424301EE_559A3BD901CC_var* //#UC END# *559A424301EE_559A3BD901CC_var* begin //#UC START# *559A424301EE_559A3BD901CC_impl* inherited Create; f_CurSessionID := BlankSession; f_CurUser := 0; f_Factory := aFactory; f_CurStatTree := Tl3Tree.Create; Randomize; //#UC END# *559A424301EE_559A3BD901CC_impl* end;//TdaJournal.Create function TdaJournal.GetNewSessionID: TdaSessionID; //#UC START# *5549F9E70184_559A3BD901CC_var* var l_Query: IdaTabledQuery; Uniq : Boolean; TmpDate : TStDate; l_ResultSet: IdaResultSet; //#UC END# *5549F9E70184_559A3BD901CC_var* begin //#UC START# *5549F9E70184_559A3BD901CC_impl* l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtJournal))); try Result:=BlankSession; TmpDate:=(CurrentDate - DMYtoStDate(1,1,1998)) mod 24855; Result:=TmpDate * 24 * 60 * 60 + CurrentTime; l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtJournal)['session_id'])); l_Query.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtJournal)['session_id'], da_copEqual, 'p_SessionID'); l_Query.Prepare; try Repeat l_Query.Param['p_SessionID'].AsLargeInt := Result; l_ResultSet := l_Query.OpenResultSet; try Uniq := l_ResultSet.IsEmpty; if Not Uniq then Inc(Result); finally l_ResultSet := nil; end; until Uniq; finally l_Query.UnPrepare; end; finally l_Query := nil; end; //#UC END# *5549F9E70184_559A3BD901CC_impl* end;//TdaJournal.GetNewSessionID procedure TdaJournal.AnalyseLog(const aLog: IdaResultSet); //#UC START# *5563292201CF_559A3BD901CC_var* Var I : LongInt; CurS_ID : LargeInt; TmpNode, CurS_Node : Il3Node; DT1,DT2 : TStDateTimeRec; Days,Secnds: LongInt; Hours,Mins, Secs : Word; l_Hours, l_Minutes, l_Seconds: Integer; Day, Month, Year : Integer; PauseTime : TStTime; TmpStr : ShortString; //Iter : TSearchParameters; FullTime, FullPause, FullOpenDocs, FullModifDocs, FullModifications : LongInt; l_SessionField: IdaField; l_DateField: IdaField; l_TimeField: IdaField; l_OperationField: IdaField; l_AdditionalInfoField: IdaField; l_ExtIDField: IdaField; l_Additional: Integer; function FindLastNodeByParam(Parent: Il3Node; Param : Integer) : Il3Node; Var ResNode : Il3Node; function IterHandler(CurNode : Il3Node) : Boolean;far; begin if Param = (CurNode as Il3HandleNode).Handle then ResNode:=CurNode; Result:=False; end; begin ResNode:=nil; CurStatTree.IterateF(l3L2NA(@IterHandler),imOneLevel,Parent); Result:=ResNode; end; Procedure GetTimeFromLongInt(aSecnds : LongInt;Var Hours,Minutes,Seconds : Word); Const cSIH = 60*60; cSIM = 60; begin Hours:=aSecnds div cSIH; aSecnds:=aSecnds mod cSIH; Minutes:=aSecnds div cSIM; Seconds:=aSecnds mod cSIM; end; procedure SetSessionTime; begin DateTimeDiff(DT1,DT2,Days,Secnds); FullTime:=FullTime+Days*(24*60*60)+Secnds; GetTimeFromLongInt(Secnds,Hours,Mins,Secs); Hours:=Hours+Days*24; CurStatTree.InsertNode(CurS_Node, MakeNode(Format('Продолжительность сессии: %0.2d:%0.2d:%0.2d', [Hours,Mins,Secs]))); if PauseTime<>0 then begin GetTimeFromLongInt(PauseTime,Hours,Mins,Secs); CurStatTree.InsertNode(CurS_Node, MakeNode(Format('Нерабочее время (пауза): %0.2d:%0.2d:%0.2d', [Hours,Mins,Secs]))); FullPause:=FullPause+PauseTime; end; end; procedure SetFooterParams; begin GetTimeFromLongInt(FullTime,Hours,Mins,Secs); CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(Format('Общее время работы: %0.2d:%0.2d:%0.2d', [Hours,Mins,Secs]))); GetTimeFromLongInt(FullPause,Hours,Mins,Secs); CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(Format('Общее время простоя (паузы): %0.2d:%0.2d:%0.2d', [Hours,Mins,Secs]))); CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(Format('Количество открытых документов: %d',[FullOpenDocs]))); CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(Format('Количество отредактированных документов: %d',[FullModifDocs]))); CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(Format('Общее количество изменений в документах: %d',[FullModifications]))); end; //#UC END# *5563292201CF_559A3BD901CC_var* begin //#UC START# *5563292201CF_559A3BD901CC_impl* CurStatTree.Clear; FullTime:=0; FullPause:=0; FullOpenDocs:=0; FullModifDocs:=0; FullModifications:=0; PauseTime:=0; DT1.D:=0; DT1.T:=0; DT2.D:=0; DT2.T:=0; CurS_ID:=0; CurS_Node:=nil; l_SessionField := aLog.Field['session_id']; l_DateField := aLog.Field['Date']; l_TimeField := aLog.Field['Time']; l_OperationField := aLog.Field['operation_id']; l_AdditionalInfoField := aLog.Field['Additional']; l_ExtIDField := aLog.Field['ext_id']; while not aLog.EOF do begin if l_SessionField.AsLargeInt <> CurS_ID then begin if CurS_Node<>nil then SetSessionTime; DT1.D := l_DateField.AsStDate; DT1.T := l_TimeField.AsStTime; CurS_ID := l_SessionField.AsLargeInt; PauseTime:=0; end; Case TdaJournalOperation(l_OperationField.AsInteger) of da_oobPause : PauseTime:=PauseTime + l_AdditionalInfoField.AsInteger; da_oobSessionBegin: begin TmpNode := CurStatTree.FindNodeByParam(CurStatTree.RootNode, Integer(TdaUserID(l_ExtIDField.AsLargeInt)), imOneLevel); if TmpNode=nil then begin TmpNode:=CurStatTree.InsertNode(CurStatTree.RootNode, MakeNode(PAnsiChar(GlobalDataProvider.UserManager.GetUserName(l_ExtIDField.AsLargeInt)))); (TmpNode as Il3HandleNode).Handle:=Integer(TdaUserID(l_ExtIDField.AsLargeInt)); end; StDateToDMY(l_DateField.AsStDate,Day,Month,Year); StTimeToHMS(l_TimeField.AsStTime, l_Hours, l_Minutes, l_Seconds); CurS_Node:=CurStatTree.InsertNode(TmpNode, MakeNode(Format('Рабочая сессия (%d/%d/%d %.2d:%.2d:%.2d)', [Day, Month, Year, l_Hours, l_Minutes, l_Seconds]))); end; da_oobSessionEnd : CurStatTree.InsertNode(CurS_Node, MakeNode('Cессия закончилась корректно')); da_oobOpenDoc : begin Inc(FullOpenDocs); TmpNode:=CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Открыт документ N %d',[l_ExtIDField.AsLargeInt]))); (TmpNode as Il3HandleNode).Handle:=l_ExtIDField.AsLargeInt; end; da_oobCreateDoc : begin Inc(FullOpenDocs); TmpNode:=CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Создан документ N %d',[l_ExtIDField.AsLargeInt]))); (TmpNode as Il3HandleNode).Handle:=l_ExtIDField.AsLargeInt; end; da_oobDeleteDoc : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Удален документ N %d',[l_ExtIDField.AsLargeInt]))); da_oobEditDoc: begin Inc(FullModifications); TmpNode:=FindLastNodeByParam(CurS_Node,l_ExtIDField.AsLargeInt); if TmpNode=nil then begin TmpNode:=CurStatTree.InsertNode(CurS_Node, MakeNode(Format('Отредактирован документ N %d',[l_ExtIDField.AsLargeInt]))); Inc(FullModifDocs); end else if Not TmpNode.HasChild then Inc(FullModifDocs); l_Additional := l_AdditionalInfoField.AsInteger; Case PdaDocEditRec(@l_Additional).EditType of da_detText : CurStatTree.InsertNode(TmpNode,MakeNode('Изменен Текст')); da_detAttribute : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Аттрибуты')); da_detHyperLink : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Гиперлинки')); da_detSub : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Subы')); da_detDiction: Case PdaDocEditRec(@l_Additional).Details.DictType of da_dlSources : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Органы')); da_dlTypes : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Типы')); da_dlClasses : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Классы')); da_dlKeyWords : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены KW')); da_dlBases : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Группы')); da_dlDateNums : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Дата или Номер')); da_dlWarnings : CurStatTree.InsertNode(TmpNode,MakeNode('Изменены Предупреждения')); da_dlCorrects : CurStatTree.InsertNode(TmpNode,MakeNode('Внесена вычитка')); end; end; end; da_oobPrintDoc : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Документ N %d напечатан',[l_ExtIDField.AsLargeInt]))); da_oobSaveDoc : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Документ N %d сохранен на диск',[l_ExtIDField.AsLargeInt]))); da_oobEditDictionary : begin l_Additional := l_AdditionalInfoField.AsInteger; Case PdaDictEditRec(@l_Additional).Operation of da_eoNone : TmpStr:=''; da_eoAdd : TmpStr:='(Добавлен элемент)'; da_eoEdit : TmpStr:='(Исправлен элемент)'; da_eoDelete : TmpStr:='(Удален элемент)'; end; Case PdaDictEditRec(@l_Additional).DictType of da_dlSources : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь Органы %s',[TmpStr]))); da_dlTypes : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь Типы %s',[TmpStr]))); da_dlClasses : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь Классы %s',[TmpStr]))); da_dlKeyWords : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь KW %s',[TmpStr]))); da_dlBases : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь Группы %s',[TmpStr]))); da_dlWarnings : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Изменен словарь Предупреждения %s',[TmpStr]))); da_dlCorSources : CurStatTree.InsertNode(CurS_Node, MakeNode(Format('Изменен словарь Источники публикации %s',[TmpStr]))); end; end; da_oobExport : CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Проведен Экспорт %d документов', [l_AdditionalInfoField.AsInteger]))); da_oobImport : CurStatTree.InsertNode(CurS_Node,MakeNode('Проведен Импорт')); da_oobSearch_Deprecated : ; da_oobAutoClass: CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Проведена автоклассификация %d документов', [l_AdditionalInfoField.AsInteger]))); else CurStatTree.InsertNode(CurS_Node,MakeNode(Format('Нераспознанная операция (%s)', [GetEnumName(TypeInfo(TdaJournalOperation), l_OperationField.AsInteger)]))); end; DT2.D := l_DateField.AsStDate; DT2.T := l_TimeField.AsStTime; aLog.Next; end; SetSessionTime; SetFooterParams; //#UC END# *5563292201CF_559A3BD901CC_impl* end;//TdaJournal.AnalyseLog procedure TdaJournal.CorrectDates(var FromDate: TStDate; var ToDate: TStDate); //#UC START# *55657CD20360_559A3BD901CC_var* //#UC END# *55657CD20360_559A3BD901CC_var* begin //#UC START# *55657CD20360_559A3BD901CC_impl* if FromDate = 0 then FromDate := 1{CurrentDate}; if ToDate = 0 then ToDate := CurrentDate + 5; //#UC END# *55657CD20360_559A3BD901CC_impl* end;//TdaJournal.CorrectDates function TdaJournal.NeedLogSessionBegin: Boolean; //#UC START# *56F2622600C7_559A3BD901CC_var* //#UC END# *56F2622600C7_559A3BD901CC_var* begin //#UC START# *56F2622600C7_559A3BD901CC_impl* Result := True; //#UC END# *56F2622600C7_559A3BD901CC_impl* end;//TdaJournal.NeedLogSessionBegin function TdaJournal.NeedLogSessionEnd: Boolean; //#UC START# *56F271D602AB_559A3BD901CC_var* //#UC END# *56F271D602AB_559A3BD901CC_var* begin //#UC START# *56F271D602AB_559A3BD901CC_impl* Result := True; //#UC END# *56F271D602AB_559A3BD901CC_impl* end;//TdaJournal.NeedLogSessionEnd procedure TdaJournal.LogEvent(aOperation: TdaJournalOperation; aFamilyID: TdaFamilyID; aExtID: LongInt; aData: LongInt); //#UC START# *573C3BC601D1_559A3BD901CC_var* //#UC END# *573C3BC601D1_559A3BD901CC_var* begin //#UC START# *573C3BC601D1_559A3BD901CC_impl* if not UserIsService(f_CurUser) then DoLogEvent(aOperation, aFamilyID, aExtID, aData); //#UC END# *573C3BC601D1_559A3BD901CC_impl* end;//TdaJournal.LogEvent function TdaJournal.Get_CurStatisticTreeRoot: Il3RootNode; //#UC START# *554092F701E2_559A3BD901CCget_var* //#UC END# *554092F701E2_559A3BD901CCget_var* begin //#UC START# *554092F701E2_559A3BD901CCget_impl* Result := CurStatTree.RootNode; //#UC END# *554092F701E2_559A3BD901CCget_impl* end;//TdaJournal.Get_CurStatisticTreeRoot procedure TdaJournal.CalcStatistics(const FromDate: TStDate; const ToDate: TStDate; aDocID: TdaDocID; UserOrGroupID: TdaUserID; UserGr: Boolean); //#UC START# *554093EC02FE_559A3BD901CC_var* //#UC END# *554093EC02FE_559A3BD901CC_var* begin //#UC START# *554093EC02FE_559A3BD901CC_impl* AnalyseLog(MakeResultSet(FromDate, ToDate, aDocID, UserOrGroupID, UserGr)); //#UC END# *554093EC02FE_559A3BD901CC_impl* end;//TdaJournal.CalcStatistics procedure TdaJournal.LogExport(aFamilyID: TdaFamilyID; aCount: LongInt); //#UC START# *55409430035F_559A3BD901CC_var* //#UC END# *55409430035F_559A3BD901CC_var* begin //#UC START# *55409430035F_559A3BD901CC_impl* LogEvent(da_oobExport, aFamilyID, 0, aCount); //#UC END# *55409430035F_559A3BD901CC_impl* end;//TdaJournal.LogExport procedure TdaJournal.LogImport(aFamilyID: TdaFamilyID); //#UC START# *5540943F02DB_559A3BD901CC_var* //#UC END# *5540943F02DB_559A3BD901CC_var* begin //#UC START# *5540943F02DB_559A3BD901CC_impl* LogEvent(da_oobImport, aFamilyID, 0, 0); //#UC END# *5540943F02DB_559A3BD901CC_impl* end;//TdaJournal.LogImport procedure TdaJournal.LogPause(aLength: LongInt); //#UC START# *5540945201E3_559A3BD901CC_var* //#UC END# *5540945201E3_559A3BD901CC_var* begin //#UC START# *5540945201E3_559A3BD901CC_impl* LogEvent(da_oobPause, 0, 0, aLength); //#UC END# *5540945201E3_559A3BD901CC_impl* end;//TdaJournal.LogPause procedure TdaJournal.LogPrintDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); //#UC START# *55409462014D_559A3BD901CC_var* //#UC END# *55409462014D_559A3BD901CC_var* begin //#UC START# *55409462014D_559A3BD901CC_impl* LogEvent(da_oobPrintDoc, aFamilyID, aDocID, 0); //#UC END# *55409462014D_559A3BD901CC_impl* end;//TdaJournal.LogPrintDoc procedure TdaJournal.LogSaveDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); //#UC START# *554094740288_559A3BD901CC_var* //#UC END# *554094740288_559A3BD901CC_var* begin //#UC START# *554094740288_559A3BD901CC_impl* LogEvent(da_oobSaveDoc, aFamilyID, aDocID, 0); //#UC END# *554094740288_559A3BD901CC_impl* end;//TdaJournal.LogSaveDoc procedure TdaJournal.LogEditDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID; aEditType: TdaDocEditType; anOperation: TdaEditOperation = daTypes.da_eoNone); //#UC START# *554096B30178_559A3BD901CC_var* var // l_EditInfo2: TDocEditRec; l_EditInfo: TdaDocEditRec; Tmp: Longint; //#UC END# *554096B30178_559A3BD901CC_var* begin //#UC START# *554096B30178_559A3BD901CC_impl* l_EditInfo.EditType := aEditType; l_EditInfo.Details.Operation := anOperation; Tmp := 0; l3Move(l_EditInfo, Tmp, SizeOf(l_EditInfo)); LogEvent(da_oobEditDoc, aFamilyID, aDocID, Tmp); //#UC END# *554096B30178_559A3BD901CC_impl* end;//TdaJournal.LogEditDoc procedure TdaJournal.LogEditDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID; aEditType: TdaDocEditType; aDictType: TdaDictionaryType); //#UC START# *5540970E00EA_559A3BD901CC_var* var l_EditInfo: TdaDocEditRec; Tmp: Longint; //#UC END# *5540970E00EA_559A3BD901CC_var* begin //#UC START# *5540970E00EA_559A3BD901CC_impl* l_EditInfo.EditType := aEditType; l_EditInfo.Details.DictType := aDictType; Tmp := 0; l3Move(aEditType, Tmp, SizeOf(l_EditInfo)); LogEvent(da_oobEditDoc, aFamilyID, aDocID, Tmp); //#UC END# *5540970E00EA_559A3BD901CC_impl* end;//TdaJournal.LogEditDoc procedure TdaJournal.LogDeleteDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); //#UC START# *554097C303BF_559A3BD901CC_var* //#UC END# *554097C303BF_559A3BD901CC_var* begin //#UC START# *554097C303BF_559A3BD901CC_impl* LogEvent(da_oobDeleteDoc, aFamilyID, aDocID, 0); //#UC END# *554097C303BF_559A3BD901CC_impl* end;//TdaJournal.LogDeleteDoc procedure TdaJournal.LogEditDict(aFamilyID: TdaFamilyID; aDictType: TdaDictionaryType; anOperation: TdaEditOperation = daTypes.da_eoNone); //#UC START# *554097DC02FC_559A3BD901CC_var* var // l_Rec2: TDictEditRec; l_Rec: TdaDictEditRec; Tmp: Longint; //#UC END# *554097DC02FC_559A3BD901CC_var* begin //#UC START# *554097DC02FC_559A3BD901CC_impl* l_Rec.DictType := aDictType; l_Rec.Operation := anOperation; Tmp := 0; l3Move(l_Rec, Tmp, SizeOf(l_Rec)); LogEvent(da_oobEditDictionary, aFamilyID, 0, Tmp); //#UC END# *554097DC02FC_559A3BD901CC_impl* end;//TdaJournal.LogEditDict procedure TdaJournal.LogCreateDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); //#UC START# *554098710243_559A3BD901CC_var* //#UC END# *554098710243_559A3BD901CC_var* begin //#UC START# *554098710243_559A3BD901CC_impl* LogEvent(da_oobCreateDoc, aFamilyID, aDocID, 0); //#UC END# *554098710243_559A3BD901CC_impl* end;//TdaJournal.LogCreateDoc procedure TdaJournal.LogAutoClass(aFamilyID: TdaFamilyID; aCount: LongInt); //#UC START# *554098930337_559A3BD901CC_var* //#UC END# *554098930337_559A3BD901CC_var* begin //#UC START# *554098930337_559A3BD901CC_impl* LogEvent(da_oobAutoClass, aFamilyID, 0, aCount); //#UC END# *554098930337_559A3BD901CC_impl* end;//TdaJournal.LogAutoClass procedure TdaJournal.LogOpenDoc(aFamilyID: TdaFamilyID; aDocID: TdaDocID); //#UC START# *554098A40242_559A3BD901CC_var* //#UC END# *554098A40242_559A3BD901CC_var* begin //#UC START# *554098A40242_559A3BD901CC_impl* LogEvent(da_oobOpenDoc, aFamilyID, aDocID, 0); //#UC END# *554098A40242_559A3BD901CC_impl* end;//TdaJournal.LogOpenDoc function TdaJournal.Get_UserID: TdaUserID; //#UC START# *5541F3E6031F_559A3BD901CCget_var* //#UC END# *5541F3E6031F_559A3BD901CCget_var* begin //#UC START# *5541F3E6031F_559A3BD901CCget_impl* CheckUser(f_CurUser); Result := f_CurUser; //#UC END# *5541F3E6031F_559A3BD901CCget_impl* end;//TdaJournal.Get_UserID procedure TdaJournal.Set_UserID(aValue: TdaUserID); //#UC START# *5541F3E6031F_559A3BD901CCset_var* //#UC END# *5541F3E6031F_559A3BD901CCset_var* begin //#UC START# *5541F3E6031F_559A3BD901CCset_impl* if f_CurUser <> aValue then begin if f_CurSessionID <> BlankSession then begin LogEvent(da_oobSessionEnd, 0, 0, 0); f_CurSessionID := BlankSession end; f_CurUser := aValue; UserChanged(f_CurUser); if f_CurUser<>0 then begin f_CurSessionID := GetNewSessionID; SessionChanged; LogEvent(da_oobSessionBegin, 0, LongInt(f_CurUser), 0); end; end; //#UC END# *5541F3E6031F_559A3BD901CCset_impl* end;//TdaJournal.Set_UserID procedure TdaJournal.StartCaching; //#UC START# *5541F6EC00DE_559A3BD901CC_var* //#UC END# *5541F6EC00DE_559A3BD901CC_var* begin //#UC START# *5541F6EC00DE_559A3BD901CC_impl* DoStartCaching; //#UC END# *5541F6EC00DE_559A3BD901CC_impl* end;//TdaJournal.StartCaching procedure TdaJournal.StopCaching; //#UC START# *5541F6FB0124_559A3BD901CC_var* //#UC END# *5541F6FB0124_559A3BD901CC_var* begin //#UC START# *5541F6FB0124_559A3BD901CC_impl* DoStopCaching; //#UC END# *5541F6FB0124_559A3BD901CC_impl* end;//TdaJournal.StopCaching procedure TdaJournal.SessionDone; //#UC START# *554A037B0325_559A3BD901CC_var* //#UC END# *554A037B0325_559A3BD901CC_var* begin //#UC START# *554A037B0325_559A3BD901CC_impl* if NeedLogSessionEnd then LogEvent(da_oobSessionEnd, 0, 0, 0); f_CurSessionID := BlankSession; //#UC END# *554A037B0325_559A3BD901CC_impl* end;//TdaJournal.SessionDone procedure TdaJournal.SetAlienData(anUserID: TdaUserID; aSessionID: TdaSessionID); //#UC START# *56E2A25501A6_559A3BD901CC_var* //#UC END# *56E2A25501A6_559A3BD901CC_var* begin //#UC START# *56E2A25501A6_559A3BD901CC_impl* if (f_CurUser <> anUserID) or (f_CurSessionID <> aSessionID) then begin if f_CurSessionID <> BlankSession then begin f_CurSessionID := BlankSession; SessionChanged; if NeedLogSessionEnd then LogEvent(da_oobSessionEnd, 0, 0, 0); end; f_CurUser := anUserID; UserChanged(f_CurUser); if f_CurUser<>0 then begin f_CurSessionID := aSessionID; SessionChanged; if NeedLogSessionBegin then LogEvent(da_oobSessionBegin, 0, LongInt(f_CurUser), 0); end; end; //#UC END# *56E2A25501A6_559A3BD901CC_impl* end;//TdaJournal.SetAlienData procedure TdaJournal.LogAlienEvent(aOperation: TdaJournalOperation; aFamilyID: TdaFamilyID; aExtID: LongInt; aData: LongInt); //#UC START# *56E2A7DB03CE_559A3BD901CC_var* //#UC END# *56E2A7DB03CE_559A3BD901CC_var* begin //#UC START# *56E2A7DB03CE_559A3BD901CC_impl* DoLogEvent(aOperation, aFamilyID, aExtID, aData); //#UC END# *56E2A7DB03CE_559A3BD901CC_impl* end;//TdaJournal.LogAlienEvent function TdaJournal.MakeAlienResultSet(const FromDate: TStDate; const ToDate: TStDate; aDocID: TdaDocID; UserOrGroupID: TdaUserID; UserGr: Boolean): IdaResultSet; //#UC START# *56E2B57C01FA_559A3BD901CC_var* //#UC END# *56E2B57C01FA_559A3BD901CC_var* begin //#UC START# *56E2B57C01FA_559A3BD901CC_impl* Result := MakeResultSet(FromDate, ToDate, aDocID, UserOrGroupID, UserGr); //#UC END# *56E2B57C01FA_559A3BD901CC_impl* end;//TdaJournal.MakeAlienResultSet function TdaJournal.Get_CurSessionID: TdaSessionID; //#UC START# *56EBDD1F0184_559A3BD901CCget_var* //#UC END# *56EBDD1F0184_559A3BD901CCget_var* begin //#UC START# *56EBDD1F0184_559A3BD901CCget_impl* Result := f_CurSessionID; //#UC END# *56EBDD1F0184_559A3BD901CCget_impl* end;//TdaJournal.Get_CurSessionID function TdaJournal.IsSessionActive: Boolean; //#UC START# *56F2627200AE_559A3BD901CC_var* //#UC END# *56F2627200AE_559A3BD901CC_var* begin //#UC START# *56F2627200AE_559A3BD901CC_impl* Result := f_CurSessionID <> BlankSession; //#UC END# *56F2627200AE_559A3BD901CC_impl* end;//TdaJournal.IsSessionActive procedure TdaJournal.AlienCheckUser(anUserID: TdaUserID); //#UC START# *573C4C3B031D_559A3BD901CC_var* //#UC END# *573C4C3B031D_559A3BD901CC_var* begin //#UC START# *573C4C3B031D_559A3BD901CC_impl* CheckUser(anUserID); //#UC END# *573C4C3B031D_559A3BD901CC_impl* end;//TdaJournal.AlienCheckUser procedure TdaJournal.AlienUserChanged(anUserID: TdaUserID); //#UC START# *573C4C4903B7_559A3BD901CC_var* //#UC END# *573C4C4903B7_559A3BD901CC_var* begin //#UC START# *573C4C4903B7_559A3BD901CC_impl* UserChanged(anUserID); //#UC END# *573C4C4903B7_559A3BD901CC_impl* end;//TdaJournal.AlienUserChanged procedure TdaJournal.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_559A3BD901CC_var* //#UC END# *479731C50290_559A3BD901CC_var* begin //#UC START# *479731C50290_559A3BD901CC_impl* f_Factory := nil; FreeAndNil(f_CurStatTree); inherited; //#UC END# *479731C50290_559A3BD901CC_impl* end;//TdaJournal.Cleanup procedure TdaJournal.ClearFields; begin f_Factory := nil; inherited; end;//TdaJournal.ClearFields end.
unit Control.Entregas; interface uses Model.Entregas, System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum; type TEntregasControl = class private FEntregas : TEntregas; public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): TFDQuery; function LocalizarExata(aParam: array of variant): Boolean; function ValidaCampos(): Boolean; function ValidaExclusao(): Boolean; function Previas(aParam: array of variant): TFDQuery; function EntregasExtrato(aParam: Array of variant): TFDQuery; function EntregasExtratoEntregadores(aParam: Array of variant): boolean; function EncerraEntregas(aParam: array of variant): Boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; function GetAReceber(iEntregador: Integer): TFDQuery; property Entregas: TEntregas read FEntregas write FEntregas; end; implementation { TEntregasControl } constructor TEntregasControl.Create; begin FEntregas := TEntregas.Create; end; destructor TEntregasControl.Destroy; begin FEntregas.Free; inherited; end; function TEntregasControl.EncerraEntregas(aParam: array of variant): Boolean; begin Result := FEntregas.EncerraEntregas(aParam) end; function TEntregasControl.EntregasExtrato(aParam: array of variant): TFDQuery; begin Result := FEntregas.EntregasExtrato(aParam); end; function TEntregasControl.EntregasExtratoEntregadores(aParam: array of variant): boolean; begin Result := FEntregas.EntregasExtratoEntregadores(aParam); end; function TEntregasControl.GetAReceber(iEntregador: Integer): TFDQuery; begin Result := Fentregas.GetAReceber(iEntregador); end; function TEntregasControl.GetField(sField, sKey, sKeyValue: String): String; begin Result := FEntregas.GetField(sField, sKey, sKeyValue); end; function TEntregasControl.Gravar: Boolean; begin Result := False; if FEntregas.Acao = Common.ENum.tacExcluir then begin if not ValidaExclusao() then Exit; end; //if not ValidaCampos then Exit; Result := FEntregas.Gravar; end; function TEntregasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FEntregas.Localizar(aParam); end; function TEntregasControl.LocalizarExata(aParam: array of variant): Boolean; begin Result := FEntregas.LocalizarExata(aParam); end; function TEntregasControl.Previas(aParam: array of variant): TFDQuery; begin Result := FEntregas.Previas(aParam); end; function TEntregasControl.ValidaCampos: Boolean; begin Result := False; if FEntregas.NN.IsEmpty then begin Application.MessageBox('Informe o Nosso Número da entrega.', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end else begin if FEntregas.Acao = Common.ENum.tacIncluir then begin if FEntregas.ExisteNN(FEntregas.NN) then begin Application.MessageBox('Nosso Número já cadastrado.', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; end end; if FEntregas.NF.IsEmpty then begin Application.MessageBox('Número da nota fiscal náo pode ser vazio!.', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.Consumidor.IsEmpty then begin Application.MessageBox('Nome do concumidor náo pode ser vazio!.', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.Endereco.IsEmpty then begin Application.MessageBox('Endereço do consumuidor náo pode ser vazio!', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.Bairro.IsEmpty then begin Application.MessageBox('Bairro do endereço do consumuidor náo pode ser vazio!', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if (DateTimeToStr(FEntregas.Expedicao).IsEmpty) or (FEntregas.Expedicao = 0) then begin Application.MessageBox('Data da expedição inválida.', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if (DateTimeToStr(FEntregas.Previsao).IsEmpty) or (FEntregas.Previsao = 0) then begin Application.MessageBox('Data da previsão de entrega inválida!', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.Volumes = 0 then begin Application.MessageBox('Quantidade de volumes não pode ser zero!', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.PesoReal = 0 then begin Application.MessageBox('Peso do(s) volume(s) não pode(m) ser zero!', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; Result := True; end; function TEntregasControl.ValidaExclusao: Boolean; begin Result := False; if FEntregas.CodigoFeedback <> 0 then begin Application.MessageBox('Entrega já processada pelo Feedback! Impossível excluir', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if FEntregas.Lote <> 0 then begin Application.MessageBox('Entrega em Lote de Atribuição! Impossível excluir', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if (FEntregas.Bairro = 'N') or (FEntregas.Bairro.IsEmpty) then begin Application.MessageBox('Entrega já baixada! Impossível excluir', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; if (FEntregas.Pago = 'N') or (FEntregas.Bairro.IsEmpty) then begin Application.MessageBox('Entrega já paga! Impossível excluir', PChar(FEntregas.NN), MB_OK + MB_ICONWARNING); Exit; end; Result := True; end; end.
unit UnitFoldedBitsIDe; interface uses ToolsApi, System.Classes; type TIdeFoldedBitsIDE = class(TNotifierObject, IOTAWizard) private procedure Execute; function GetIDString: string; function GetName: string; function GetState: TWizardState; public end; TKeyboardOTABinding = class(TNotifierObject, IOTAKeyboardBinding) private procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices); function GetBindingType: TBindingType; function GetDisplayName: string; function GetName: string; function SourceEditor(Module: IOTAModule): IOTASourceEditor; Procedure CreateBindExecute(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); public end; procedure Register; var iWizardIndex: Integer = 0; iKeyBindingIndex: Integer = 0; implementation uses System.SysUtils, Vcl.Menus; { TIdeFoldedBitsIDE } procedure Register; begin iWizardIndex := (BorlandIDEServices As IOTAWizardServices) .AddWizard(TIdeFoldedBitsIDE.Create); //Application.Handle := (BorlandIDEServices As IOTAServices).GetParentHandle; iKeyBindingIndex := (BorlandIDEServices As IOTAKeyboardServices) .AddKeyboardBinding(TKeyboardOTABinding.Create); end; procedure TIdeFoldedBitsIDE.Execute; var TopView: IOTAEditView; editServices: IOTAEditorServices; i: IOTAElideActions; begin if Supports(BorlandIDEServices, IOTAEditorServices, editServices) then TopView:= editServices.TopView; if TopView.QueryInterface(IOTAElideActions, I) = S_OK then begin i.ElideNearestBlock; TopView.Paint; end; end; function TIdeFoldedBitsIDE.GetIDString: string; begin Result:= 'ideFoldedBitsIDE'; end; function TIdeFoldedBitsIDE.GetName: string; begin Result:= 'ideFoldedBitsIDE'; end; function TIdeFoldedBitsIDE.GetState: TWizardState; begin Result:= [wsEnabled]; end; { TKeyboardOTABinding } procedure TKeyboardOTABinding.BindKeyboard( const BindingServices: IOTAKeyBindingServices); begin BindingServices.AddKeyBinding([TextToShortCut('Ctrl+Shift+F8')], CreateBindExecute, nil); end; procedure TKeyboardOTABinding.CreateBindExecute(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult); var vIotaWizer: IOTAWizard; begin vIotaWizer:= TIdeFoldedBitsIDE.Create; vIotaWizer.Execute; end; function TKeyboardOTABinding.GetBindingType: TBindingType; begin Result:= btPartial; end; function TKeyboardOTABinding.GetDisplayName: string; begin Result:= 'ShortcutIde'; end; function TKeyboardOTABinding.GetName: string; begin Result:= 'ShortcutIde'; end; function TKeyboardOTABinding.SourceEditor(Module: IOTAModule): IOTASourceEditor; begin end; end.
unit App; { Based on 020_cube_mapping.cpp example from oglplus (http://oglplus.org/) } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App, Sample.Geometry; type TCubeMappingApp = class(TApplication) private FProgram: TGLProgram; FVerts: TGLBuffer; FNormals: TGLBuffer; FTexture: TGLTexture; FUniProjectionMatrix: TGLUniform; FUniCameraMatrix: TGLUniform; FUniModelMatrix: TGLUniform; FShape: TSpiralSphereGeometry; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; procedure Resize(const AWidth, AHeight: Integer); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Math, Sample.Assets, Sample.Targa; { TCubeMappingApp } procedure TCubeMappingApp.Initialize; var VertexShader, FragmentShader: TGLShader; VertAttr: TGLVertexAttrib; Uniform: TGLUniform; Image: TTgaImage; I: Integer; begin TAssets.Initialize; VertexShader.New(TGLShaderType.Vertex, 'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+ 'attribute vec3 Position;'#10+ 'attribute vec3 Normal;'#10+ 'attribute vec2 TexCoord;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec3 vertLightDir;'#10+ 'varying vec3 vertLightRefl;'#10+ 'varying vec3 vertViewDir;'#10+ 'varying vec3 vertViewRefl;'#10+ 'uniform vec3 LightPos;'#10+ 'void main(void)'#10+ '{'#10+ ' gl_Position = ModelMatrix * vec4(Position, 1.0);'#10+ ' vertNormal = mat3(ModelMatrix) * Normal;'#10+ ' vertLightDir = LightPos - gl_Position.xyz;'#10+ ' vertLightRefl = reflect('#10+ ' -normalize(vertLightDir),'#10+ ' normalize(vertNormal));'#10+ ' vertViewDir = ('#10+ ' vec4(0.0, 0.0, 1.0, 1.0)*'#10+ ' CameraMatrix).xyz;'#10+ ' vertViewRefl = reflect('#10+ ' normalize(vertViewDir),'#10+ ' normalize(vertNormal));'#10+ ' gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'uniform samplerCube TexUnit;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec3 vertLightDir;'#10+ 'varying vec3 vertLightRefl;'#10+ 'varying vec3 vertViewDir;'#10+ 'varying vec3 vertViewRefl;'#10+ 'void main(void)'#10+ '{'#10+ ' float l = length(vertLightDir);'#10+ ' float d = dot('#10+ ' normalize(vertNormal), '#10+ ' normalize(vertLightDir)) / l;'#10+ ' float s = dot('#10+ ' normalize(vertLightRefl),'#10+ ' normalize(vertViewDir));'#10+ ' vec3 lt = vec3(1.0, 1.0, 1.0);'#10+ ' vec3 env = textureCube(TexUnit, vertViewRefl).rgb;'#10+ ' gl_FragColor = vec4('#10+ ' env * 0.4 + '#10+ ' (lt + env) * 1.5 * max(d, 0.0) + '#10+ ' lt * pow(max(s, 0.0), 64.0), '#10+ ' 1.0);'#10+ '}'); FragmentShader.Compile; FProgram.New(VertexShader, FragmentShader); FProgram.Link; VertexShader.Delete; FragmentShader.Delete; FProgram.Use; FShape.Generate; { Positions } FVerts.New(TGLBufferType.Vertex); FVerts.Bind; FVerts.Data<TVector3>(FShape.Positions); VertAttr.Init(FProgram, 'Position'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Normals } FNormals.New(TGLBufferType.Vertex); FNormals.Bind; FNormals.Data<TVector3>(FShape.Normals); VertAttr.Init(FProgram, 'Normal'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Don't need data anymore } FShape.Clear; { Setup the texture } Image.Load('Newton.tga'); FTexture.New(TGLTextureType.CubeMap); FTexture.Bind; FTexture.MinFilter(TGLMinFilter.Linear); FTexture.MagFilter(TGLMagFilter.Linear); FTexture.WrapS(TGLWrapMode.ClampToEdge); FTexture.WrapT(TGLWrapMode.ClampToEdge); for I := 0 to 5 do FTexture.Upload(TGLPixelFormat.RGBA, Image.Width, Image.Height, @Image.Data[0], 0, TGLPixelDataType.UnsignedByte, I); { Uniforms } Uniform.Init(FProgram, 'TexUnit'); Uniform.SetValue(0); Uniform.Init(FProgram, 'LightPos'); Uniform.SetValue(3.0, 5.0, 4.0); FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix'); FUniCameraMatrix.Init(FProgram, 'CameraMatrix'); FUniModelMatrix.Init(FProgram, 'ModelMatrix'); gl.ClearColor(0.2, 0.05, 0.1, 0); gl.ClearDepth(1); gl.Enable(TGLCapability.DepthTest); gl.Enable(TGLCapability.CullFace); gl.FrontFace(TGLFaceOrientation.CounterClockwise); gl.CullFace(TGLFace.Back); end; procedure TCubeMappingApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TCubeMappingApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); var CameraMatrix, ModelMatrix: TMatrix4; begin { Clear the color and depth buffer } gl.Clear([TGLClear.Color, TGLClear.Depth]); { Use the program } FProgram.Use; { Set the matrix for camera orbiting the origin } OrbitCameraMatrix(TVector3.Zero, 4.5 - Sin(ATotalTimeSec * Pi / 8) * 2, ATotalTimeSec * Pi / 6, Radians(Sin(Pi * ATotalTimeSec / 15) * 90), CameraMatrix); FUniCameraMatrix.SetValue(CameraMatrix); { Update and render the sphere } ModelMatrix.InitRotation(Vector3(1, 1, 1), ATotalTimeSec * Pi / 5); FUniModelMatrix.SetValue(ModelMatrix); FShape.Draw; end; procedure TCubeMappingApp.Resize(const AWidth, AHeight: Integer); var ProjectionMatrix: TMatrix4; begin inherited; ProjectionMatrix.InitPerspectiveFovRH(Radians(60), AWidth / AHeight, 1, 100); FProgram.Use; FUniProjectionMatrix.SetValue(ProjectionMatrix); end; procedure TCubeMappingApp.Shutdown; begin { Release resources } FTexture.Delete; FNormals.Delete; FVerts.Delete; FProgram.Delete; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_SoundManager * Implements the global sound manager *********************************************************************************************************************** } Unit TERRA_SoundManager; {$I terra.inc} Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_String, TERRA_Utils, TERRA_Sound, TERRA_Application, TERRA_Collections, TERRA_Vector3D, TERRA_Log, TERRA_SoundSource, TERRA_SoundAmbience, TERRA_Resource, TERRA_ResourceManager, TERRA_AL; Type SoundManager = Class(ResourceManager) Protected _Context:PALCcontext; _Device:PALCdevice; _SoundDeviceList:List; _SoundCaptureDeviceList:List; _Sources:Array Of SoundSource; _SourceCount:Integer; _Ambience:SoundAmbience; _Enabled:Boolean; Procedure LoadDeviceList(Var DeviceList:List; QueryID:Integer); Procedure Init; Override; Procedure Update; Override; Procedure UpdatePosition(Position, Direction, Up:Vector3D); Procedure SetEnabled(Const Value: Boolean); Public Procedure Release; Override; Function Play(MySound:Sound):SoundSource; Overload; Function Play(Const Name:TERRAString):SoundSource; Overload; Function Spawn(MySound:Sound; Position:Vector3D; Volume:Single=1.0):SoundSource; Procedure Delete(Source:SoundSource); Function GetSound(Name:TERRAString; ValidateError:Boolean = True):Sound; Procedure ValidateSource(Var Source:SoundSource); Class Function Instance:SoundManager; Property Ambience:SoundAmbience Read _Ambience; Property Enabled:Boolean Read _Enabled Write SetEnabled; End; Implementation Uses TERRA_Error, TERRA_CollectionObjects, TERRA_GraphicsManager, TERRA_Camera, TERRA_FileManager; Var _SoundManager_Instance:ApplicationObject = Nil; { SoundSystem } Procedure SoundManager.Init; Var Attribs:Array[0..1] Of Integer; Begin Inherited; Self.AutoUnload := True; LoadOpenAL(); //Open default sound device Log(logDebug, 'Audio','Opening AL device'); _Device := alcOpenDevice(Nil); Attribs[0] := ALC_FREQUENCY; {$IFDEF MOBILE} Attribs[1] := 22050; {$ELSE} Attribs[1] := 44100; {$ENDIF} //Create context Log(logDebug, 'Audio','Creating AL context'); _Context := alcCreateContext(_Device, @Attribs[0]); //Set active context Log(logDebug, 'Audio','Making context current'); alcMakeContextCurrent(_Context); Log(logDebug, 'Audio','Initializing AL functions'); InitOpenAL; LoadDeviceList(_SoundDeviceList, ALC_DEVICE_SPECIFIER); LoadDeviceList(_SoundCaptureDeviceList, ALC_CAPTURE_DEVICE_SPECIFIER); alListenerfv(AL_Position, @VectorZero); alListenerfv(AL_VELOCITY, @VectorZero); //alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); If (Assigned(_SoundDeviceList)) And (_SoundDeviceList.Count<=0) Then Log(logWarning, 'Audio','No sound devices found!'); _Ambience := SoundAmbience.Create; _Enabled := True; AutoUnload := False; End; Procedure SoundManager.Release; Var I:Integer; Begin Inherited; For I := 0 To Pred(_SourceCount) Do ReleaseObject(_Sources[I]); SetLength(_Sources, 0); _SourceCount := 0; ReleaseObject(_Ambience); ReleaseObject(_SoundDeviceList); ReleaseObject(_SoundCaptureDeviceList); If Assigned(_Context) Then Begin alcMakeContextCurrent(Nil); alcDestroyContext(_Context); //Release context End; If Assigned(_Device) Then alcCloseDevice(_Device); //Close device FreeOpenAL(); _SoundManager_Instance := Nil; End; Function SoundManager.GetSound(Name:TERRAString; ValidateError:Boolean):Sound; Var S:TERRAString; Begin Result := Nil; Name := StringTrim(Name); If (Name='') Then Exit; Result := Sound(GetResource(Name)); If (Not Assigned(Result)) Then Begin S := FileManager.Instance().SearchResourceFile(Name+'.wav'); If (S='') Then S := FileManager.Instance().SearchResourceFile(Name+'.ogg'); If S<>'' Then Begin Result := Sound.Create(rtLoaded, S); Self.AddResource(Result); End Else If ValidateError Then RaiseError('Could not find sound resource. ['+Name +']'); End; End; Class function SoundManager.Instance: SoundManager; Begin If Not Assigned(_SoundManager_Instance) Then _SoundManager_Instance := InitializeApplicationComponent(SoundManager, Nil); Result := SoundManager(_SoundManager_Instance.Instance); End; Procedure SoundManager.LoadDeviceList(var DeviceList:List; QueryID: Integer); Var S:TERRAString; List:PAnsiChar; Begin S := ''; If Not Assigned(DeviceList) Then Begin DeviceList := TERRA_Collections.List.Create(collection_Unsorted); List := alcGetString(Nil,QueryID); If Assigned(List) Then While (List^<>#0) Do Begin S := S + List^; Inc(List); If (List^=#0) Then Begin DeviceList.Add(StringObject.Create(S)); Log(logDebug, 'Audio', 'Device: '+ S); S:=''; Inc(List); End; End; End; End; Procedure SoundManager.Update; Var I:Integer; Cam:Camera; Begin Inherited; (* If (GraphicsManager.Instance().ActiveViewport = Nil) Then Exit; Cam := GraphicsManager.Instance().ActiveViewport.Camera; UpdatePosition(Cam.Position, Cam.View, Cam.Up);*) I := 0; While (I<_SourceCount) Do If (_Sources[I].Waiting) Then Begin If (_Sources[I].Sound.IsReady) Then _Sources[I].Start; Inc(I); End Else If (Not _Sources[I].Loop) And (_Sources[I].Status = sndStopped) Then Begin _Sources[I].OnFinish(); ReleaseObject(_Sources[I]); _Sources[I] := _Sources[Pred(_SourceCount)]; Dec(_SourceCount); End Else Begin If Assigned(_Sources[I].Sound) Then _Sources[I].Sound.IsReady; Inc(I); End; End; Procedure SoundManager.Delete(Source:SoundSource); Var N, I:Integer; Begin N := -1; For I:=0 To Pred(_SourceCount) Do If (_Sources[I] = Source) Then Begin N := I; Break; End; If (N<0) Then Exit; ReleaseObject(_Sources[N]); _Sources[N] := _Sources[Pred(_SourceCount)]; _Sources[Pred(_SourceCount)] := Nil; Dec(_SourceCount); End; Function SoundManager.Play(MySound: Sound): SoundSource; Begin {$IFDEF DISABLESOUND} Result := Nil; Exit; {$ENDIF} If (Not Assigned(MySound)) Then Begin Result := Nil; Exit; End; {$IFNDEF ANDROID} If (OpenALHandle=0) Then Begin Result := Nil; Exit; End; {$ENDIF} If (Not _Enabled) Then Begin Result := Nil; Exit; End; Log(logDebug, 'Sound', 'Playing '+MySound.Name); MySound.Prefetch(); Result := SoundSource.Create(); Result.Bind(MySound); Log(logDebug, 'Sound', 'Setting '+MySound.Name+' position'); (* If Assigned(GraphicsManager.Instance().MainViewport) Then Result.Position := GraphicsManager.Instance().MainViewport.Camera.Position Else*) Result.Position := VectorZero; Log(logDebug, 'Sound', 'Registering sound in manager'); Inc(_SourceCount); If Length(_Sources)<_SourceCount Then SetLength(_Sources, _SourceCount); _Sources[Pred(_SourceCount)] := Result; End; Procedure SoundManager.UpdatePosition(Position, Direction, Up:Vector3D); Var Orientation:Record Direction:Vector3D; Up:Vector3D; End; Begin Orientation.Direction := Direction; Orientation.Up := Up; alListenerfv(AL_POSITION, @Position); alListenerfv(AL_ORIENTATION, @Orientation); End; Function SoundManager.Spawn(MySound:Sound; Position:Vector3D; Volume:Single): SoundSource; Begin Result := Self.Play(MySound); If Assigned(Result) Then Begin Result.Position := Position; Result.Volume := Volume; End; End; Procedure SoundManager.ValidateSource(var Source: SoundSource); Var I:Integer; Begin For I:=0 To Pred(_SourceCount) Do If (_Sources[I]=Source) Then Exit; Source := Nil; End; Function SoundManager.Play(Const Name:TERRAString): SoundSource; Var Snd:Sound; Begin Snd := Self.GetSound(Name, False); If Snd = Nil Then Begin Result := Nil; Exit; End; Result := Self.Play(Snd); End; Procedure SoundManager.SetEnabled(const Value: Boolean); Var S:TERRAString; Begin If (Self._Enabled = Value) Then Exit; _Enabled := Value; If (Value) Then S := 'Enabling audio...' Else S := 'Disabling audio...'; Log(logDebug, 'Audio', S); End; End.
{ File: HFSVolumes.p Contains: On-disk data structures for HFS and HFS Plus volumes. Version: Technology: Mac OS 8.1 Release: Universal Interfaces 3.4.2 Copyright: © 1984-2002 by Apple Computer, Inc. All rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit HFSVolumes; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,Files,Finder; {$ALIGN MAC68K} { Signatures used to differentiate between HFS and HFS Plus volumes } const kHFSSigWord = $4244; { 'BD' in ASCII } kHFSPlusSigWord = $482B; { 'H+' in ASCII } kHFSPlusVersion = $0004; { will change as format changes (version 4 shipped with Mac OS 8.1) } kHFSPlusMountVersion = FourCharCode('8.10'); { will change as implementations change ('8.10' in Mac OS 8.1) } { CatalogNodeID is used to track catalog objects } type HFSCatalogNodeID = UInt32; const kHFSMaxVolumeNameChars = 27; kHFSMaxFileNameChars = 31; kHFSPlusMaxFileNameChars = 255; { Extent overflow file data structures } { HFS Extent key } type HFSExtentKeyPtr = ^HFSExtentKey; HFSExtentKey = record keyLength: SInt8; { length of key, excluding this field } forkType: SInt8; { 0 = data fork, FF = resource fork } fileID: HFSCatalogNodeID; { file ID } startBlock: UInt16; { first file allocation block number in this extent } end; { HFS Plus Extent key } HFSPlusExtentKeyPtr = ^HFSPlusExtentKey; HFSPlusExtentKey = record keyLength: UInt16; { length of key, excluding this field } forkType: SInt8; { 0 = data fork, FF = resource fork } pad: SInt8; { make the other fields align on 32-bit boundary } fileID: HFSCatalogNodeID; { file ID } startBlock: UInt32; { first file allocation block number in this extent } end; { Number of extent descriptors per extent record } const kHFSExtentDensity = 3; kHFSPlusExtentDensity = 8; { HFS extent descriptor } type HFSExtentDescriptorPtr = ^HFSExtentDescriptor; HFSExtentDescriptor = record startBlock: UInt16; { first allocation block } blockCount: UInt16; { number of allocation blocks } end; { HFS Plus extent descriptor } HFSPlusExtentDescriptorPtr = ^HFSPlusExtentDescriptor; HFSPlusExtentDescriptor = record startBlock: UInt32; { first allocation block } blockCount: UInt32; { number of allocation blocks } end; { HFS extent record } HFSExtentRecord = array [0..2] of HFSExtentDescriptor; { HFS Plus extent record } HFSPlusExtentRecord = array [0..7] of HFSPlusExtentDescriptor; { Fork data info (HFS Plus only) - 80 bytes } HFSPlusForkDataPtr = ^HFSPlusForkData; HFSPlusForkData = record logicalSize: UInt64; { fork's logical size in bytes } clumpSize: UInt32; { fork's clump size in bytes } totalBlocks: UInt32; { total blocks used by this fork } extents: HFSPlusExtentRecord; { initial set of extents } end; { Permissions info (HFS Plus only) - 16 bytes } HFSPlusPermissionsPtr = ^HFSPlusPermissions; HFSPlusPermissions = record ownerID: UInt32; { user or group ID of file/folder owner } groupID: UInt32; { additional user of group ID } permissions: UInt32; { permissions (bytes: unused, owner, group, everyone) } specialDevice: UInt32; { UNIX: device for character or block special file } end; { Catalog file data structures } const kHFSRootParentID = 1; { Parent ID of the root folder } kHFSRootFolderID = 2; { Folder ID of the root folder } kHFSExtentsFileID = 3; { File ID of the extents file } kHFSCatalogFileID = 4; { File ID of the catalog file } kHFSBadBlockFileID = 5; { File ID of the bad allocation block file } kHFSAllocationFileID = 6; { File ID of the allocation file (HFS Plus only) } kHFSStartupFileID = 7; { File ID of the startup file (HFS Plus only) } kHFSAttributesFileID = 8; { File ID of the attribute file (HFS Plus only) } kHFSBogusExtentFileID = 15; { Used for exchanging extents in extents file } kHFSFirstUserCatalogNodeID = 16; { HFS catalog key } type HFSCatalogKeyPtr = ^HFSCatalogKey; HFSCatalogKey = record keyLength: SInt8; { key length (in bytes) } reserved: SInt8; { reserved (set to zero) } parentID: HFSCatalogNodeID; { parent folder ID } nodeName: Str31; { catalog node name } end; { HFS Plus catalog key } HFSPlusCatalogKeyPtr = ^HFSPlusCatalogKey; HFSPlusCatalogKey = record keyLength: UInt16; { key length (in bytes) } parentID: HFSCatalogNodeID; { parent folder ID } nodeName: HFSUniStr255; { catalog node name } end; { Catalog record types } const { HFS Catalog Records } kHFSFolderRecord = $0100; { Folder record } kHFSFileRecord = $0200; { File record } kHFSFolderThreadRecord = $0300; { Folder thread record } kHFSFileThreadRecord = $0400; { File thread record } { HFS Plus Catalog Records } kHFSPlusFolderRecord = 1; { Folder record } kHFSPlusFileRecord = 2; { File record } kHFSPlusFolderThreadRecord = 3; { Folder thread record } kHFSPlusFileThreadRecord = 4; { File thread record } { Catalog file record flags } kHFSFileLockedBit = $0000; { file is locked and cannot be written to } kHFSFileLockedMask = $0001; kHFSThreadExistsBit = $0001; { a file thread record exists for this file } kHFSThreadExistsMask = $0002; { HFS catalog folder record - 70 bytes } type HFSCatalogFolderPtr = ^HFSCatalogFolder; HFSCatalogFolder = record recordType: SInt16; { record type } flags: UInt16; { folder flags } valence: UInt16; { folder valence } folderID: HFSCatalogNodeID; { folder ID } createDate: UInt32; { date and time of creation } modifyDate: UInt32; { date and time of last modification } backupDate: UInt32; { date and time of last backup } userInfo: DInfo; { Finder information } finderInfo: DXInfo; { additional Finder information } reserved: array [0..3] of UInt32; { reserved - set to zero } end; { HFS Plus catalog folder record - 88 bytes } HFSPlusCatalogFolderPtr = ^HFSPlusCatalogFolder; HFSPlusCatalogFolder = record recordType: SInt16; { record type = HFS Plus folder record } flags: UInt16; { file flags } valence: UInt32; { folder's valence (limited to 2^16 in Mac OS) } folderID: HFSCatalogNodeID; { folder ID } createDate: UInt32; { date and time of creation } contentModDate: UInt32; { date and time of last content modification } attributeModDate: UInt32; { date and time of last attribute modification } accessDate: UInt32; { date and time of last access (Rhapsody only) } backupDate: UInt32; { date and time of last backup } permissions: HFSPlusPermissions; { permissions (for Rhapsody) } userInfo: DInfo; { Finder information } finderInfo: DXInfo; { additional Finder information } textEncoding: UInt32; { hint for name conversions } reserved: UInt32; { reserved - set to zero } end; { HFS catalog file record - 102 bytes } HFSCatalogFilePtr = ^HFSCatalogFile; HFSCatalogFile = record recordType: SInt16; { record type } flags: SInt8; { file flags } fileType: SInt8; { file type (unused ?) } userInfo: FInfo; { Finder information } fileID: HFSCatalogNodeID; { file ID } dataStartBlock: UInt16; { not used - set to zero } dataLogicalSize: SInt32; { logical EOF of data fork } dataPhysicalSize: SInt32; { physical EOF of data fork } rsrcStartBlock: UInt16; { not used - set to zero } rsrcLogicalSize: SInt32; { logical EOF of resource fork } rsrcPhysicalSize: SInt32; { physical EOF of resource fork } createDate: UInt32; { date and time of creation } modifyDate: UInt32; { date and time of last modification } backupDate: UInt32; { date and time of last backup } finderInfo: FXInfo; { additional Finder information } clumpSize: UInt16; { file clump size (not used) } dataExtents: HFSExtentRecord; { first data fork extent record } rsrcExtents: HFSExtentRecord; { first resource fork extent record } reserved: UInt32; { reserved - set to zero } end; { HFS Plus catalog file record - 248 bytes } HFSPlusCatalogFilePtr = ^HFSPlusCatalogFile; HFSPlusCatalogFile = record recordType: SInt16; { record type = HFS Plus file record } flags: UInt16; { file flags } reserved1: UInt32; { reserved - set to zero } fileID: HFSCatalogNodeID; { file ID } createDate: UInt32; { date and time of creation } contentModDate: UInt32; { date and time of last content modification } attributeModDate: UInt32; { date and time of last attribute modification } accessDate: UInt32; { date and time of last access (Rhapsody only) } backupDate: UInt32; { date and time of last backup } permissions: HFSPlusPermissions; { permissions (for Rhapsody) } userInfo: FInfo; { Finder information } finderInfo: FXInfo; { additional Finder information } textEncoding: UInt32; { hint for name conversions } reserved2: UInt32; { reserved - set to zero } { start on double long (64 bit) boundry } dataFork: HFSPlusForkData; { size and block data for data fork } resourceFork: HFSPlusForkData; { size and block data for resource fork } end; { HFS catalog thread record - 46 bytes } HFSCatalogThreadPtr = ^HFSCatalogThread; HFSCatalogThread = record recordType: SInt16; { record type } reserved: array [0..1] of SInt32; { reserved - set to zero } parentID: HFSCatalogNodeID; { parent ID for this catalog node } nodeName: Str31; { name of this catalog node } end; { HFS Plus catalog thread record -- maximum 520 bytes } HFSPlusCatalogThreadPtr = ^HFSPlusCatalogThread; HFSPlusCatalogThread = record recordType: SInt16; { record type } reserved: SInt16; { reserved - set to zero } parentID: HFSCatalogNodeID; { parent ID for this catalog node } nodeName: HFSUniStr255; { name of this catalog node (variable length) } end; { These are the types of records in the attribute B-tree. The values were chosen so that they wouldn't conflict with the catalog record types. } const kHFSPlusAttrInlineData = $10; { if size < kAttrOverflowSize } kHFSPlusAttrForkData = $20; { if size >= kAttrOverflowSize } kHFSPlusAttrExtents = $30; { overflow extents for large attributes } { HFSPlusAttrInlineData For small attributes, whose entire value is stored within this one B-tree record. There would not be any other records for this attribute. } type HFSPlusAttrInlineDataPtr = ^HFSPlusAttrInlineData; HFSPlusAttrInlineData = record recordType: UInt32; { = kHFSPlusAttrInlineData } reserved: UInt32; logicalSize: UInt32; { size in bytes of userData } userData: packed array [0..1] of UInt8; { variable length; space allocated is a multiple of 2 bytes } end; { HFSPlusAttrForkData For larger attributes, whose value is stored in allocation blocks. If the attribute has more than 8 extents, there will be additonal records (of type HFSPlusAttrExtents) for this attribute. } HFSPlusAttrForkDataPtr = ^HFSPlusAttrForkData; HFSPlusAttrForkData = record recordType: UInt32; { = kHFSPlusAttrForkData } reserved: UInt32; theFork: HFSPlusForkData; { size and first extents of value } end; { HFSPlusAttrExtents This record contains information about overflow extents for large, fragmented attributes. } HFSPlusAttrExtentsPtr = ^HFSPlusAttrExtents; HFSPlusAttrExtents = record recordType: UInt32; { = kHFSPlusAttrExtents } reserved: UInt32; extents: HFSPlusExtentRecord; { additional extents } end; { A generic Attribute Record } HFSPlusAttrRecordPtr = ^HFSPlusAttrRecord; HFSPlusAttrRecord = record case SInt16 of 0: ( recordType: UInt32; ); 1: ( inlineData: HFSPlusAttrInlineData; ); 2: ( forkData: HFSPlusAttrForkData; ); 3: ( overflowExtents: HFSPlusAttrExtents; ); end; { Key and node lengths } const kHFSPlusExtentKeyMaximumLength = 10; kHFSExtentKeyMaximumLength = 7; kHFSPlusCatalogKeyMaximumLength = 516; kHFSPlusCatalogKeyMinimumLength = 6; kHFSCatalogKeyMaximumLength = 37; kHFSCatalogKeyMinimumLength = 6; kHFSPlusCatalogMinNodeSize = 4096; kHFSPlusExtentMinNodeSize = 512; kHFSPlusAttrMinNodeSize = 4096; { HFS and HFS Plus volume attribute bits } { Bits 0-6 are reserved (always cleared by MountVol call) } kHFSVolumeHardwareLockBit = 7; { volume is locked by hardware } kHFSVolumeUnmountedBit = 8; { volume was successfully unmounted } kHFSVolumeSparedBlocksBit = 9; { volume has bad blocks spared } kHFSVolumeNoCacheRequiredBit = 10; { don't cache volume blocks (i.e. RAM or ROM disk) } kHFSBootVolumeInconsistentBit = 11; { boot volume is inconsistent (System 7.6 and later) } { Bits 12-14 are reserved for future use } kHFSVolumeSoftwareLockBit = 15; { volume is locked by software } kHFSVolumeHardwareLockMask = $80; kHFSVolumeUnmountedMask = $0100; kHFSVolumeSparedBlocksMask = $0200; kHFSVolumeNoCacheRequiredMask = $0400; kHFSBootVolumeInconsistentMask = $0800; kHFSVolumeSoftwareLockMask = $8000; kHFSMDBAttributesMask = $8380; kHFSCatalogNodeIDsReusedBit = 12; { nextCatalogID wrapped around } kHFSCatalogNodeIDsReusedMask = $1000; { Master Directory Block (HFS only) - 162 bytes } { Stored at sector #2 (3rd sector) } type HFSMasterDirectoryBlockPtr = ^HFSMasterDirectoryBlock; HFSMasterDirectoryBlock = record { These first fields are also used by MFS } drSigWord: UInt16; { volume signature } drCrDate: UInt32; { date and time of volume creation } drLsMod: UInt32; { date and time of last modification } drAtrb: UInt16; { volume attributes } drNmFls: UInt16; { number of files in root folder } drVBMSt: UInt16; { first block of volume bitmap } drAllocPtr: UInt16; { start of next allocation search } drNmAlBlks: UInt16; { number of allocation blocks in volume } drAlBlkSiz: UInt32; { size (in bytes) of allocation blocks } drClpSiz: UInt32; { default clump size } drAlBlSt: UInt16; { first allocation block in volume } drNxtCNID: UInt32; { next unused catalog node ID } drFreeBks: UInt16; { number of unused allocation blocks } drVN: Str27; { volume name } { Master Directory Block extensions for HFS } drVolBkUp: UInt32; { date and time of last backup } drVSeqNum: UInt16; { volume backup sequence number } drWrCnt: UInt32; { volume write count } drXTClpSiz: UInt32; { clump size for extents overflow file } drCTClpSiz: UInt32; { clump size for catalog file } drNmRtDirs: UInt16; { number of directories in root folder } drFilCnt: UInt32; { number of files in volume } drDirCnt: UInt32; { number of directories in volume } drFndrInfo: array [0..7] of SInt32; { information used by the Finder } drEmbedSigWord: UInt16; { embedded volume signature (formerly drVCSize) } drEmbedExtent: HFSExtentDescriptor; { embedded volume location and size (formerly drVBMCSize and drCtlCSize) } drXTFlSize: UInt32; { size of extents overflow file } drXTExtRec: HFSExtentRecord; { extent record for extents overflow file } drCTFlSize: UInt32; { size of catalog file } drCTExtRec: HFSExtentRecord; { extent record for catalog file } end; { HFSPlusVolumeHeader (HFS Plus only) - 512 bytes } { Stored at sector #2 (3rd sector) and second-to-last sector. } HFSPlusVolumeHeaderPtr = ^HFSPlusVolumeHeader; HFSPlusVolumeHeader = record signature: UInt16; { volume signature == 'H+' } version: UInt16; { current version is kHFSPlusVersion } attributes: UInt32; { volume attributes } lastMountedVersion: UInt32; { implementation version which last mounted volume } reserved: UInt32; { reserved - set to zero } createDate: UInt32; { date and time of volume creation } modifyDate: UInt32; { date and time of last modification } backupDate: UInt32; { date and time of last backup } checkedDate: UInt32; { date and time of last disk check } fileCount: UInt32; { number of files in volume } folderCount: UInt32; { number of directories in volume } blockSize: UInt32; { size (in bytes) of allocation blocks } totalBlocks: UInt32; { number of allocation blocks in volume (includes this header and VBM } freeBlocks: UInt32; { number of unused allocation blocks } nextAllocation: UInt32; { start of next allocation search } rsrcClumpSize: UInt32; { default resource fork clump size } dataClumpSize: UInt32; { default data fork clump size } nextCatalogID: HFSCatalogNodeID; { next unused catalog node ID } writeCount: UInt32; { volume write count } encodingsBitmap: UInt64; { which encodings have been use on this volume } finderInfo: packed array [0..31] of UInt8; { information used by the Finder } allocationFile: HFSPlusForkData; { allocation bitmap file } extentsFile: HFSPlusForkData; { extents B-tree file } catalogFile: HFSPlusForkData; { catalog B-tree file } attributesFile: HFSPlusForkData; { extended attributes B-tree file } startupFile: HFSPlusForkData; { boot file } end; { ---------- HFS and HFS Plus B-tree structures ---------- } { BTNodeDescriptor -- Every B-tree node starts with these fields. } BTNodeDescriptorPtr = ^BTNodeDescriptor; BTNodeDescriptor = record fLink: UInt32; { next node at this level } bLink: UInt32; { previous node at this level } kind: SInt8; { kind of node (leaf, index, header, map) } height: SInt8; { zero for header, map; child is one more than parent } numRecords: UInt16; { number of records in this node } reserved: UInt16; { reserved; set to zero } end; { Constants for BTNodeDescriptor kind } const kBTLeafNode = -1; kBTIndexNode = 0; kBTHeaderNode = 1; kBTMapNode = 2; { BTHeaderRec -- The first record of a B-tree header node } type BTHeaderRecPtr = ^BTHeaderRec; BTHeaderRec = record treeDepth: UInt16; { maximum height (usually leaf nodes) } rootNode: UInt32; { node number of root node } leafRecords: UInt32; { number of leaf records in all leaf nodes } firstLeafNode: UInt32; { node number of first leaf node } lastLeafNode: UInt32; { node number of last leaf node } nodeSize: UInt16; { size of a node, in bytes } maxKeyLength: UInt16; { reserved } totalNodes: UInt32; { total number of nodes in tree } freeNodes: UInt32; { number of unused (free) nodes in tree } reserved1: UInt16; { unused } clumpSize: UInt32; { reserved } btreeType: SInt8; { reserved } reserved2: SInt8; { reserved } attributes: UInt32; { persistent attributes about the tree } reserved3: array [0..15] of UInt32; { reserved } end; { Constants for BTHeaderRec attributes } const kBTBadCloseMask = $00000001; { reserved } kBTBigKeysMask = $00000002; { key length field is 16 bits } kBTVariableIndexKeysMask = $00000004; { keys in index nodes are variable length } {$ALIGN MAC68K} end.
unit uEqualizer; interface uses SysUtils, Classes, Dialogs, Graphics, Windows, Forms, ExtCtrls, Controls, fQIPPlugin, u_common, IniFiles, About, Options, BassPlayer, Info, Volume, Recording, Equalizer, EditStations, FastAddStation, DownloadFile; const EQ_REVERB = 19; type { EqHz } TEqHz = class public Hz : WideString; //nepoř. dB : Real; end; { EqPreset } TEqPreset = class public Name : WideString; Hz : TStringList; end; procedure LoadEqualizerSettings; procedure LoadPersonalEqualizerSettings(var sValues: WideString); procedure ActiveEqualizer(Preset: string); procedure DeactiveEqualizer; procedure SaveEqualizerSettings; procedure AddEqualizerPreset(sName, sValues: WideString); procedure UpdateEqualizerPreset(sName, sValues: WideString); procedure GetEqualizerPreset; implementation uses General, Convs, uSuperReplace, uLNG, uINI; procedure LoadEqualizerSettings; var INI: TINIFile; sFreqs: string; begin INIGetProfileConfig(INI); EqualizerOption := INIReadStringUTF8(INI, 'Equalizer', 'Option', 'Flat'); if EqualizerOption = '' then EqualizerOption := 'Flat'; EqualizerToRadioGenre := INIReadBool(INI, 'Equalizer', 'ToRadioGenre', true) ; INI := TIniFile.Create(PluginDLLpath + 'equalizer.ini'); sFreqs := INIReadStringUTF8(INI, 'Conf', 'Freqs', ''); slFreqs := TStringList.Create; slFreqs.Clear; slFreqs.Delimiter := ','; slFreqs.DelimitedText := sFreqs; INIFree(INI); end; procedure LoadPersonalEqualizerSettings(var sValues: WideString); var INI : TINIFile; sText : String; idx : Integer; begin INIGetProfileConfig(INI); sText := ''; for idx := 1 to FrequencyCount do sText := sText + '0, '; Delete(sText, Length(sText) - 1, 2); // smazání poslední mezery s čárkou sValues := INIReadStringUTF8(INI, 'Equalizer', 'Values', sText ); if sValues = '' then sValues := sText; INIFree(INI); end; procedure ActiveEqualizer(Preset: string); var idx: integer; begin if EqualizerPreset.IndexOf(Preset) = -1 then Preset := 'Pop'; for idx := 1 to FrequencyCount do begin FBassPlayer.BASSPlayer_SetEq(idx, Round(TEqHz(TEqPreset(EqualizerPreset.Objects[EqualizerPreset.IndexOf(Preset)]).Hz.Objects[idx-1]).dB)); end; if not EqualizerToRadioGenre then FBassPlayer.BASSPlayer_SetReverb(EQ_REVERB, 20-EqualizerReverb) else FBassPlayer.BASSPlayer_SetReverb(EQ_REVERB, 20); end; procedure DeactiveEqualizer; var idx: integer; begin for idx := 1 to FrequencyCount do begin FBassPlayer.BASSPlayer_SetEq(idx, 0); end; FBassPlayer.BASSPlayer_SetReverb(EQ_REVERB,20); end; procedure SaveEqualizerSettings; var INI : TIniFile; begin INIGetProfileConfig(INI); INIWriteBool(INI, 'Equalizer', 'Enabled', EqualizerEnabled); INIWriteBool(INI, 'Equalizer', 'ToRadioGenre', EqualizerToRadioGenre); INIWriteInteger(INI, 'Equalizer', 'Reverb', EqualizerReverb); if EqualizerOption = 'Personal' then begin INIWriteStringUTF8(INI, 'Equalizer', 'Values', Eq); end; INIWriteStringUTF8(INI, 'Equalizer', 'Option', EqualizerOption ); INIFree(INI); end; procedure AddEqualizerPreset(sName, sValues: WideString); var idx, idx1: integer; slValues: TStringList; dB: real; begin slValues := TStringList.Create; slValues.Clear; slValues.Delimiter := ','; slValues.DelimitedText := sValues; EqualizerPreset.Add(sName); idx1 := EqualizerPreset.Count - 1; EqualizerPreset.Objects[idx1] := TEqPreset.Create; TEqPreset(EqualizerPreset.Objects[idx1]).Name := sName; TEqPreset(EqualizerPreset.Objects[idx1]).Hz := TStringList.Create; for idx := 0 to slValues.Count - 1 do begin dB := ConvStrToInt( Trim( slValues.Strings[idx] )); TEqPreset(EqualizerPreset.Objects[idx1]).Hz.Add(''); TEqPreset(EqualizerPreset.Objects[idx1]).Hz.Objects[idx] := TEqHz.Create; TEqHz(TEqPreset(EqualizerPreset.Objects[idx1]).Hz.Objects[idx]).dB := dB; end; end; procedure UpdateEqualizerPreset(sName, sValues: WideString); var idx, idx1: integer; slValues: TStringList; dB: real; begin slValues := TStringList.Create; slValues.Clear; slValues.Delimiter := ','; slValues.DelimitedText := sValues; idx1 := EqualizerPreset.IndexOf(sName); for idx := 0 to slValues.Count - 1 do begin dB := ConvStrToInt( Trim( slValues.Strings[idx] )); TEqPreset(EqualizerPreset.Objects[idx1]).Hz.Objects[idx] := TEqHz.Create; TEqHz(TEqPreset(EqualizerPreset.Objects[idx1]).Hz.Objects[idx]).dB := dB; end; end; procedure GetEqualizerPreset; var INI : TINIFILE; slSections : TStringList; idx, idx2 : Integer; sValues : WideString; sText : String; begin LoadEqualizerSettings; LoadPersonalEqualizerSettings(sValues); AddEqualizerPreset('Personal', sValues); slSections := TStringList.Create; slSections.Clear; if FileExists(PluginDllPath + 'equalizer.ini') = False then begin ShowMessage( TagsReplace( StringReplace(LNG('Texts', 'ConfigNotFound', 'Config file %file% wasn''t found.[br]Plugin can be unstable.'), '%file%', 'equalizer.ini', [rfReplaceAll, rfIgnoreCase]) ) ); end; INI := TiniFile.Create( PluginDllPath + 'equalizer.ini'); INI.ReadSections(slSections); idx:=0; while ( idx <= slSections.Count - 1 ) do begin Application.ProcessMessages; sText := ''; for idx2 := 1 to FrequencyCount do sText := sText + '0, '; Delete(sText, Length(sText) - 1, 2); // smazání poslední mezery s čárkou sValues := INIReadStringUTF8(INI, slSections.Strings[idx], 'Values', sText ); if sValues = '' then sValues := sText; if slSections.Strings[idx] <> 'Conf' then AddEqualizerPreset(slSections.Strings[idx], sValues); Inc(idx); end; INIFree(INI); end; end.
unit uConfiguracao; interface uses FireDac.Comp.Client, IdHashMessageDigest, FMX.TabControl; Type TFuncoes = class class procedure ClonarDataSet(const ADataSet: TFDMemTable; const AQuery: TFDQuery); end; TMudarAba = record procedure ClienteInicio(AbaInicial: TChangeTabAction); end; TBairroSelecionado = record private FCodigo: integer; FNome: string; procedure SetCodigo(const Value: integer); procedure SetNome(const Value: string); public Property Codigo: integer read FCodigo write SetCodigo; Property Nome: string read FNome write SetNome; end; TUsuario = record private FCodUsuarioAtual: integer; procedure SetCodUsuarioAtual(const Value: integer); public property CodUsuarioAtual: integer read FCodUsuarioAtual write SetCodUsuarioAtual; end; TConfiguracao = record private FDSHostName: string; FTituloJanelaMain: string; FRESTContext: string; FDSMethod: string; FNumeroConexao: integer; FDSContext: string; FURLBase: string; FDSPort: string; procedure SetDSContext(const Value: string); procedure SetDSHostName(const Value: string); procedure SetDSMethod(const Value: string); procedure SetDSPort(const Value: string); procedure SetNumeroConexao(const Value: integer); procedure SetRESTContext(const Value: string); procedure SetTituloJanelaMain(const Value: string); procedure SetURLBase(const Value: string); public property URLBase: string read FURLBase write SetURLBase; property DSHostName: string read FDSHostName write SetDSHostName; property DSContext: string read FDSContext write SetDSContext; property RESTContext: string read FRESTContext write SetRESTContext; property DSPort: string read FDSPort write SetDSPort; property DSMethod: string read FDSMethod write SetDSMethod; property NumeroConexao: integer read FNumeroConexao write SetNumeroConexao; property TituloJanelaMain: string read FTituloJanelaMain write SetTituloJanelaMain; end; TSistema = record private FEstouNoLogin: Boolean; FFormAtual: string; procedure SetEstouNoLogin(const Value: Boolean); procedure SetFormAtual(const Value: string); public property EstouNoLogin: Boolean read FEstouNoLogin write SetEstouNoLogin; property FormAtual: string read FFormAtual write SetFormAtual; end; TProdutos = record private FCodigo: integer; FAbaAtual: integer; FNome: string; procedure SetCodigo(const Value: integer); procedure SetAbaAtual(const Value: integer); procedure SetNome(const Value: string); public property Codigo: integer read FCodigo write SetCodigo; property Nome: string read FNome write SetNome; Property AbaAtual: integer read FAbaAtual write SetAbaAtual; end; procedure MudarTituloPesq(ATexto: string); procedure MudarTituloPesq2(ATexto: string); procedure MudarTituloGeral(ATexto: string); Function MD5Crypt(const Value: string): string; var Configuracao: TConfiguracao; Produtos: TProdutos; Sistema: TSistema; Usuario: TUsuario; BairroSelecionado: TBairroSelecionado; implementation uses uFrmMain; procedure MudarTituloPesq2(ATexto: string); begin // frmMain.lblGeralPesquisas2.Text := ATexto; end; procedure MudarTituloPesq(ATexto: string); begin // frmMain.lblGeralPesquisas.Text := ATexto; end; procedure MudarTituloGeral(ATexto: string); begin // frmMain.lblTituloGeral.Text := ATexto; end; Function MD5Crypt(const Value: string): string; var xMD5: TIdHashMessageDigest5; begin xMD5 := TIdHashMessageDigest5.Create; try Result := xMD5.HashStringAsHex(Value); finally xMD5.free; end; end; { TProdutos } procedure TProdutos.SetAbaAtual(const Value: integer); begin FAbaAtual := Value; end; procedure TProdutos.SetCodigo(const Value: integer); begin FCodigo := Value; end; procedure TProdutos.SetNome(const Value: string); begin FNome := Value; end; { TSistema } procedure TSistema.SetEstouNoLogin(const Value: Boolean); begin FEstouNoLogin := Value; end; procedure TSistema.SetFormAtual(const Value: string); begin FFormAtual := Value; end; { TFuncoes } class procedure TFuncoes.ClonarDataSet(const ADataSet: TFDMemTable; const AQuery: TFDQuery); begin if ADataSet.Active then begin ADataSet.EmptyDataSet; end; ADataSet.AppendData(AQuery, True); end; { TConfiguracao } procedure TConfiguracao.SetDSContext(const Value: string); begin FDSContext := Value; end; procedure TConfiguracao.SetDSHostName(const Value: string); begin FDSHostName := Value; end; procedure TConfiguracao.SetDSMethod(const Value: string); begin FDSMethod := Value; end; procedure TConfiguracao.SetDSPort(const Value: string); begin FDSPort := Value; end; procedure TConfiguracao.SetNumeroConexao(const Value: integer); begin FNumeroConexao := Value; end; procedure TConfiguracao.SetRESTContext(const Value: string); begin FRESTContext := Value; end; procedure TConfiguracao.SetTituloJanelaMain(const Value: string); begin FTituloJanelaMain := Value; end; procedure TConfiguracao.SetURLBase(const Value: string); begin FURLBase := Value; end; { TUsuario } procedure TUsuario.SetCodUsuarioAtual(const Value: integer); begin FCodUsuarioAtual := Value; end; { TBairroSelecionado } procedure TBairroSelecionado.SetCodigo(const Value: integer); begin FCodigo := Value; end; procedure TBairroSelecionado.SetNome(const Value: string); begin FNome := Value; end; { TMudarAba } procedure TMudarAba.ClienteInicio(AbaInicial: TChangeTabAction); begin end; end.
unit SubscriptionsService; interface uses JunoApi4Delphi.Interfaces, Data.DB; type TSubscriptions = class(TInterfacedObject, iSubscriptions) private FBilling : iBilling<iSubscriptions>; FSplit : iSplit<iSubscriptions>; public constructor Create; destructor Destroy; override; class function New : iSubscriptions; function CreateSubscription : iSubscriptions; function DueDay(Value : Integer) : iSubscriptions; function PlanId(Value : String) : iSubscriptions; function ChargeDescription(Value : String): iSubscriptions; function CreditCardDetails(Value : String) : iSubscriptions; function Billing : iBilling<iSubscriptions>; function Split : iSplit<iSubscriptions>; function &End(Value : TDataSet) : iSubscriptions; overload; function &End : String; overload; end; implementation { TSubscriptions } uses Billing, Split; function TSubscriptions.Billing: iBilling<iSubscriptions>; begin Result := FBilling; end; function TSubscriptions.ChargeDescription(Value: String): iSubscriptions; begin end; function TSubscriptions.&End: String; begin end; function TSubscriptions.&End(Value: TDataSet): iSubscriptions; begin end; constructor TSubscriptions.Create; begin FBilling := TBilling<iSubscriptions>.New(Self); FSplit := TSplit<iSubscriptions>.New(Self); end; function TSubscriptions.CreateSubscription: iSubscriptions; begin end; function TSubscriptions.CreditCardDetails(Value: String): iSubscriptions; begin end; destructor TSubscriptions.Destroy; begin inherited; end; function TSubscriptions.DueDay(Value: Integer): iSubscriptions; begin end; class function TSubscriptions.New: iSubscriptions; begin Result := Self.Create; end; function TSubscriptions.PlanId(Value: String): iSubscriptions; begin end; function TSubscriptions.Split: iSplit<iSubscriptions>; begin end; end.
unit _3DScene; interface uses _Types, Types, Graphics, _3DCameraView, _Utils, Classes; type T3DTriangle = class RP: array [1..3] of T3DPoint; RV: array [1..3] of Boolean; BColor, PColor: TColor; SP: array [1..3] of TPoint; ClockWise: Boolean; LSP,RSP: array [1..3] of TPoint; LClockWise,RClockWise: Boolean; constructor Create(Pnt1,Pnt2,Pnt3: T3DPoint; Rbr1,Rbr2,Rbr3: Boolean; BrushColor,PenColor: TColor); procedure CalcScreenPoints(cam: T3DCameraViewAnaglyph); procedure Draw(Canvas: TCanvas); procedure DrawLeft(Canvas: TCanvas; penColor: TColor); procedure DrawRight(Canvas: TCanvas; penColor: TColor); end; T3DObject = class ListObj: TList; VisibleObj: TList; CenterPoint: T3DPoint; DistToCamera: RealType; constructor Create(x,y,z: RealType); destructor Destroy; override; procedure CalcScreenCoords(cam: T3DCameraViewAnaglyph); procedure Draw(Canvas: TCanvas); procedure DrawLeft(Canvas: TCanvas; penColor: TColor); procedure DrawRight(Canvas: TCanvas; penColor: TColor); procedure Clear; procedure Add3(P1,P2,P3: T3DPoint; R1,R2,R3: Boolean; BrushColor,PenColor: TColor); procedure Add4(P1,P2,P3,P4: T3DPoint; R1,R2,R3,R4: Boolean; BrushColor,PenColor: TColor); end; T3DScene = class List3DObj: TList; constructor Create; destructor Destroy; override; procedure CalcScreenCoords(cam: T3DCameraViewAnaglyph); procedure Add(obj: T3DObject); procedure Draw(Canvas: TCanvas); procedure DrawLeft(Canvas: TCanvas; penColor: TColor); procedure DrawRight(Canvas: TCanvas; penColor: TColor); end; implementation constructor T3DTriangle.Create(Pnt1,Pnt2,Pnt3: T3DPoint; Rbr1,Rbr2,Rbr3: Boolean; BrushColor,PenColor: TColor); begin inherited Create; RP[1] := Pnt1; RP[2] := Pnt2; RP[3] := Pnt3; RV[1] := Rbr1; RV[2] := Rbr2; RV[3] := Rbr3; BColor := BrushColor; PColor := PenColor; end; procedure T3DTriangle.CalcScreenPoints(cam: T3DCameraViewAnaglyph); var i: Integer; begin for i := 1 to 3 do SP[i] := cam.GetPixelCoord(RP[i].X, RP[i].Y, RP[i].Z); ClockWise := ClockWise3Point(SP[1],SP[2],SP[3]); // stereo for i := 1 to 3 do cam.GetLRPixelCoord(RP[i].X, RP[i].Y, RP[i].Z, LSP[i], RSP[i]); LClockWise := ClockWise3Point(LSP[1],LSP[2],LSP[3]); RClockWise := ClockWise3Point(RSP[1],RSP[2],RSP[3]); end; procedure T3DTriangle.Draw(Canvas: TCanvas); var i,l: Integer; begin if ClockWise then Exit; with Canvas do begin Brush.Color := BColor; Pen.Style := psClear; Canvas.Polygon(SP); Pen.Style := psSolid; Pen.Color := PColor; for i := 1 to 3 do if RV[i] then begin l := i mod 3 + 1; MoveTo(SP[i].X, SP[i].Y); LineTo(SP[l].X, SP[l].Y); end; end; end; procedure T3DTriangle.DrawLeft(Canvas: TCanvas; penColor: TColor); var i,l: Integer; begin if LClockWise then Exit; with Canvas do begin Brush.Color := clWhite; Pen.Style := psClear; Canvas.Polygon(LSP); Pen.Style := psSolid; Pen.Color := penColor; for i := 1 to 3 do if RV[i] then begin l := i mod 3 + 1; MoveTo(LSP[i].X, LSP[i].Y); LineTo(LSP[l].X, LSP[l].Y); end; end; end; procedure T3DTriangle.DrawRight(Canvas: TCanvas; penColor: TColor); var i,l: Integer; begin if RClockWise then Exit; with Canvas do begin Brush.Color := clWhite; Pen.Style := psClear; Canvas.Polygon(RSP); Pen.Style := psSolid; Pen.Color := penColor; for i := 1 to 3 do if RV[i] then begin l := i mod 3 + 1; MoveTo(RSP[i].X, RSP[i].Y); LineTo(RSP[l].X, RSP[l].Y); end; end; end; // constructor T3DObject.Create; begin inherited Create; CenterPoint := _3DPoint(x,y,z); ListObj := TList.Create; VisibleObj := TList.Create; end; destructor T3DObject.Destroy; begin Clear; ListObj.Free; VisibleObj.Free; inherited Destroy; end; procedure T3DObject.CalcScreenCoords(cam: T3DCameraViewAnaglyph); var i: Integer; tr: T3DTriangle; begin VisibleObj.Clear; for i := 0 to ListObj.Count - 1 do begin TR := T3DTriangle(ListObj[i]); TR.CalcScreenPoints(cam); if not TR.ClockWise then VisibleObj.Add(TR); end; DistToCamera := Sqr(CenterPoint.X-cam.CoordCamera.X) + Sqr(CenterPoint.Y-cam.CoordCamera.Y) + Sqr(CenterPoint.Z-cam.CoordCamera.Z); end; procedure T3DObject.Draw(Canvas: TCanvas); var i: Integer; begin for i := 0 to VisibleObj.Count - 1 do T3DTriangle(VisibleObj[i]).Draw(Canvas); end; procedure T3DObject.DrawLeft(Canvas: TCanvas; penColor: TColor); var i: Integer; begin for i := 0 to VisibleObj.Count - 1 do T3DTriangle(VisibleObj[i]).DrawLeft(Canvas, penColor); end; procedure T3DObject.DrawRight(Canvas: TCanvas; penColor: TColor); var i: Integer; begin for i := 0 to VisibleObj.Count - 1 do T3DTriangle(VisibleObj[i]).DrawRight(Canvas, penColor); end; procedure T3DObject.Clear; var i: Integer; begin VisibleObj.Clear; for i := 0 to ListObj.Count - 1 do T3DTriangle(ListObj[i]).Free; ListObj.Clear; end; procedure T3DObject.Add3(P1,P2,P3: T3DPoint; R1,R2,R3: Boolean; BrushColor,PenColor: TColor); begin ListObj.Add(T3DTriangle.Create(_Move(P1,CenterPoint),_Move(P2,CenterPoint),_Move(P3,CenterPoint), R1,R2,R3, BrushColor, PenColor)); end; procedure T3DObject.Add4(P1,P2,P3,P4: T3DPoint; R1,R2,R3,R4: Boolean; BrushColor,PenColor: TColor); begin Add3(P1,P2,P3, R1,R2,False, BrushColor, PenColor); Add3(P1,P3,P4, False,R3,R4, BrushColor, PenColor); end; ///// constructor T3DScene.Create; begin inherited Create; List3DObj := TList.Create; end; destructor T3DScene.Destroy; var i: Integer; begin for i := 0 to List3DObj.Count - 1 do T3DObject(List3DObj[i]).Free; List3DObj.Free; inherited Destroy; end; procedure T3DScene.Draw(Canvas: TCanvas); var i: Integer; begin for i := 0 to List3DObj.Count - 1 do T3DObject(List3DObj[i]).Draw(Canvas); end; procedure T3DScene.DrawLeft(Canvas: TCanvas; penColor: TColor); var i: Integer; begin for i := 0 to List3DObj.Count - 1 do T3DObject(List3DObj[i]).DrawLeft(Canvas, penColor); end; procedure T3DScene.DrawRight(Canvas: TCanvas; penColor: TColor); var i: Integer; begin for i := 0 to List3DObj.Count - 1 do T3DObject(List3DObj[i]).DrawRight(Canvas, penColor); end; procedure T3DScene.Add(obj: T3DObject); begin List3DObj.Add(obj); end; procedure T3DScene.CalcScreenCoords(cam: T3DCameraViewAnaglyph); var i,j: Integer; obj1,obj2: T3DObject; begin for i := 0 to List3DObj.Count - 1 do T3DObject(List3DObj[i]).CalcScreenCoords(cam); for i := 0 to List3DObj.Count - 1 do for j := 0 to List3DObj.Count - 1 do if i <> j then begin obj1 := T3DObject(List3DObj[i]); obj2 := T3DObject(List3DObj[j]); if obj1.DistToCamera > obj2.DistToCamera then List3DObj.Exchange(i,j); end; end; end.
unit taito_cchip; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} rom_engine,upd7810,cpu_misc,main_engine,timer_engine; type cchip_chip=class constructor create(clock:dword;frame:word); destructor free; public upd7810:cpu_upd7810; function asic_r(direccion:word):byte; procedure asic_w(direccion:word;valor:byte); function mem_r(direccion:word):byte; procedure mem_w(direccion:word;valor:byte); procedure set_int; procedure reset; function get_eeprom_dir:pbyte; procedure change_ad(ad_in:upd7810_cb); procedure change_in(ca,cb,cc,cd,cf:upd7810_cb); private upd4464_ram:array[0..7,0..$3ff] of byte; asic_ram:array[0..3] of byte; upd4464_bank:byte; cchip_rom:array[0..$fff] of byte; eeprom:array[0..$1fff] of byte; in_ad:function:byte; in_ca,in_cb,in_cc,in_cd,in_cf:function:byte; end; var cchip_0:cchip_chip; cchip_timer:byte; implementation const tcchip_rom:tipo_roms=(n:'cchip_upd78c11.bin';l:$1000;p:0;crc:$43021521); procedure cchip_chip.change_ad(ad_in:upd7810_cb); begin self.in_ad:=ad_in; end; procedure cchip_chip.change_in(ca,cb,cc,cd,cf:upd7810_cb); begin self.in_ca:=ca; self.in_cb:=cb; self.in_cc:=cc; self.in_cd:=cd; self.in_cf:=cf; end; function an_0:byte; begin an_0:=(cchip_0.in_ad shr 0) and 1; end; function an_1:byte; begin an_1:=(cchip_0.in_ad shr 1) and 1; end; function an_2:byte; begin an_2:=(cchip_0.in_ad shr 2) and 1; end; function an_3:byte; begin an_3:=(cchip_0.in_ad shr 3) and 1; end; function an_4:byte; begin an_4:=(cchip_0.in_ad shr 4) and 1; end; function an_5:byte; begin an_5:=(cchip_0.in_ad shr 5) and 1; end; function an_6:byte; begin an_6:=(cchip_0.in_ad shr 6) and 1; end; function an_7:byte; begin an_7:=(cchip_0.in_ad shr 7) and 1; end; function ca_cb(mask:byte):byte; begin if addr(cchip_0.in_ca)<>nil then ca_cb:=cchip_0.in_ca else ca_cb:=$ff; end; function cb_cb(mask:byte):byte; begin if addr(cchip_0.in_cb)<>nil then cb_cb:=cchip_0.in_cb else cb_cb:=$ff; end; function cc_cb(mask:byte):byte; begin if addr(cchip_0.in_cc)<>nil then cc_cb:=cchip_0.in_cc else cc_cb:=$ff; end; function cd_cb(mask:byte):byte; begin if addr(cchip_0.in_cd)<>nil then cd_cb:=cchip_0.in_cd else cd_cb:=$ff; end; function cf_cb(mask:byte):byte; begin if addr(cchip_0.in_cf)<>nil then cf_cb:=cchip_0.in_cf else cf_cb:=$ff; end; function cchip_getbyte(direccion:word):byte; begin case direccion of 0..$fff:cchip_getbyte:=cchip_0.cchip_rom[direccion]; $1000..$13ff:cchip_getbyte:=cchip_0.mem_r(direccion and $3ff); $1400..$17ff:cchip_getbyte:=cchip_0.asic_r(direccion and $3ff); $2000..$3fff:cchip_getbyte:=cchip_0.eeprom[direccion and $1fff]; $ff00..$ffff:cchip_getbyte:=cchip_0.upd7810.ram[direccion and $ff]; end; end; procedure cchip_putbyte(direccion:word;valor:byte); begin case direccion of 0..$fff,$2000..$3fff:; //ROM + EEPROM $1000..$13ff:cchip_0.mem_w(direccion and $3ff,valor); $1400..$17ff:cchip_0.asic_w(direccion and $3ff,valor); $ff00..$ffff:cchip_0.upd7810.ram[direccion and $ff]:=valor; end; end; procedure clear_irq; begin timers.enabled(cchip_timer,false); cchip_0.upd7810.set_input_line(UPD7810_INTF1,CLEAR_LINE); end; constructor cchip_chip.create(clock:dword;frame:word); var dir:string; begin dir:=directory.arcade_list_roms[find_rom_multiple_dirs('cchip.zip')]; carga_rom_zip(dir+'cchip.zip',tcchip_rom.n,@self.cchip_rom,tcchip_rom.l,tcchip_rom.crc,false); self.upd7810:=cpu_upd7810.create(clock,frame,CPU_7810); self.upd7810.change_ram_calls(cchip_getbyte,cchip_putbyte); self.upd7810.change_an(an_0,an_1,an_2,an_3,an_4,an_5,an_6,an_7); self.upd7810.change_in(ca_cb,cb_cb,cc_cb,cd_cb,cf_cb); cchip_timer:=timers.init(self.upd7810.numero_cpu,10,clear_irq,nil,false); end; destructor cchip_chip.free; begin self.upd7810.free; end; procedure cchip_chip.reset; begin self.asic_ram[0]:=0; self.asic_ram[1]:=0; self.asic_ram[2]:=0; self.asic_ram[3]:=0; upd4464_bank:=0; self.upd7810.reset; end; function cchip_chip.get_eeprom_dir:pbyte; begin get_eeprom_dir:=@self.eeprom; end; function cchip_chip.asic_r(direccion:word):byte; begin if (direccion<$200) then asic_r:=self.asic_ram[direccion and 3]// 400-5ff is asic 'ram' else asic_r:=0; // 600-7ff is write-only(?) asic banking reg, may read as open bus or never assert /DTACK on read? end; procedure cchip_chip.asic_w(direccion:word;valor:byte); begin if (direccion=$200) then upd4464_bank:=valor else self.asic_ram[direccion and 3]:=valor; end; function cchip_chip.mem_r(direccion:word):byte; begin mem_r:=upd4464_ram[upd4464_bank and 7,direccion and $3ff]; end; procedure cchip_chip.mem_w(direccion:word;valor:byte); begin upd4464_ram[upd4464_bank and 7,direccion and $3ff]:=valor; end; procedure cchip_chip.set_int; begin cchip_0.upd7810.set_input_line(UPD7810_INTF1,ASSERT_LINE); timers.enabled(cchip_timer,true); end; end.
unit GX_EditBookmark; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm; type TfmEditBookmarks = class(TfmBaseForm) ed_Line: TEdit; l_BmIndex: TLabel; cmb_BmIndex: TComboBox; l_Module: TLabel; cmb_Module: TComboBox; l_Line: TLabel; b_Ok: TButton; b_Cancel: TButton; procedure cmb_ModuleChange(Sender: TObject); procedure ed_LineChange(Sender: TObject); procedure cmb_BmIndexChange(Sender: TObject); private procedure SetData(const _Module: string; _LineNo: Integer; _BmIndex: Integer); procedure GetData(out _Module: string; out _LineNo: Integer; out _BmIndex: Integer); procedure CheckInput; public class function Execute(_Owner: TWinControl; var _Module: string; var _LineNo: Integer; var _BmIndex: Integer): Boolean; overload; class function Execute(_Owner: TWinControl; const _Module: string; var _LineNo: Integer): Boolean; overload; constructor Create(_Owner: TComponent); override; destructor Destroy; override; end; implementation {$R *.dfm} uses GX_OtaUtils, GX_dzVclUtils; { TfmEditBookmarks } class function TfmEditBookmarks.Execute(_Owner: TWinControl; var _Module: string; var _LineNo, _BmIndex: Integer): Boolean; var frm: TfmEditBookmarks; begin frm := TfmEditBookmarks.Create(_Owner); try frm.SetData(_Module, _LineNo, _BmIndex); Result := (frm.ShowModal = mrok); if Result then frm.GetData(_Module, _LineNo, _BmIndex); finally FreeAndNil(frm); end; end; class function TfmEditBookmarks.Execute(_Owner: TWinControl; const _Module: string; var _LineNo: Integer): Boolean; var frm: TfmEditBookmarks; BmIndex: Integer; Module: string; begin frm := TfmEditBookmarks.Create(_Owner); try frm.SetData(_Module, _LineNo, -1); frm.cmb_BmIndex.Visible := False; frm.l_BmIndex.Visible := False; Result := (frm.ShowModal = mrok); if Result then frm.GetData(Module, _LineNo, BmIndex); finally FreeAndNil(frm); end; end; constructor TfmEditBookmarks.Create(_Owner: TComponent); resourcestring rcNext = 'Next'; var i: Integer; List: TList; ui: TUnitInfo; begin inherited; TControl_SetMinConstraints(Self); TComboBox_SetDropdownWidth(cmb_Module, Self.Width); List := TList.Create; try GxOtaFillUnitInfoListForCurrentProject(List); for i := 0 to List.Count - 1 do begin ui := TObject(List[i]) as TUnitInfo; cmb_Module.Items.AddObject(ExtractFileName(ui.Filename), ui); end; finally FreeAndNil(List); end; // -1 would raise an exception in Delphi 6 when retrieving it again, but -2 is fine too TComboBox_AddIntObject(cmb_BmIndex, rcNext, -2); for i := 0 to 19 do begin TComboBox_AddIntObject(cmb_BmIndex, IntToStr(i), i); end; end; destructor TfmEditBookmarks.Destroy; begin TComboBox_ClearWithObjects(cmb_Module); inherited; end; procedure TfmEditBookmarks.cmb_BmIndexChange(Sender: TObject); begin CheckInput; end; procedure TfmEditBookmarks.cmb_ModuleChange(Sender: TObject); begin CheckInput; end; procedure TfmEditBookmarks.ed_LineChange(Sender: TObject); begin CheckInput; end; procedure TfmEditBookmarks.CheckInput; var b: Boolean; Value: Integer; s: string; begin b := TComboBox_GetSelected(cmb_Module, s); b := b and TryStrToInt(ed_Line.Text, Value) and (Value > 0); // bmIndex may be left empty b_Ok.Enabled := b; end; procedure TfmEditBookmarks.SetData(const _Module: string; _LineNo, _BmIndex: Integer); begin TComboBox_Select(cmb_Module, ExtractFileName(_Module)); TComboBox_SelectByObject(cmb_BmIndex, _BmIndex); ed_Line.Text := IntToStr(_LineNo); end; procedure TfmEditBookmarks.GetData(out _Module: string; out _LineNo, _BmIndex: Integer); resourcestring rcSelectAModule = 'You must select a module.'; var ui: TUnitInfo; begin if not TComboBox_GetSelectedObject(cmb_Module, Pointer(ui)) then raise Exception.Create(rcSelectAModule); _Module := ui.Filename; _BmIndex := TComboBox_GetSelectedObjectDef(cmb_BmIndex, -1); _LineNo := StrToInt(ed_Line.Text); end; end.
{ CoreGraphics - CGDataProvider.h * Copyright (c) 1999-2004 Apple Computer, Inc. * All rights reserved. } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGDataProvider; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CFData,CGBase,CFURL; {$ALIGN POWER} type CGDataProviderRef = ^SInt32; { an opaque 32-bit type } { This callback is called to copy `count' bytes from the sequential data * stream to `buffer'. } type CGDataProviderGetBytesCallback = function( info: UnivPtr; buffer: UnivPtr; count: size_t ): size_t; { This callback is called to skip `count' bytes forward in the sequential * data stream. } type CGDataProviderSkipBytesCallback = procedure( info: UnivPtr; count: size_t ); { This callback is called to rewind to the beginning of sequential data * stream. } type CGDataProviderRewindCallback = procedure( info: UnivPtr ); { This callback is called to release the `info' pointer when the data * provider is freed. } type CGDataProviderReleaseInfoCallback = procedure( info: UnivPtr ); { Callbacks for sequentially accessing data. * `getBytes' is called to copy `count' bytes from the sequential data * stream to `buffer'. It should return the number of bytes copied, or 0 * if there's no more data. * `skipBytes' is called to skip ahead in the sequential data stream by * `count' bytes. * `rewind' is called to rewind the sequential data stream to the beginning * of the data. * `releaseProvider', if non-NULL, is called to release the `info' pointer * when the provider is freed. } type CGDataProviderCallbacks = record getBytes: CGDataProviderGetBytesCallback; skipBytes: CGDataProviderSkipBytesCallback; rewind: CGDataProviderRewindCallback; releaseProvider: CGDataProviderReleaseInfoCallback; end; { This callback is called to get a pointer to the entire block of data. } type CGDataProviderGetBytePointerCallback = function( info: UnivPtr ): UnivPtr; { This callback is called to release the pointer to entire block of * data. } type CGDataProviderReleaseBytePointerCallback = procedure( info: UnivPtr; pointr: {const} UnivPtr ); { This callback is called to copy `count' bytes at byte offset `offset' * into `buffer'. } type CGDataProviderGetBytesAtOffsetCallback = function( info: UnivPtr; buffer: UnivPtr; offset: size_t; count: size_t ): size_t; { Callbacks for directly accessing data. * `getBytePointer', if non-NULL, is called to return a pointer to the * provider's entire block of data. * `releaseBytePointer', if non-NULL, is called to release a pointer to * the provider's entire block of data. * `getBytes', if non-NULL, is called to copy `count' bytes at offset * `offset' from the provider's data to `buffer'. It should return the * number of bytes copied, or 0 if there's no more data. * `releaseProvider', if non-NULL, is called when the provider is freed. * * At least one of `getBytePointer' or `getBytes' must be non-NULL. } type CGDataProviderDirectAccessCallbacks = record getBytePointer: CGDataProviderGetBytePointerCallback; releaseBytePointer: CGDataProviderReleaseBytePointerCallback; getBytes: CGDataProviderGetBytesAtOffsetCallback; releaseProvider: CGDataProviderReleaseInfoCallback; end; { Return the CFTypeID for CGDataProviderRefs. } function CGDataProviderGetTypeID: CFTypeID; external name '_CGDataProviderGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Create a sequential-access data provider using `callbacks' to provide * the data. `info' is passed to each of the callback functions. } function CGDataProviderCreate( info: UnivPtr; const (*var*) callbacks: CGDataProviderCallbacks ): CGDataProviderRef; external name '_CGDataProviderCreate'; { Create a direct-access data provider using `callbacks' to supply `size' * bytes of data. `info' is passed to each of the callback functions. } function CGDataProviderCreateDirectAccess( info: UnivPtr; size: size_t; const (*var*) callbacks: CGDataProviderDirectAccessCallbacks ): CGDataProviderRef; external name '_CGDataProviderCreateDirectAccess'; { The callback used by `CGDataProviderCreateWithData'. } type CGDataProviderReleaseDataCallback = procedure( info: UnivPtr; data: {const} UnivPtr; size: size_t ); { Create a direct-access data provider using `data', an array of `size' * bytes. `releaseData' is called when the data provider is freed, and is * passed `info' as its first argument. } function CGDataProviderCreateWithData( info: UnivPtr; data: {const} UnivPtr; size: size_t; releaseData: CGDataProviderReleaseDataCallback ): CGDataProviderRef; external name '_CGDataProviderCreateWithData'; { Create a direct-access data provider which reads from `data'. } function CGDataProviderCreateWithCFData( data: CFDataRef ): CGDataProviderRef; external name '_CGDataProviderCreateWithCFData'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Create a data provider using `url'. } function CGDataProviderCreateWithURL( url: CFURLRef ): CGDataProviderRef; external name '_CGDataProviderCreateWithURL'; { Equivalent to `CFRetain(provider)'. } function CGDataProviderRetain( provider: CGDataProviderRef ): CGDataProviderRef; external name '_CGDataProviderRetain'; { Equivalent to `CFRelease(provider)'. } procedure CGDataProviderRelease( provider: CGDataProviderRef ); external name '_CGDataProviderRelease'; {* DEPRECATED FUNCTIONS *} { Don't use this function; use CGDataProviderCreateWithURL instead. } function CGDataProviderCreateWithFilename( filename: ConstCStringPtr ): CGDataProviderRef; external name '_CGDataProviderCreateWithFilename'; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpTTBCPadding; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIBlockCipherPadding, ClpITBCPadding, ClpISecureRandom, ClpCryptoLibTypes; type /// <summary> A padder that adds Trailing-Bit-Compliment padding to a block. /// <p> /// This padding pads the block out compliment of the last bit /// of the plain text. /// </p> /// </summary> TTBCPadding = class sealed(TInterfacedObject, ITBCPadding, IBlockCipherPadding) strict private /// <returns> /// return the name of the algorithm the cipher implements. /// </returns> function GetPaddingName: String; inline; public /// <summary> /// Initialise the padder. /// </summary> /// <param name="random"> /// a SecureRandom if available. /// </param> procedure Init(const random: ISecureRandom); /// <summary> /// Return the name of the algorithm the cipher implements. /// </summary> property PaddingName: String read GetPaddingName; /// <summary> add the pad bytes to the passed in block, returning the /// number of bytes added. /// <p> /// Note: this assumes that the last block of plain text is always /// passed to it inside in. i.e. if inOff is zero, indicating the /// entire block is to be overwritten with padding the value of in /// should be the same as the last block of plain text. /// </p> /// </summary> function AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; /// <summary> /// return the number of pad bytes present in the block. /// </summary> /// <param name="input"> /// block to count pad bytes in /// </param> /// <returns> /// the number of pad bytes present in the block. /// </returns> function PadCount(const input: TCryptoLibByteArray): Int32; end; implementation { TTBCPadding } function TTBCPadding.AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; var count: Int32; code: Byte; begin count := System.Length(input) - inOff; if (inOff > 0) then begin if (input[inOff - 1] and $01) = 0 then begin code := Byte($FF) end else begin code := Byte($00) end; end else begin if (input[System.Length(input) - 1] and $01) = 0 then begin code := Byte($FF) end else begin code := Byte($00) end; end; while (inOff < System.Length(input)) do begin input[inOff] := code; System.Inc(inOff); end; result := count; end; function TTBCPadding.GetPaddingName: String; begin result := 'TBC'; end; {$IFNDEF _FIXINSIGHT_} procedure TTBCPadding.Init(const random: ISecureRandom); begin // nothing to do. end; {$ENDIF} function TTBCPadding.PadCount(const input: TCryptoLibByteArray): Int32; var code: Byte; index: Int32; begin code := input[System.Length(input) - 1]; index := System.Length(input) - 1; while ((index > 0) and (input[index - 1] = code)) do begin System.Dec(index); end; result := System.Length(input) - index; end; end.
{ ---------------------------------------------------------------------------- zbnc - Multi user IRC bouncer Copyright (c) Michael "Zipplet" Nixon 2009. Licensed under the MIT license, see license.txt in the project trunk. Unit: zipplet.pas Purpose: Random functions (to be sorted later) ---------------------------------------------------------------------------- } unit zipplet; interface uses sysutils; type tllitem = class(tobject) ptr_prev, ptr_next: tllitem; item: pointer; tag: integer; strtag: string; end; tlinkedlist = class(tobject) item_first, item_last: tllitem; item_count: integer; onadditem: function: pointer of object; ondelitem: procedure(item: pointer) of object; function add(item: pointer; integer_tag: integer; string_tag: string = ''): tllitem; function addnew(integer_tag: integer; string_tag: string = ''): tllitem; procedure flush; procedure delete(item: tllitem); function find(integer_tag: integer): tllitem; function strfind(string_tag: string): tllitem; function findnext(integer_tag: integer; last_item: tllitem): tllitem; function strfindnext(string_tag: string; last_item: tllitem): tllitem; constructor create; destructor destroy; override; end; function nativepath(path: string): string; function ipstrtoint(s: string): integer; function ipinttostr(i: integer): string; function strtok(s, sep: string; var index: integer; quoted: boolean; var output: string): boolean; implementation // ----------------------------------------------------------------------------- // Create linked list item // ----------------------------------------------------------------------------- constructor tlinkedlist.create; begin inherited create; item_first := nil; item_last := nil; item_count := 0; end; // ----------------------------------------------------------------------------- // Add an item to the list. Return tllitem. // ----------------------------------------------------------------------------- function tlinkedlist.add(item: pointer; integer_tag: integer; string_tag: string = ''): tllitem; var i: tllitem; begin i := tllitem.create; i.tag := integer_tag; i.strtag := string_tag; i.item := item; if item_count = 0 then begin i.ptr_prev := nil; i.ptr_next := nil; item_first := i; item_last := i; end else begin i.ptr_prev := item_last; i.ptr_next := nil; item_last.ptr_next := i; item_last := i; end; inc(item_count); result := i; end; // ----------------------------------------------------------------------------- // Create an item and add it to the list. Return tllitem. // ----------------------------------------------------------------------------- function tlinkedlist.addnew(integer_tag: integer; string_tag: string = ''): tllitem; var x: pointer; begin if not assigned(onadditem) then begin raise exception.create('Cannot addnew when onadditem is not assigned. Use add instead.'); exit; end else begin x := onadditem; end; result := add(x, integer_tag, string_tag); end; // ----------------------------------------------------------------------------- // Flush the list. // ----------------------------------------------------------------------------- procedure tlinkedlist.flush; var i, i2: tllitem; begin i := item_first; while assigned(i) do begin i2 := i.ptr_next; if assigned(ondelitem) then ondelitem(i.item); i.Destroy; i := i2; end; item_count := 0; item_first := nil; item_last := nil; end; // ----------------------------------------------------------------------------- // Delete specified item // ----------------------------------------------------------------------------- procedure tlinkedlist.delete(item: tllitem); begin if assigned(ondelitem) then ondelitem(item.item); if assigned(item.ptr_prev) then item.ptr_prev.ptr_next := item.ptr_next; if assigned(item.ptr_next) then item.ptr_next.ptr_prev := item.ptr_prev; if not assigned(item.ptr_prev) then item_first := item.ptr_next; if not assigned(item.ptr_next) then item_last := item.ptr_prev; dec(item_count); end; // ----------------------------------------------------------------------------- // Find item based on integer tag, and return item // ----------------------------------------------------------------------------- function tlinkedlist.find(integer_tag: integer): tllitem; var i: tllitem; begin result := nil; i := item_first; while assigned(i) do begin if i.tag = integer_tag then begin result := i; exit; end; i := i.ptr_next; end; end; // ----------------------------------------------------------------------------- // Find item based on string tag. Return item // ----------------------------------------------------------------------------- function tlinkedlist.strfind(string_tag: string): tllitem; var i: tllitem; begin result := nil; i := item_first; while assigned(i) do begin if i.strtag = string_tag then begin result := i; exit; end; i := i.ptr_next; end; end; // ----------------------------------------------------------------------------- // Find next item based on tag // ----------------------------------------------------------------------------- function tlinkedlist.findnext(integer_tag: integer; last_item: tllitem): tllitem; var i: tllitem; begin result := nil; i := last_item; while assigned(i) do begin if i.tag = integer_tag then begin result := i; exit; end; i := i.ptr_next; end; end; // ----------------------------------------------------------------------------- // Find next item based on string tag // ----------------------------------------------------------------------------- function tlinkedlist.strfindnext(string_tag: string; last_item: tllitem): tllitem; var i: tllitem; begin result := nil; i := last_item; while assigned(i) do begin if i.strtag = string_tag then begin result := i; exit; end; i := i.ptr_next; end; end; // ----------------------------------------------------------------------------- // Destructor - linked list // ----------------------------------------------------------------------------- destructor tlinkedlist.destroy; begin flush; inherited destroy; end; // ----------------------------------------------------------------------------- // Convert slashes in a path to make the path native to the OS it's running // on. This means they become \ inside windows, and / inside unix. // ----------------------------------------------------------------------------- function nativepath(path: string): string; var i: integer; begin result := path; for i := 1 to length(path) do begin if (copy(path, i, 1) = '\') or (copy(path, i, 1) = '/') then {$ifdef unix} result[i] := '/'; {$else} result[i] := '\'; {$endif} end; end; // ----------------------------------------------------------------------------- // String tokeniser. Returns the next token from the string. <start> is modified // and always points to the next character to be read, and will > length(s) if // there are no more tokens. Blank tokens are permitted. <quoted> if true will // allow strtok to interpret quotes " " to allow spaces inside tokens. // WARNING: Unsafe! Does not limit length of returned string. // Boolean result: True = more tokens available, False = End reached. // ----------------------------------------------------------------------------- function strtok(s, sep: string; var index: integer; quoted: boolean; var output: string): boolean; var done, inquote: boolean; start: integer; begin inquote := false; // Sanity check if index > length(s) then begin // Illegal start - no tokens result := false; exit; end; // Loop past any whitespace at the begin. This is required because when a // token is found the index points at whitespace. repeat done := true; if s[index] = sep then begin inc(index); done := false; end; if index > length(s) then begin // End of string result := false; exit; end; until done; start := index; done := false; repeat if index > length(s) then begin // Can't possibly be more tokens done := true; end else begin // First, the quote test if quoted then begin if s[index] = #34 then begin if inquote then inquote := false else inquote := true; end; end; if not inquote then begin if s[index] = sep then begin // Seperator done := true; end; end; end; inc(index); until done; output := copy(s, start, index - start - 1); result := true; end; // ----------------------------------------------------------------------------- // Convert a string (dotted) ipv4 address into a 32-bit integer in network byte // order. // ----------------------------------------------------------------------------- function ipstrtoint(s: string): integer; var a: string; i: integer; x: integer; begin result := 0; try a := s; x := pos('.', a); i := strtoint(copy(a, 1, x - 1)); a := copy(a, x + 1, length(a) - x); result := result or i; x := pos('.', a); i := strtoint(copy(a, 1, x - 1)); a := copy(a, x + 1, length(a) - x); result := result or (i shl 8); x := pos('.', a); i := strtoint(copy(a, 1, x - 1)); a := copy(a, x + 1, length(a) - x); result := result or (i shl 16); i := strtoint(a); result := result or (i shl 24); except result := 0; end; end; // ----------------------------------------------------------------------------- // Convert an ipv4 32-bit integer in network byte order address into a dotted // string. // ----------------------------------------------------------------------------- function ipinttostr(i: integer): string; begin result := inttostr(i and $FF) + '.' + inttostr((i shr 8) and $FF) + '.' + inttostr((i shr 16) and $FF) + '.' + inttostr((i shr 24) and $FF); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerOctetString; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes, ClpAsn1Tags, ClpDerOutputStream, ClpIProxiedInterface, ClpAsn1OctetString, ClpIDerOctetString; type TDerOctetString = class(TAsn1OctetString, IDerOctetString) public /// <param name="str">The octets making up the octet string.</param> constructor Create(const str: TCryptoLibByteArray); overload; constructor Create(const obj: IAsn1Encodable); overload; destructor Destroy(); override; procedure Encode(const derOut: TStream); overload; override; class procedure Encode(const derOut: TDerOutputStream; const bytes: TCryptoLibByteArray; offset, length: Int32); reintroduce; overload; static; inline; end; implementation { TDerOctetString } constructor TDerOctetString.Create(const str: TCryptoLibByteArray); begin Inherited Create(str); end; constructor TDerOctetString.Create(const obj: IAsn1Encodable); begin Inherited Create(obj); end; destructor TDerOctetString.Destroy; begin inherited Destroy; end; procedure TDerOctetString.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.OctetString, str); end; class procedure TDerOctetString.Encode(const derOut: TDerOutputStream; const bytes: TCryptoLibByteArray; offset, length: Int32); begin derOut.WriteEncoded(TAsn1Tags.OctetString, bytes, offset, length); end; end.
unit mgLngLst; (* // // module: mglnglst.pas // author: Mickael P. Golovin // // Copyright (c) 1997-2000 by Archivarius Team, free for non commercial use. // // $Id: mglnglst.pas,v 1.2 2014/08/21 07:02:08 lulin Exp $ // *) {$I m0Define.inc} interface uses Windows, Messages, SysUtils, Consts, Classes, l3Types, l3Base, m0Const, //m0AddTyp, //m0MEMLib, //m0IDPLib, //mgConst, mgBasLst ; type TmgLangFormHandle = class(TmgBaseHandle) private FStatus: longint; FValue: string; protected // internal methods class function IsCacheable: Bool; override; {-} public property Status: longint Read FStatus Write FStatus; property Value: string Read FValue Write FValue; procedure AssignHandle(AItem: TmgBaseHandle); override; end;//TmgLangFormHandle PmgLangFormHandleKey = ^TmgLangFormHandleKey; TmgLangFormHandleKey = packed record RBuff: PAnsiChar; RSize: longint; end;//TmgLangFormHandleKey TmgLangFormHandleList = class(TmgBaseHandleList) private function pm_GetHandle(AIndex: longint): TmgLangFormHandle; reintroduce; protected procedure AllocItem(var AItem: Pointer); override; function CompareKeyByItem(AKey: Pointer; AItem: Pointer): integer; override; public property Handles[AIndex: longint]: TmgLangFormHandle Read pm_GetHandle; function BinSearchByKey(ABuff: PAnsiChar; ASize: longint; var AIndex: longint): longbool; end;//TmgLangFormHandleList implementation uses m2MemLib ; // start class TmgLangFormHandle class function TmgLangFormHandle.IsCacheable: Bool; //override; {-} begin Result := True; end; procedure TmgLangFormHandle.AssignHandle(AItem: TmgBaseHandle); var LItem: TmgLangFormHandle absolute AItem; begin Status := LItem.Status; Value := LItem.Value; end; // start class TmgLangFormHandleList function TmgLangFormHandleList.pm_GetHandle(AIndex: longint): TmgLangFormHandle; begin Result := TmgLangFormHandle(GetItem(AIndex)); end; procedure TmgLangFormHandleList.AllocItem(var AItem: Pointer); var LItem: TmgLangFormHandle absolute AItem; begin LItem := TmgLangFormHandle.Create; end; function TmgLangFormHandleList.CompareKeyByItem(AKey: Pointer; AItem: Pointer): integer; var LItem: TmgLangFormHandle absolute AItem; LKey: PmgLangFormHandleKey absolute AKey; begin with LKey^ do with LItem do Result := m2MEMCompare(Pointer(RBuff), RSize, Pointer(Value), Length(Value)); end; function TmgLangFormHandleList.BinSearchByKey(ABuff: PAnsiChar; ASize: longint; var AIndex: longint): longbool; var LKey: TmgLangFormHandleKey; begin with LKey do begin RBuff := ABuff; RSize := ASize; end; Result := FindItemByKey( @LKey, AIndex); end; end.
unit Framework.Interfaces; interface uses System.SysUtils; type IDataValidator = interface(IInterface) ['{D022EC8D-13B4-4BA0-96EE-C4E14E022696}'] function Parse(const AValue: Variant): Boolean; end; IValidationRule = interface(IInterface) ['{7CD39036-1AB4-4D63-BDD7-E14D2AE76396}'] function Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; end; IField = interface(IInterface) ['{17A1E04E-9020-4E17-BC2F-2D0D3E144960}'] function GetName: String; procedure SetName(const AName: String); function GetValue: Variant; procedure SetValue(const AValue: Variant); property Name: String read GetName write SetName; function Parse(var AReasonForRejection: String): Boolean; property Value: Variant read GetValue write SetValue; end; IRecord = interface(IInterface) ['{49628DFF-B6B4-489D-8419-5F63ABD2D889}'] function GetFields: TArray<IField>; function FieldByName(const AFieldName: String): IField; procedure AddField(const AField: IField); property Fields: TArray<IField> read GetFields; end; IFile = interface(IInterface) ['{960B153E-2687-40D1-A1F9-9DF228A07D14}'] procedure LoadFromFile(const AFileName: string); overload; procedure SaveToFile(const AFileName: string); overload; procedure LoadFromFile(const AFileName: string; AEncoding: TEncoding); overload; procedure SaveToFile(const AFileName: string; AEncoding: TEncoding); overload; function Add(const AString: string): Integer; function GetCount: Integer; property Count: Integer read GetCount; procedure Clear; end; IDefinition = interface(IInterface) ['{1F86BADE-DA3F-4A33-AF36-8FB2F815FB74}'] procedure LoadFromFile(const AFileName: string); overload; procedure LoadFromFile(const AFileName: string; AEncoding: TEncoding); overload; function Prepare: Boolean; end; implementation end.
unit K619338871; {* [Requestlink:619338871] } // Модуль: "w:\common\components\rtl\Garant\Daily\K619338871.pas" // Стереотип: "TestCase" // Элемент модели: "K619338871" MUID: (56E010DE0110) // Имя типа: "TK619338871" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK619338871 = class(TRTFtoEVDWriterTest) {* [Requestlink:619338871] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK619338871 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56E010DE0110impl_uses* //#UC END# *56E010DE0110impl_uses* ; function TK619338871.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK619338871.GetFolder function TK619338871.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56E010DE0110'; end;//TK619338871.GetModelElementGUID initialization TestFramework.RegisterTest(TK619338871.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit uxmldoc; { Ollivier Civiol - 2019 ollivier@civiol.eu https://ollivierciviolsoftware.wordpress.com/ } {$MODE Delphi} // // XmlDoc : XMlDocument, Ollivier Civiol 2014 // interface {$define O_INLINE} uses Classes, SysUtils, OXmlReadWrite, Variants; const XML_CDATA = 'CDATA'; XML_COMMENT = 'COMMENT'; XML_DOCTYPE = 'DOCTYPE'; type TXMLDoc = Class; { TXMLElement } TXMLElement = Class(TObject) private FElements : TList; FAttributes: TStringList; FTagName : String; FText: String; FLine : int64; FOwner : TXMLDoc; FParent : TXMLElement; FTokenType: TXMLReaderTokenType; function GetIndex: Integer; procedure SetTagName(const aName : String); protected function GetElement(index : integer):TXMLElement; overload; function GetAttribute(index : integer):string; overload; function GetAttributeValue(index : integer):string; function GetShortAttributeValue(index : integer):string; function GetNbElements:integer; {$ifdef RELEASE}inline;{$endif} function GetNbAttributes:integer; inline; function GetAttribList:String; function GetElemValue:String; inline; procedure SetElementValue(const aValue : String); function GetAttribs:String; function GetLevel:Integer; function GetText:String; procedure SetText(const aText : String); procedure DoBeforeNodeChange; procedure DoAfterNodeChange; procedure DoOnAddChildNode(aChildNode : TXMLElement); function GetNodePath:String; function GetLine:Int64; inline; procedure SetLine(aLine : int64); //function GetTagName:String; function GetElements:TList; inline; procedure StartLoad(Token: PXMLReaderToken; Reader : TXMLReader); procedure Load(var Token: PXMLReaderToken; Reader : TXMLReader); procedure Save(Writer : TXMLWriter; omitXMLDeclaration : Boolean = False); function Locate(aElem : TXMLElement) : Integer; function GetParent:TXMLElement; inline; procedure MoveTo(aNewParent : TXMLElement); property Attribute[index : integer] : string read GetAttribute; public constructor Create; overload; constructor Create(aOwner, aParent : TObject); overload; constructor Create(aParent : TXMLElement; aName, aText : String; TokenType: TXMLReaderTokenType; aLine : int64); overload; destructor Destroy; override; procedure Assign(aElem : TXMLElement); procedure AddText(const txt : String); procedure Clear; procedure ClearChildren; function FirstChild : TXMLElement; function NextSibling : TXMLElement; function AddChildNode(const aName : String):TXMLElement; procedure DeleteChildNode(aNode : TXMLElement); function InsertNode(aNode : TXMLElement):TXMLElement; procedure SetValueByElement(const aNodeName, aValue : String); function NodeByAttributeValue(const aNodeName, AAttributeName, AValue: string):TXMLElement; procedure RemoveChild(aNode : TXMLElement); function SelectSingleNode(const aNodeName : String):TXMLElement; function SelectNodes(const aName : String) : TList; procedure SwapElements(aFirst, aSecond : Integer); // CP added functions function GetAttributeName(index : integer):string; inline; procedure AddAttrib(const attr : String); inline; function GetAttribute(const AName: string): variant; overload; procedure RemoveAttribute(const AName: string); overload; procedure RemoveAttribute(index: integer); overload; function GetAttributeStr(const AName: string): string; function GetAttributeBool(const AName: string; vDefault : Boolean = False): boolean; //procedure GetAttributeHex(const AName: string; var aArr: TArray<Byte>); function GetAttributeInt(const AName: string): Int64; procedure SetAttribute(const AName: string; AValue: Variant); procedure SetAttributeBool(const AName: string; AValue: Boolean); procedure SetAttributeDate(const aName: String; const aValue: TDateTime); function GetAttributeDate(const AName: string; AValue: TDateTime):TDateTime; //procedure SetAttributeHex(const AName: string; aArr : TArray<Byte>); function GetNode(const aNodeName : String; bAutoCreate : Boolean = True):TXMLElement; function GetValueByElement(const aNodeName: string; var AValue: string): boolean; overload; function GetValueByElement(const aNodeName: string): string; overload; function GetElementByValue(const AElementName, AValue: string): TXMLElement; function GetNodeByElementValue(const aNodeName, AElementName, AValue: string; bAutoCreate : Boolean = True): TXMLElement; function GetNodeByAttributeValue(const aNodeName, AAttributeName, AValue: string; bAutoCreate : Boolean = True): TXMLElement; // compare node structures function Compare(AElement: TXMLElement): boolean; property Level : integer read GetLevel; /// property Line : int64 read GetLine write SetLine; // TagName, NodeName : same difference /// property TagName : String read FTagName write SetTagName; property NodeName : String read FTagName write SetTagName; property Text : String read GetText write SetText; property NbElements : integer read GetNbElements; property NbAttributes : integer read GetNbAttributes; property Elements[index : integer] : TXMLElement read GetElement; property Index:Integer read GetIndex; // tweek to offer MSXML compatibility //property ChildNodes : TList read GetElements; property Attribs : String read GetAttribs; property AttributeValue[index : integer] : String read GetAttributeValue; property AttributeName[index : integer] : string read GetAttributeName; property ShortAttributeValue[index : integer] : string read GetShortAttributeValue; property Attributes : TStringList read FAttributes; property Path : String read GetNodePath; property Parent : TXMLElement read GetParent; // tweek to offer MSXML compatibility property nodeTypedValue : String read GetElemValue write SetElementValue; property TokenType: TXMLReaderTokenType read FTokenType; property Owner : TXMLDoc read FOwner; end; TNodeChangeEvent = procedure (aNode : TXMLElement) of object; TNodeChildEvent = procedure (aNode, aChildNode : TXMLElement) of object; TXMLDoc = Class(TObject) private FElement : TXMLElement; //XMLReader : TXMLReader; //XMLWriter : TXMLWriter; FFilename : String; FBeforeNodeChange : TNodeChangeEvent; FAfterNodeChange : TNodeChangeEvent; FOnAddChildNode : TNodeChildEvent; FOnDeleteNode : TNodeChildEvent; FomitXMLDeclaration : Boolean; FModified : Boolean; procedure LoadData(XMLReader : TXMLReader); function GetReader:TXMLReader; function GetWriter:TXMLWriter; protected function GetDocumentElement:TXMLElement; function GetAsString:String; procedure SetAsString(const aString : String); function GetElement:TXMLElement; function GetomitXMLDeclaration:Boolean; procedure SetomitXMLDeclaration(aVal : Boolean); function GetFilename:String; procedure SetModified(Sender : TObject); public constructor Create; destructor Destroy; override; procedure Clear; function CreateNewDocumentElement(const aName : String):TXMLElement; procedure MoveElement(aElement, aNewParent : TXMLElement); procedure loadXML(const aXMLStr : String); procedure LoadFromFile(const afilename : String); procedure SaveToFile(const afilename : String); procedure SaveToStream(aStream : TStream; {bWriteBom : Boolean = True; }aOmitXMLDeclaration : boolean = False); procedure LoadFromStream(aStream : TStream); function GetNodeFromPath(const aPath : String):TXMLElement; property DocumentElement : TXMLElement read GetDocumentElement; property Element : TXMLElement read GetElement; property Filename : String read GetFilename; property AsString : String read GetAsString write SetAsString; property XML : String read GetAsString; property omitXMLDeclaration : Boolean read GetomitXMLDeclaration write SetomitXMLDeclaration; // Callback events property BeforeNodeChange : TNodeChangeEvent read FBeforeNodeChange write FBeforeNodeChange; property AfterNodeChange : TNodeChangeEvent read FAfterNodeChange write FAfterNodeChange; property OnAddChildNode : TNodeChildEvent read FOnAddChildNode write FOnAddChildNode; property OnDeleteChildNode : TNodeChildEvent read FOnDeleteNode write FOnDeleteNode; property Modified : Boolean Read FModified; end; { // tweek to offer MSXML compatibility TListEx = Class(TListExIntf) private function Getcount : integer; function GetElement(index : integer):TXMLElement; public property length : Integer read Getcount; property Item[index : integer] : TXMLElement read GetElement; End; TXMLElementList = Class(TListEx); IXMLDOMNodeList = TXMLElementList; } implementation uses OTextReadWrite, VariantUtils, DateUtils; { function TListEx.Getcount : Integer; begin result := Count; End; function TListEx.GetElement(index : integer):TXMLElement; begin result := Items[index]; end; } function _IsDateTime(aText : String): Boolean; {$ifdef O_INLINE} inline; {$endif} begin result := False; // is xmldatetime if (length(aText) = 23) or (length(aText) = 19) then result := (aText[5] = '-') and (aText[11] = 'T'); end; function _IsDate(aText : String): Boolean; {$ifdef O_INLINE} inline; {$endif} begin // 2015-12-31 result := False; if length(aText) = 10 then begin result := (aText[5] = '-') and (aText[8] = '-'); if result then try strtoint(copy(aText, 1, 4)); strtoint(copy(aText, 6, 2)); strtoint(copy(aText, 9, 2)); except result := False; end; end; end; function _XmlDateToDateTime(aXmlDate : String):TDateTime; var sy, sm, sd, sh, smm, ss, sms : string; y, m, d, h, mm, s, ms : word; begin // i.e : 2015-01-01 sy := ''; sm := ''; sd := ''; sh := ''; smm := ''; ss := ''; sms := ''; if (length(aXmlDate) >= 10) and (_IsDate(aXmlDate) or _IsDateTime(aXmlDate)) then begin sy := copy(aXmlDate, 1, 4); sm := copy(aXmlDate, 6, 2); sd := copy(aXmlDate, 9, 2); end; // has time part // i.e : 2015-01-01T00:00:00 if (length(aXmlDate) >= 19) and _IsDateTime(aXmlDate) then begin sh := copy(aXmlDate, 12, 2); smm := copy(aXmlDate, 15, 2); ss := copy(aXmlDate, 18, 2); end; // has milliseconds part // i.e : 2015-01-01T00:00:00.000 // i.e : 2015-01-01T00:00:00.5 if (length(aXmlDate) > 19) and _IsDateTime(aXmlDate) then sms := copy(aXmlDate, 21, 3); y := StrToIntDef(sy, 0); m := StrToIntDef(sm, 0); d := StrToIntDef(sd, 0); h := StrToIntDef(sh, 0); mm := StrToIntDef(smm, 0); s := StrToIntDef(ss, 0); ms := StrToIntDef(sms, 0); Result := EncodeDateTime(y, m, d, h, mm, s, ms); end; constructor TXMLElement.Create; begin if FOwner = nil then Raise Exception.Create('Owner not initialized !'); inherited Create; end; constructor TXMLElement.Create(aOwner, aParent : TObject); begin FOwner := TXMLDoc(aOwner); FParent := TXMLElement(aParent); Create; FLine := 0; FElements := TList.Create; FAttributes := TStringList.Create; FAttributes.OnChange := Owner.SetModified; //FText := TStringList.Create; FText := ''; FTokenType := rtOpenElement; end; constructor TXMLElement.Create(aParent : TXMLElement; aName, aText : String; TokenType: TXMLReaderTokenType; aLine : int64); begin Create(aParent.FOwner, aParent); FTagName := aName; FText := aText; FTokenType := TokenType; FLine := aLine; end; destructor TXMLElement.Destroy; begin Clear; FElements.Free; FAttributes.Free; //FText.Free; inherited Destroy; end; procedure TXMLElement.Assign(aElem : TXMLElement); var i : Integer; Elem : TXMLElement; begin // assign child elements for i := 0 to aElem.NbElements - 1 do begin Elem := AddChildNode(TXMlelement(aElem.FElements[i]).TagName); Elem.Assign(aElem.FElements[i]); end; // assign attribs FAttributes.Text := aElem.Attributes.Text; FText := aElem.Text; FTokenType := aElem.TokenType; end; procedure TXMLElement.Clear; begin ClearChildren; FElements.Clear; FAttributes.Clear; FText := ''; end; procedure TXMLElement.ClearChildren; var i : integer; begin for i:=0 to NbElements-1 do TXMlelement(FElements[i]).Free; end; function TXMLElement.FirstChild : TXMLElement; begin result := nil; if NbElements > 0 then result := FElements[0]; end; function TXMLElement.Locate(aElem : TXMLElement) : Integer; var i : Integer; begin result := -1; for i := 0 to NbElements - 1 do if FElements[i] = aElem then begin result := i; exit; end; end; function TXMLElement.GetParent:TXMLElement; begin result := FParent; end; procedure TXMLElement.MoveTo(aNewParent : TXMLElement); var i : Integer; begin with Parent do for i := 0 to FElements.count - 1 do if FElements[i] = Self then begin FElements.Delete(i); Break; end; FParent := aNewParent; aNewParent.FElements.Add(Self); end; function TXMLElement.NextSibling : TXMLElement; var i : integer; begin result := nil; i := TXMLElement(Parent).Locate(Self); if (i>=0) and (i < Parent.NbElements-1) then result := Parent.FElements[i+1]; end; function TXMLElement.AddChildNode(const aName : String):TXMLElement; // aTokenType : TXMLReaderTokenType = rtOpenElement):TXMLElement; begin Felements.Add(TXMLElement.Create(FOwner, Self)); result := FElements[Felements.count-1]; with TXMLElement(result) do begin FTagName := aName; FTokenType := rtOpenElement; //aTokenType; end; DoOnAddChildNode(result); Owner.SetModified(Self); end; procedure TXMLElement.DeleteChildNode(aNode : TXMLElement); var i : Integer; begin for I := 0 to NbElements-1 do if FElements[i] = aNode then begin if Assigned(Owner.OnDeleteChildNode) then Owner.OnDeleteChildNode(aNode, FElements[i]); FElements.Delete(i); aNode.Free; Owner.SetModified(Self); exit; end; end; function TXMLElement.InsertNode(aNode : TXMLElement):TXMLElement; begin result := AddChildNode(aNode.TagName); result.Assign(aNode) end; function TXMLElement.SelectSingleNode(const aNodeName : String):TXMLElement; var i : integer; begin result := nil; for i := 0 to NbElements - 1 do if TXMlelement(FElements[i]).TagName = aNodeName then begin result := FElements[i]; exit; end; end; procedure TXMLElement.RemoveChild(aNode : TXMLElement); var i : integer; begin for i := 0 to FElements.Count - 1 do if FElements[i] = aNode then begin FElements.Delete(i); aNode.Free; exit; end; end; function TXMLElement.SelectNodes(const aName : String) : TList; var i : Integer; begin result := TList.Create; with result do for I := 0 to NbElements - 1 do if TXMlelement(FElements[i]).TagName = aName then Add(FElements[i]); end; procedure TXMLElement.SwapElements(aFirst, aSecond: Integer); var Node : TObject; begin Node := FElements[aFirst]; FElements[aFirst] := FElements[aSecond]; FElements[aSecond] := Node; Owner.SetModified(Self); end; function TXMLElement.GetAttribute(const AName: string): variant; var s : String; begin result := Null; if AName = '' then exit; result := FAttributes.Values[AName]; if result <> '' then begin s := FAttributes.Values[AName]; // check for dates if (Length(s) = 23) then begin if (s[5]='-') and (s[11]='T') then begin s := StringReplace(s, '-', '/', [rfReplaceAll]); s[11] := ' '; s := copy(s, 9, 2)+'/'+copy(s, 6, 2)+'/'+copy(s, 1, 4) + copy(s, 11, length(s));; try result := StrToDateTime(s); except result := 0; end; end else result := FAttributes.Values[AName]; end else result := FAttributes.Values[AName]; end; end; procedure TXMLElement.RemoveAttribute(index: integer); begin with FAttributes do if index < Count then Delete(index); end; procedure TXMLElement.RemoveAttribute(const AName: string); var i : Integer; begin with FAttributes do for i := 0 to Count - 1 do if Strings[i] = aName then begin Delete(i); Exit; end; end; function TXMLElement.GetAttributeStr(const AName: string): string; begin result := ''; result := FAttributes.Values[AName]; end; function TXMLElement.GetAttributeBool(const AName: string; vDefault : Boolean = False): boolean; var a: string; begin result := vDefault; a := FAttributes.Values[AName]; if a <> '' then result := (a = '1') or (a = 'true'); end; { procedure TXMLElement.GetAttributeHex(const AName: string; var aArr: TArray<Byte>); const Convert: array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); var I, j, o : Integer; aHex : string; begin aHex := GetAttribute(aNAme); I := Length(aHex); j := 1; o := 0; SetLength(aArr, length(aHex) div 2); while I > 0 do begin if (CharInSet(aHex[j], [':'..'@']) or CharInSet(aHex[j], ['G'..#96])) or (CharInSet(aHex[j+1], [':'..'@']) or CharInSet(aHex[j+1], ['G'..#96])) then Break; if not CharInSet(aHex[j], ['0'..'f']) or not CharInSet(aHex[j+1], ['0'..'f']) then Break; aArr[O] := byte((Convert[AnsiChar(aHex[j])] shl 4) + Convert[AnsiChar(aHex[j+1])]); Inc(O); Inc(j, 2); Dec(I, 2); end; end; procedure TXMLElement.SetAttributeHex(const AName: string; aArr : TArray<Byte>); const Convert: array[0..15] of WideChar = '0123456789ABCDEF'; var I: Integer; s : string; begin s := ''; for I := Low(aArr) to High(aArr) do begin s := s + Convert[Byte(aArr[I]) shr 4]; s := s + Convert[Byte(aArr[I]) and $F]; end; SetAttribute(AName, s); end; } function TXMLElement.GetAttributeInt(const AName: string): Int64; begin result := VarToIntDef(FAttributes.Values[AName], 0); end; procedure TXMLElement.SetAttributeBool(const AName: string; AValue: Boolean); begin if AValue then SetAttribute(AName, 'true') else SetAttribute(AName, 'false'); end; function TXMLElement.GetAttributeDate(const AName: string; AValue: TDateTime):TDateTime; begin if _IsDateTime(GetAttributeStr(aName)) then result := _XmlDateToDateTime(GetAttributeStr(aName)) else result := AValue; end; procedure TXMLElement.SetAttributeDate(const aName: String; const aValue: TDateTime); begin SetAttribute(aName, FormatDateTime('yyyy-mm-dd', aValue) + 'T' + FormatDateTime('hh":"nn":"ss.zzz', aValue)); end; function TXMLElement.GetNode(const aNodeName : String; bAutoCreate : Boolean = True):TXMLElement; begin result := selectSingleNode(aNodeName); if (result = nil) and (bAutoCreate) then result := AddChildNode(aNodeName); end; function TXMLElement.GetValueByElement(const aNodeName: string; var AValue: string): boolean; var n: TXMLElement; begin n := selectSingleNode(aNodeName); result := n <> nil; if result then AValue := n.text; end; function TXMLElement.GetValueByElement(const aNodeName: string): string; begin result := ''; GetValueByElement(aNodeName, result); end; function TXMLElement.GetElementByValue(const AElementName, AValue: string): TXMLElement; var i: integer; begin result := nil; for i := 0 to NbElements -1 do if TXMLElement(FElements[i]).Text = AValue then begin result := FElements[i]; break; end; if result = nil then begin result := AddChildNode(AElementName); result.text := AValue; end; end; function TXMLElement.GetNodeByElementValue(const aNodeName, AElementName, AValue: string; bAutoCreate : Boolean = True): TXMLElement; var i: integer; n: TXMLElement; begin result := nil; for i := 0 to NbElements -1 do begin n := FElements[i]; if SameText(n.GetValueByElement(AElementName), AValue) then begin result := n; break; end; end; if (result = nil) and bAutoCreate then begin result := AddChildNode(aNodeName); n := result.GetNode(AElementName); n.Text := AValue; end; end; function TXMLElement.GetNodeByAttributeValue(const aNodeName, AAttributeName, AValue: string; bAutoCreate : Boolean = True): TXMLElement; var i: integer; n: TXMLElement; begin result := nil; for i := 0 to NbElements -1 do begin n := FElements[i]; if SameText(n.GetAttribute(AAttributeName), AValue) then begin result := n; break; end; end; if (result = nil) and bAutoCreate then begin result := AddChildNode(aNodeName); result.SetAttribute(AAttributeName, AValue); end; end; function TXMLElement.Compare(AElement : TXMLElement): boolean; var i, j : integer; Match: Boolean; begin Result := True; Match := False; if (AElement = nil) OR (TagName <> AElement.TagName) OR (Attribs <> AElement.Attribs) OR (NbElements <> AElement.NbElements) then begin Result := False; exit; end; for i := 0 to NbElements - 1 do begin for j := 0 to AElement.NbElements - 1 do begin Match := False; if (TXMLElement(FElements[i]).TagName = TXMLElement(AElement.FElements[j]).TagName) AND (TXMLElement(FElements[i]).Attribs = TXMLElement(AElement.FElements[j]).Attribs) then begin Match := True; Result := TXMLElement(FElements[i]).Compare(AElement.FElements[j]); if not Result then exit else break; end; end; if not Match then begin Result := False; exit; end; end; end; procedure TXMLElement.SetAttribute(const AName: string; AValue: Variant); var s : string; begin if not VarIsNull(AValue) then if VarType(AValue) = VarDate then begin s := FormatDateTime('yyyy-mm-dd', TDateTime(AValue)) + 'T' + FormatDateTime('hh:nn:ss.zzz', TDateTime(AValue)); FAttributes.Values[aName] := s; end else FAttributes.Values[aName] := AValue; end; procedure TXMLElement.SetValueByElement(const aNodeName, aValue : String); var i : integer; begin for i := 0 to NbElements - 1 do if TXMLElement(FElements[i]).TagName = anodeName then begin TXMLElement(FElements[i]).Text := aValue; Exit; end; AddChildNode(aNodeName).Text := aValue; end; function TXMLElement.NodeByAttributeValue(const aNodeName, AAttributeName, AValue: string): TXMLElement; var i,j : integer; begin for i := 0 to NbElements - 1 do for j := 0 to TXMLElement(FElements[i]).Attributes.Count - 1 do if TXMLElement(FElements[i]).Attributes.Values[AAttributeName] = AValue then begin result := FElements[i]; exit; end; // not found : create result := AddChildNode(aNodeName); TXMLElement(result).Attributes.Values[aAttributeName] := aValue; end; procedure TXMLElement.Save(Writer : TXMLWriter; omitXMLDeclaration : Boolean = False); var i : integer; s : string; procedure TabIt; var ii : integer; begin for ii:=1 to Level-1 do Writer.RawText(#9); end; begin // tabs to nicely format the xml but not // for xml fragment if not omitXMLDeclaration then TabIt; // special case for the XML document declaration if ((Level = 0) and (TagName = 'xml')) and (not omitXMLDeclaration) then begin Writer.OpenXMLDeclaration; FAttributes.Values['encoding'] := Writer.Encoding.EncodingName; for i := 0 to NbAttributes-1 do Writer.Attribute(FAttributes.Names[i], FAttributes.ValueFromIndex[i]); Writer.FinishOpenXMLDeclaration; end // child elements else case FTokenType of rtCData : //cdata: <![CDATA[value]]> Writer.CData(Text); rtComment: //comment: <!--value--> Writer.Comment(Text); rtProcessingInstruction: //custom processing instruction: <?target content?> Writer.ProcessingInstruction(TagName, Text); rtDocType : //docty Writer.DocType(Text); rtOpenElement : begin Writer.OpenElement(TagName); if NbAttributes > 0 then for i := 0 to NbAttributes-1 do Writer.Attribute(FAttributes.Names[i], FAttributes.ValueFromIndex[i]); if (NbElements > 0) or (Text <> '') then Writer.FinishOpenElement(TagName) else Writer.FinishOpenElementClose(TagName); if Text <> '' then begin s := Text; //Writer.RawText(s); Writer.Text(s, false); // format XML only if not XML Fragment if not omitXMLDeclaration then Writer.RawText(#13#10); Writer.CloseElement(TagName, True); end; end; end; // format XML only if not XML Fragment if not omitXMLDeclaration then Writer.RawText(#13#10); // process chid elements for i := 0 to NbElements -1 do TXMLElement(FElements[i]).Save(Writer, omitXMLDeclaration); // close element except for top level XML declaration if (NbElements > 0) and (Level > 0)then begin // format XML only if not XML Fragment if not omitXMLDeclaration then TabIt; Writer.CloseElement(TagName, True); // format XML only if not XML Fragment if not omitXMLDeclaration then Writer.RawText(#13#10); end; end; procedure TXMLElement.StartLoad(Token: PXMLReaderToken; Reader : TXMLReader); begin FTagName := Token^.TokenName; Load(Token, Reader); end; procedure TXMLElement.Load(var Token: PXMLReaderToken; Reader : TXMLReader); begin repeat case Token^.TokenType of rtDocumentStart : ;//start of reading rtXMLDeclarationAttribute : FAttributes.Add(Token^.TokenName+'='+Token^.TokenValue) ;//attribute in an xml declaration: name="value" rtCData : //cdata: <![CDATA[value]]> Felements.Add(TXMLElement.Create(Self, XML_CDATA, Token^.TokenValue, Token^.TokenType, Reader.Line)); rtComment : //comment: <!--value--> Felements.Add(TXMLElement.Create(Self, XML_COMMENT, Token^.TokenValue, Token^.TokenType, Reader.Line)); rtProcessingInstruction : //custom processing instruction: <?target content?> Felements.Add(TXMLElement.Create(Self, Token^.TokenName, Token^.TokenValue, Token^.TokenType, Reader.Line)); rtDocType : //docty Felements.Add(TXMLElement.Create(Self, XML_DOCTYPE, Token^.TokenValue, Token^.TokenType, Reader.Line)); rtOpenElement : //open element: <name begin Felements.Add(TXMLElement.Create(FOwner, Self)); with TXMLElement(FElements[Felements.count-1]) do begin FTagName := Token^.TokenName; FTokenType := Token^.TokenType; Reader.ReadNextToken(Token); FLine := Reader.Line; Load(Token, Reader); end; end; rtAttribute : FAttributes.Add(Token^.TokenName+'='+Token^.TokenValue); //attribute: name="value" rtFinishOpenElement : ;//open element finished but not closed: <node ... ">" rtFinishOpenElementClose : exit; //open element finished and closed: <node ... "/>" rtFinishXMLDeclarationClose, rtCloseElement : if Token^.TokenName = FTagName then exit; //close element: "</node>" rtText : begin AddText(Token^.TokenValue); end; rtEntityReference : ;//&name; (value = the dereferenced entity value) end; until not Reader.ReadNextToken(Token); end; procedure TXMLElement.AddText(const txt : String); begin FText := StringReplace(txt, #13#13#10, #13#10, [rfReplaceAll]); end; procedure TXMLElement.SetTagName(const aName : String); begin if FTagName <> aName then begin FTagName := aName; Owner.SetModified(Self); end; end; function TXMLElement.GetIndex: Integer; var i : integer; begin result := -1; if Assigned(Parent) then for i:=0 to Parent.NbElements-1 do if Parent.Elements[i] = Self then begin result := i; break; end; end; function TXMLElement.GetElement(index : integer):TXMLElement; begin result := TXMLElement(FElements[index]); end; function TXMLElement.GetAttribute(index : integer):string; begin result := FAttributes[index]; end; function TXMLElement.GetAttributeValue(index : integer):string; begin result := GetAttribute(AttributeName[index]); end; function TXMLElement.GetShortAttributeValue(index : integer):string; function FormatNumber(aNum : integer):string; begin if aNum > 10240000 then result := IntToStr(aNum div 10240)+' mb' else if aNum > 102400 then result := IntToStr(aNum div 1024)+' kb' else result := IntToStr(aNum)+' b'; result := '(' + Result + ')'; end; begin result := GetAttributeValue(index); result := Copy(result, 1, 10) + '... ' + FormatNumber(Length(result)); end; function TXMLElement.GetAttributeName(index : integer):string; begin if index < FAttributes.Count then result := FAttributes.Names[index]; end; function TXMLElement.GetNbElements:integer; begin result := FElements.Count; end; function TXMLElement.GetNbAttributes:integer; begin result := FAttributes.Count; end; function TXMLElement.GetAttribList:String; var i : integer; begin result := ''; for i:=0 to FAttributes.Count-1 do result := result + FAttributes.ValueFromIndex[i] + ';'; Setlength(result, length(result)-1); end; function TXMLElement.GetAttribs:String; var i : integer; begin result := ''; if NbAttributes > 0 then begin for i:=0 to NbAttributes-1 do if Length(Attribute[i]) > 50 then result := result + AttributeName[i]+'='+ShortAttributeValue[i] + ' ' else result := result + Attribute[i] + ' '; Setlength(result, length(result)-1); end; end; function TXMLElement.GetLevel:Integer; begin result := 0; if assigned(self) and Assigned(Self.parent) then result := parent.level + 1; end; function TXMLElement.GetText:String; begin result := Trim(FText); end; procedure TXMLElement.SetText(const aText : String); begin DoBeforeNodeChange; if FText <> aText then begin FText := aText; Owner.SetModified(Self); end; DoAfterNodeChange; end; function TXMLElement.GetNodePath:String; var n : TXMLElement; begin result := ''; n := Self; repeat result := '/'+ n.TagName + result; n := TXMLElement(n.Parent); until n.level = 0; end; function TXMLElement.GetLine:Int64; begin result := FLine; end; procedure TXMLElement.SetLine(aLine : int64); begin FLine := aLine; end; function TXMLElement.GetElements:TList; begin result := FElements; end; { function TXMLElement.GetValue(aName : String):String; var i : integer; begin result := ''; if Name = aName then begin if Text <> '' then; result := Text; end else for i:=0 to NbElements-1 do begin result := TXMLElement(FElements[i]).GetValue(aName); if result <> '' then exit; end; end; } procedure TXMLElement.DoBeforeNodeChange; begin if Assigned(FOwner.BeforeNodeChange) then FOwner.BeforeNodeChange(Self); end; procedure TXMLElement.DoAfterNodeChange; begin if Assigned(FOwner.AfterNodeChange) then FOwner.AfterNodeChange(Self); end; procedure TXMLElement.DoOnAddChildNode(aChildNode : TXMLElement); begin if Assigned(FOwner.OnAddChildNode) then TXMLElement(Self).FOwner.OnAddChildNode(Self, aChildNode); end; function TXMLElement.GetElemValue:String; begin result := Trim(Text); end; procedure TXMLElement.SetElementValue(const aValue : String); begin Text := aValue; end; { procedure TXMLElement.SetValue(aName, Avalue : String); var i : integer; begin if Name = aName then Text := aValue else for i:=0 to NbElements-1 do TXMLElement(FElements[i]).SetValue(aName, aValue); end; } procedure TXMLElement.AddAttrib(const attr : String); begin FAttributes.Add(attr); end; // // TXMLDOC // constructor TXMLDoc.Create; begin inherited Create; FomitXMLDeclaration := False; FElement := TXMLElement.Create(Self, nil); FElement.FTagName := 'xml'; FElement.AddAttrib('version=1.0'); FModified := False; end; destructor TXMLDoc.Destroy; begin FElement.Free; inherited Destroy; end; procedure TXMLDoc.Clear; begin FElement.Clear; end; function TXMLDoc.CreateNewDocumentElement(const aName : String):TXMLElement; begin if FElement.NbElements > 0 then FElement.ClearChildren; Result := FElement.AddChildNode(aName) end; function TXMLDoc.GetDocumentElement:TXMLElement; begin result := nil; if FElement.NbElements = 0 then CreateNewDocumentElement('xml'); result := TXMLElement(FElement.FElements[0]); end; procedure TXMLDoc.MoveElement(aElement, aNewParent : TXMLElement); begin aElement.MoveTo(aNewParent); SetModified(Self); end; procedure TXMLDoc.LoadData(XMLReader : TXMLReader); var Token: PXMLReaderToken; begin Token:=nil; with XMLReader do begin ReadNextToken(Token); if not Assigned(Token) then raise Exception.Create('Token not found, invalid XML file !'); repeat case Token^.TokenType of rtOpenXMLDeclaration: FElement.StartLoad(Token, XMLReader); rtXMLDeclarationAttribute: FElement.AddAttrib(Token^.TokenName+'='+Token^.TokenValue); rtText : FElement.AddTExt(Token^.TokenValue); rtOpenElement: FElement.Load(Token, XMLReader); end; until not ReadNextToken(Token); end; end; procedure TXMLDoc.LoadFromFile(const afilename : String); var x : TXMLReader; begin FFilename := aFilename; x := GetReader; with x do try InitFile(FFilename); Clear; LoadData(x); FModified := False; finally Free; end; end; procedure TXMLDoc.loadXML(const aXMLStr : String); begin AsString := aXMLStr; FModified := False; end; procedure TXMLDoc.SaveToStream(aStream : TStream; {bWriteBom : Boolean = True; }aOmitXMLDeclaration : boolean = False); var x : TXMLWriter; begin x := GetWriter; //x.WriteBOM := bWriteBom; with x do try InitStream(aStream); DefaultIndentLevel := 4; if aOmitXMLDeclaration then TXMLElement(DocumentElement).Save(x, aOmitXMLDeclaration) else FElement.Save(x, aOmitXMLDeclaration); FModified := False; finally Free; end; end; procedure TXMLDoc.SaveToFile(const afilename : String); var x : TXMLWriter; begin x := GetWriter; with x do try InitFile(aFilename); DefaultIndentLevel := 4; if FomitXMLDeclaration then TXMLElement(DocumentElement).Save(x) else FElement.Save(x, FomitXMLDeclaration); FFilename := aFilename; FModified := False; finally Free; end; end; procedure TXMLDoc.LoadFromStream(aStream : TStream); var x : TXMLReader; begin x := GetReader; with x do try InitStream(aStream); Clear; LoadData(x); FModified := False; finally Free; end; end; function TXMLDoc.GetNodeFromPath(const aPath : String):TXMLElement; var List: TStrings; i : integer; begin result := DocumentElement; if aPath[1] <> '/' then raise Exception.Create('Invalid node path format !'); List := TStringList.Create; try ExtractStrings(['/'], [], PChar(aPath), List); // special case for 1st node if Result = nil then Result := CreateNewDocumentElement(List[0]); with List do if Count > 0 then for i := 1 to Count - 1 do Result := Result.GetNode(Strings[i]); finally List.Free; end; end; function TXMLDoc.GetAsString:String; var ss: TStringStream; begin Result := ''; ss := TStringStream.Create(''); with ss do try Self.SaveToStream(ss, {False,} True); position := 0; Result := SS.DataString; finally free; end; end; procedure TXMLDoc.SetAsString(const aString : String); var x : TXMLReader; begin x := GetReader; with x do try InitXML(aString); Clear; LoadData(x); FModified := True; finally Free; end; end; function TXMLDoc.GetElement:TXMLElement; begin result := Felement; end; function TXMLDoc.GetomitXMLDeclaration:Boolean; begin result := FomitXMLDeclaration; end; procedure TXMLDoc.SetomitXMLDeclaration(aVal : Boolean); begin FomitXMLDeclaration := aVal; end; function TXMLDoc.GetFilename:String; begin result := FFilename; end; procedure TXMLDoc.SetModified(Sender : TObject); begin FModified := True; end; function TXMLDoc.GetReader:TXMLReader; begin result := TXMLReader.Create; with result.ReaderSettings do begin ErrorHandling := ehRaise; StrictXML := True; end; end; function TXMLDoc.GetWriter:TXMLWriter; begin result := TXMLWriter.Create; with result do begin OwnsEncoding := False; //Encoding := TEncoding.Unicode; WriterSettings.WriteBOM := True; end; end; end.
program LamwinoDemo2; {by Lamwino: Lazarus Arduino Module Wizard} { Assumptions: - LED connected to PIN 13 [PortB bit 5] - Switch/PushButton connected to PIN 2 [PORTD bit 2] - ref. http://brittonkerin.com/cduino/xlinked_source_html/lesson3.c.html -My experiment assembly: https://od.lk/f/Ml8xMTIzODM1NDFf } var DelayVar: Integer = 0; //This function simulates some kind of delay by looping. [Thanks to @ykot!] procedure SomeDelay; var I: LongInt; begin for I := 0 to 400000 do Dec(DelayVar); end; const PB5 = 1 shl 5; //set Bit index 5 in "Port B" [Pin 13/LED] //00000001 shl 5 --> 00100000 PD2 = 1 shl 2; //set Bit index 2 in "Port D" [Pin 2] //00000001 shl 2 --> 00000100 var value: byte; begin //http://urbanhonking.com/ideasfordozens/2009/05/18/an_tour_of_the_arduino_interna/ //Bit 5 in "Set B" control Pin 13 [internal LED] //Turn ON the bit in DDRB corresponding to pin 13 [PorB bit 5] to configure it for "output" //Data Direction --> output [ => 1] //can be manipulated using PORTB DDRB:= DDRB or PB5; //force DDRB bit 5 to 1 !! [direction Pin13 is output] --> LED //Data Direction --> input [=> 0] DDRD:= DDRD and (not PD2); //(not PD2 = 11111011) force DDRD bit 2 to 0 !! [direction Pin2 is "input"] //The pins marked as input now has the capability to read the voltage level at that pin... //http://www.avr-tutorials.com/digital/about-avr-8-bit-microcontrollers-digital-io-ports //DDRx is an 8-bit register which stores configuration information for the pins of Portx. //Writing a 1 in the pin location in the DDRx makes the physical pin of that port //an output pin and writing a 0 makes that pin an input pin //PIND is an 8-bit register that stores the logic value, the current state, //of the physical pins on PortD. //So to read the values on the pins of PortD, //you read the values that are in its PIN register. while True do begin //NOTE: In input mode, when pull-up is enabled, default state of pin becomes = 1. //So even if you don’t connect anything to pin and if you try to read it, it will read as 1. //Now, when you externally drive that pin to zero //(i.e. connect to ground / or pull-down),only then it will be read as 0. //ref. http://www.elecrom.com/2008/02/12/avr-tutorial-2-avr-input-output/ value:= PIND and PD2; //HOWTO read a pin ... [yyyyyByy and 00000100]: value <> 0 <----> B = 1 [on] // value = 0 <----> B = 0 [off] if value <> 0 then PORTB:= PORTB or PB5 {set [internal] LED to ON } else PORTB:= PORTB and (not PB5); {set [internal] led OFF} //not PB5 --> 11011111 SomeDelay; end; end.
// ************************************************************************ // // Les types déclarés dans ce fichier ont été générés à partir de données lues // depuis le fichier WSDL décrit ci-dessous : // WSDL : D:\Documents\Embarcadero\Studio\Projets\rennes - paris\17-web-soap\Idemos.xml // >Importer : D:\Documents\Embarcadero\Studio\Projets\rennes - paris\17-web-soap\Idemos.xml>0 // Version : 1.0 // (23/03/2018 10:08:09 - - $Rev: 90173 $) // ************************************************************************ // unit Idemos1; interface uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns; type // ************************************************************************ // // Les types suivants mentionnés dans le document WSDL ne sont pas représentés // dans ce fichier. Ce sont des alias[@] d'autres types représentés ou alors ils étaient référencés // mais jamais[!] déclarés dans le document. Les types de la dernière catégorie // sont en principe mappés sur des types Embarcadero ou XML prédéfinis/connus. Toutefois, ils peuvent aussi // signaler des documents WSDL incorrects n'ayant pas réussi à déclarer ou importer un type de schéma. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:double - "http://www.w3.org/2001/XMLSchema"[Gbl] TMyEmployee = class; { "urn:udemosIntf"[GblCplx] } {$SCOPEDENUMS ON} { "urn:udemosIntf"[GblSmpl] } TEnumTest = (etNone, etAFew, etSome, etAlot); {$SCOPEDENUMS OFF} TDoubleArray = array of Double; { "urn:udemosIntf"[GblCplx] } // ************************************************************************ // // XML : TMyEmployee, global, <complexType> // Espace de nommage : urn:udemosIntf // ************************************************************************ // TMyEmployee = class(TRemotable) private FLastName: string; FFirstName: string; FSalary: Double; published property LastName: string read FLastName write FLastName; property FirstName: string read FFirstName write FFirstName; property Salary: Double read FSalary write FSalary; end; // ************************************************************************ // // Espace de nommage : urn:udemosIntf-Idemos // soapAction : urn:udemosIntf-Idemos#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // utiliser : encoded // Liaison : Idemosbinding // service : Idemosservice // port : IdemosPort // URL : http://localhost:8080/soap/Idemos // ************************************************************************ // Idemos = interface(IInvokable) ['{969D57A0-EF51-3F60-38CB-E9A441755A18}'] function echoEnum(const Value: TEnumTest): TEnumTest; stdcall; function echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall; function echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall; function echoDouble(const Value: Double): Double; stdcall; end; function GetIdemos(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): Idemos; implementation uses System.SysUtils; function GetIdemos(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): Idemos; const defWSDL = 'D:\Documents\Embarcadero\Studio\Projets\rennes - paris\17-web-soap\Idemos.xml'; defURL = 'http://localhost:8080/soap/Idemos'; defSvc = 'Idemosservice'; defPrt = 'IdemosPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as Idemos); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization { Idemos } InvRegistry.RegisterInterface(TypeInfo(Idemos), 'urn:udemosIntf-Idemos', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(Idemos), 'urn:udemosIntf-Idemos#%operationName%'); RemClassRegistry.RegisterXSInfo(TypeInfo(TEnumTest), 'urn:udemosIntf', 'TEnumTest'); RemClassRegistry.RegisterXSInfo(TypeInfo(TDoubleArray), 'urn:udemosIntf', 'TDoubleArray'); RemClassRegistry.RegisterXSClass(TMyEmployee, 'urn:udemosIntf', 'TMyEmployee'); end.
unit NewNotebook; { Inno Setup Copyright (C) 1997-2008 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. TNewNotebook component $jrsoftware: issrc/Components/NewNotebook.pas,v 1.4 2008/10/08 23:23:02 jr Exp $ } {$IFDEF VER90} {$DEFINE DELPHI2} {$ENDIF} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms; type TNewNotebookPage = class; TNewNotebook = class(TWinControl) private FActivePage: TNewNotebookPage; FPages: TList; function GetPage(Index: Integer): TNewNotebookPage; function GetPageCount: Integer; procedure InsertPage(Page: TNewNotebookPage); procedure RemovePage(Page: TNewNotebookPage); procedure SetActivePage(Page: TNewNotebookPage); protected procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure CreateParams(var Params: TCreateParams); override; procedure ShowControl(AControl: TControl); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function FindNextPage(CurPage: TNewNotebookPage; GoForward: Boolean): TNewNotebookPage; procedure GetChildren(Proc: TGetChildProc {$IFNDEF DELPHI2} ; Root: TComponent {$ENDIF}); override; property PageCount: Integer read GetPageCount; property Pages[Index: Integer]: TNewNotebookPage read GetPage; published property ActivePage: TNewNotebookPage read FActivePage write SetActivePage; property Align; property Color; property DragCursor; property DragMode; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; TNewNotebookPage = class(TCustomControl) private FNotebook: TNewNotebook; function GetPageIndex: Integer; procedure SetNotebook(ANotebook: TNewNotebook); procedure SetPageIndex(Value: Integer); protected procedure Paint; override; procedure ReadState(Reader: TReader); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Notebook: TNewNotebook read FNotebook write SetNotebook; published property Color nodefault; { nodefault needed for Color=clWindow to persist } property DragMode; property Enabled; property Font; property Height stored False; property Left stored False; property PageIndex: Integer read GetPageIndex write SetPageIndex stored False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Top stored False; property Visible stored False; property Width stored False; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; implementation { TNewNotebookPage } constructor TNewNotebookPage.Create(AOwner: TComponent); begin inherited; Align := alClient; ControlStyle := ControlStyle + [csAcceptsControls, csNoDesignVisible]; Visible := False; end; destructor TNewNotebookPage.Destroy; begin if Assigned(FNotebook) then FNotebook.RemovePage(Self); inherited; end; function TNewNotebookPage.GetPageIndex: Integer; begin if Assigned(FNotebook) then Result := FNotebook.FPages.IndexOf(Self) else Result := -1; end; procedure TNewNotebookPage.Paint; begin inherited; if csDesigning in ComponentState then begin Canvas.Pen.Style := psDash; Canvas.Brush.Style := bsClear; Canvas.Rectangle(0, 0, Width, Height); end; end; procedure TNewNotebookPage.ReadState(Reader: TReader); begin inherited; if Reader.Parent is TNewNotebook then Notebook := TNewNotebook(Reader.Parent); end; procedure TNewNotebookPage.SetNotebook(ANotebook: TNewNotebook); begin if FNotebook <> ANotebook then begin if Assigned(FNotebook) then FNotebook.RemovePage(Self); Parent := ANotebook; if Assigned(ANotebook) then ANotebook.InsertPage(Self); end; end; procedure TNewNotebookPage.SetPageIndex(Value: Integer); begin if Assigned(FNotebook) then begin if Value >= FNotebook.FPages.Count then Value := FNotebook.FPages.Count-1; if Value < 0 then Value := 0; FNotebook.FPages.Move(PageIndex, Value); end; end; { TNewNotebook } constructor TNewNotebook.Create(AOwner: TComponent); begin inherited; Width := 150; Height := 150; FPages := TList.Create; end; destructor TNewNotebook.Destroy; var I: Integer; begin if Assigned(FPages) then begin for I := 0 to FPages.Count-1 do TNewNotebookPage(FPages[I]).FNotebook := nil; FPages.Free; end; inherited; end; procedure TNewNotebook.AlignControls(AControl: TControl; var Rect: TRect); var I: Integer; Ctl: TControl; begin inherited; { The default AlignControls implementation in Delphi 2 and 3 doesn't set the size of invisible controls. Pages that aren't currently visible must have valid sizes for BidiUtils' FlipControls to work properly. Note: We loop through Controls and not FPages here because TNewNotebookPage.SetNotebook sets Parent (causing AlignControls to be called) before it calls InsertPage. } if not IsRectEmpty(Rect) then begin for I := 0 to ControlCount-1 do begin Ctl := Controls[I]; if (Ctl is TNewNotebookPage) and not Ctl.Visible then Ctl.BoundsRect := Rect; end; end; end; procedure TNewNotebook.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := Params.Style or WS_CLIPCHILDREN; end; function TNewNotebook.FindNextPage(CurPage: TNewNotebookPage; GoForward: Boolean): TNewNotebookPage; var I, StartIndex: Integer; begin if FPages.Count > 0 then begin StartIndex := FPages.IndexOf(CurPage); if StartIndex = -1 then begin if GoForward then StartIndex := FPages.Count-1 else StartIndex := 0; end; I := StartIndex; repeat if GoForward then begin Inc(I); if I = FPages.Count then I := 0; end else begin if I = 0 then I := FPages.Count; Dec(I); end; Result := FPages[I]; Exit; until I = StartIndex; end; Result := nil; end; procedure TNewNotebook.GetChildren(Proc: TGetChildProc {$IFNDEF DELPHI2} ; Root: TComponent {$ENDIF}); var I: Integer; begin for I := 0 to FPages.Count-1 do Proc(TNewNotebookPage(FPages[I])); end; function TNewNotebook.GetPage(Index: Integer): TNewNotebookPage; begin Result := FPages[Index]; end; function TNewNotebook.GetPageCount: Integer; begin Result := FPages.Count; end; procedure TNewNotebook.InsertPage(Page: TNewNotebookPage); begin FPages.Add(Page); Page.FNotebook := Self; end; procedure TNewNotebook.RemovePage(Page: TNewNotebookPage); begin Page.FNotebook := nil; FPages.Remove(Page); if FActivePage = Page then SetActivePage(nil); end; procedure TNewNotebook.ShowControl(AControl: TControl); begin if (AControl is TNewNotebookPage) and (TNewNotebookPage(AControl).FNotebook = Self) then SetActivePage(TNewNotebookPage(AControl)); inherited; end; procedure TNewNotebook.SetActivePage(Page: TNewNotebookPage); var ParentForm: {$IFDEF DELPHI2} TForm {$ELSE} TCustomForm {$ENDIF}; begin if Assigned(Page) and (Page.FNotebook <> Self) then Exit; if FActivePage <> Page then begin ParentForm := GetParentForm(Self); if Assigned(ParentForm) and Assigned(FActivePage) and FActivePage.ContainsControl(ParentForm.ActiveControl) then ParentForm.ActiveControl := FActivePage; if Assigned(Page) then begin Page.BringToFront; Page.Visible := True; if Assigned(ParentForm) and Assigned(FActivePage) and (ParentForm.ActiveControl = FActivePage) then begin if Page.CanFocus then ParentForm.ActiveControl := Page else ParentForm.ActiveControl := Self; end; end; if Assigned(FActivePage) then FActivePage.Visible := False; FActivePage := Page; if Assigned(ParentForm) and Assigned(FActivePage) and (ParentForm.ActiveControl = FActivePage) then FActivePage.SelectFirst; end; end; end.
unit uAsync; {$mode objfpc} {$H+} { Thread based Async TCP Socket Ultibo (C) 2015 - SoftOz Pty Ltd. LGPLv2.1 with static linking exception FPC (c) 1993-2015 Free Pascal Team. Modified Library GNU Public License Lazarus (c) 1993-2015 Lazarus and Free Pascal Team. Modified Library GNU Public License Other bits (c) 2016 pjde LGPLv2.1 with static linking exception } interface uses Classes, SysUtils, Winsock2, SyncObjs; const stInit = 0; stClosed = 1; stConnecting = 2; stConnected = 3; stClosing = 4; stError = 5; stQuitting = 6; type { TAsyncSocket } TAsyncEvent = procedure (Sender : TObject); TReadEvent = procedure (Sender : TObject; Buff : pointer; BuffSize : integer); TMsgEvent = procedure (Sender : TObject; s : string); TAsyncSocket = class (TThread) private FOnConnect: TAsyncEvent; FOnClose: TAsyncEvent; FOnMsg: TMsgEvent; FOnRead: TReadEvent; FPort: Word; FAddr : string; FState : integer; FEvent : TEvent; protected procedure Execute; override; procedure SetState (NewState : integer); procedure DoMsg (s : string); public Socket : TWinsock2TCPClient; constructor Create (Msgs : TMsgEvent); destructor Destroy; override; procedure Connect; procedure Disconnect; procedure Send (Buff : pointer; BuffSize : integer); overload; procedure Send (s : string); overload; function State : integer; property Addr : string read FAddr write FAddr; property Port : Word read FPort write FPort; property OnConnect : TAsyncEvent read FOnConnect write FOnConnect; property OnClose : TAsyncEvent read FOnClose write FOnClose; property OnRead : TReadEvent read FOnRead write FOnRead; property OnMsg : TMsgEvent read FOnMsg write FOnMsg; end; function StateToStr (s : integer) : string; implementation function StateToStr (s : integer) : string; begin case s of stInit : Result := 'Init'; stClosed : Result := 'Closed'; stConnecting : Result := 'Connecting'; stConnected : Result := 'Connected'; stClosing : Result := 'Closing'; stError : Result := 'Error'; stQuitting : Result := 'Quitting'; else Result := 'Unknown ' + IntToStr (s); end; end; { TAsyncSocket } procedure TAsyncSocket.Execute; //const // ft : array [boolean] of string = ('FALSE', 'TRUE'); var Buff : array [0..255] of byte; closed : boolean; count : integer; res : boolean; begin while not Terminated do begin if Socket = nil then Terminate; case FState of stClosed : begin FEvent.ResetEvent; FEvent.WaitFor (INFINITE); // park thread end; stConnecting : begin Socket.RemotePort := FPort; Socket.RemoteAddress := FAddr; if Socket.Connect then SetState (stConnected) else SetState (stClosed); end; stConnected : begin count := 0; closed := false; res := Socket.ReadAvailable (@Buff[0], 256, count, closed); // DoMsg ('Read Result ' + ft[res]); if res then begin if Assigned (FOnRead) then FOnRead (Self, @Buff[0], count); end; if not res or closed then SetState (stClosed); end; stQuitting : Terminate; end; // case end; end; procedure TAsyncSocket.SetState (NewState: integer); begin if (FState <> NewState) then begin DoMsg (StateToStr (FState) + ' to ' + StateToStr (NewState) + '.'); case NewState of stClosed : if Assigned (FOnClose) then FOnClose (Self); stConnected : if Assigned (FOnConnect) then FOnConnect (Self); end; end; FState := NewState; if not (FState in [stClosed]) then FEvent.SetEvent; end; procedure TAsyncSocket.DoMsg (s: string); begin if Assigned (FOnMsg) then FOnMsg (Self, s); end; constructor TAsyncSocket.Create (Msgs : TMsgEvent); begin inherited Create (false); FreeOnTerminate := true; FonMsg := Msgs; Socket := TWinsock2TCPClient.Create; FEvent := TEvent.Create (nil, true, false, ''); FState := stInit; Start; end; destructor TAsyncSocket.Destroy; begin FEvent.SetEvent; FEvent.Free; Socket.Free; Socket := nil; inherited Destroy; end; procedure TAsyncSocket.Connect; begin if FState in [stClosed, stInit] then SetState (stConnecting); end; procedure TAsyncSocket.Disconnect; begin if FState in [stConnected, stConnecting] then Socket.Disconnect; end; procedure TAsyncSocket.Send (Buff: pointer; BuffSize: integer); begin if FState in [stConnected] then if not Socket.WriteData (Buff, BuffSize) then Socket.Disconnect; end; procedure TAsyncSocket.Send (s: string); begin if FState in [stConnected] then if not Socket.WriteData (@s[1], length (s)) then Socket.Disconnect; end; function TAsyncSocket.State: integer; begin Result := FState; end; end.
unit ObjFactory; interface uses SysUtils, Classes; type EFactoryException = class(Exception); TBaseObject = class(TObject) public constructor Create; virtual; abstract; end; TBaseClass = class of TBaseObject; TObjectFactory = class(TObject) private FItems: TStringList; protected public constructor Create; destructor Destroy; override; function GetClass(const AName: string): TBaseClass; function CreateInstance(const aName: string): TBaseObject; procedure RegisterClass(const AName: string; const AClass: TBaseClass); end; function ObjectFactory: TObjectFactory; implementation var FactoryImpl: TObjectFactory = nil; { ObjectFactory } function ObjectFactory: TObjectFactory; begin if FactoryImpl = nil then FactoryImpl := TObjectFactory.Create; Result := FactoryImpl; end; { TObjectFactory } constructor TObjectFactory.Create; begin inherited Create; FItems := TStringList.Create; end; function TObjectFactory.CreateInstance(const aName: string): TBaseObject; begin Result := Self.GetClass(aName).Create; end; destructor TObjectFactory.Destroy; begin FItems.Free; inherited; end; function TObjectFactory.GetClass(const AName: string): TBaseClass; var I: Integer; begin I := FItems.IndexOf(UpperCase(AName)); if I = -1 then raise EFactoryException.CreateFmt('No class: %s exists', [AName]) else Result := TBaseClass(FItems.Objects[I]); end; procedure TObjectFactory.RegisterClass(const AName: string; const AClass: TBaseClass); var ItemName: string; I: Integer; begin ItemName := UpperCase(AName); I := FItems.IndexOf(ItemName); if I = -1 then FItems.AddObject(ItemName, TObject(AClass)) else raise EFactoryException.CreateFmt('Class: %s has already been registered', [AName]); end; initialization finalization FactoryImpl.Free; end.
unit MP3Reader; interface uses Windows, mmSystem, DShow, // Download this (DXMedia) and all DX headers (required) from http://delphi-jedi.org/delphigraphics/jedi-index.htm FIFO; // http://homepages.borland.com/efg2lab/Library/Delphi/Graphics/Resources.htm type TMP3Reader = class public constructor Create(const aFileName : string; Loop : boolean ); destructor Destroy; override; private fStream : IAMMultiMediaStream; fAudioStream : IAudioMediaStream; fAudioData : IAudioData; fFormat : TWaveFormatEx; fBuffer : pointer; fSample : IAudioStreamSample; fLoop : boolean; fFIFO : TFIFO; private function FeedData : boolean; public property Format : TWaveFormatEx read fFormat; public function Read(out Data; Size : integer) : integer; end; implementation uses ComObj; constructor TMP3Reader.Create(const aFileName : string; Loop : boolean); var Audio : IMediaStream; BufSize : dword; fname : widestring; DestSize : integer; begin inherited Create; fLoop := Loop; fFIFO := TFIFO.Create; fStream := CoAMMultiMediaStream.Create as IAMMultiMediaStream; OleCheck(fStream.Initialize(STREAMTYPE_READ, AMMSF_NOGRAPHTHREAD, nil)); OleCheck(fStream.AddMediaStream(nil, MSPID_PrimaryAudio, 0, Audio)); fname := aFileName; OleCheck(fStream.OpenFile(PWideChar(fname), AMMSF_RUN)); //OleCheck(fStream.GetMediaStream(MSPID_PrimaryAudio, Audio)); fAudioStream := Audio as IAudioMediaStream; OleCheck(fAudioStream.GetFormat(fFormat)); BufSize := fFormat.nAvgBytesPerSec div 4; // 1/4th of second getmem(fBuffer, BufSize); fAudioData := CreateCOMObject(CLSID_AMAudioData) as IAudioData; OleCheck(fAudioData.SetBuffer(BufSize, fBuffer, 0)); OleCheck(fAudioData.SetFormat(fFormat)); OleCheck(fAudioStream.CreateSample(fAudioData, 0, fSample)); end; destructor TMP3Reader.Destroy; begin fSample := nil; fAudioData := nil; fAudioStream := nil; fStream := nil; freemem(fBuffer); fFIFO.Free; inherited; end; function TMP3Reader.FeedData : boolean; const MS_S_ENDOFSTREAM = $40003; // DShow header bug !!! var Res : hResult; Len : dword; dNul : dword; pNul : pointer; begin Res := fSample.Update(0, 0, nil, 0); if (Res = MS_S_ENDOFSTREAM) and fLoop then begin fStream.Seek(0); Res := fSample.Update(0, 0, nil, 0); end; Result := Succeeded(Res) and (Res <> MS_S_ENDOFSTREAM); if Result then begin fAudioData.GetInfo(dNul, pNul, Len); fFIFO.Write(fBuffer^, Len); end; end; function TMP3Reader.Read(out Data; Size : integer) : integer; begin while (fFIFO.Size < Size) and FeedData do; Result := fFIFO.Read(Data, Size); end; end.
unit Unit1; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Buttons, Dialogs; type TForm1 = class(TForm) CboURL: TComboBox; Label1: TLabel; BtnUpload: TBitBtn; OpenDialog1: TOpenDialog; EdtUser: TEdit; EdtPW: TEdit; Label2: TLabel; Label3: TLabel; ChkOverwrite: TCheckBox; ChkVerify: TCheckBox; CboMethod: TComboBox; Label4: TLabel; procedure BtnUploadClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private-Deklarationen } procedure AddToURLHist(const url:string); public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.DFM} uses MSXML2_TLB, JclStrings, ComObj, VariantUtils2; { Hinweis zum Import der Unit MSXML2_TLB 1.) Datei -> alle schliesen 2.) Projekt -> Typbibliothek importieren... bei höheren Delphi Versionen geht das über Komponente -> Komponente importieren 3.) Auswählen: Microsoft XML (Version 4) 4.) Unit anlegen klicken } procedure UploadFile(const BasisURL,user,pw, filename:string; overwrite, verify:Boolean; const Method:string); var req : IXMLHTTPRequest; URL : string; data, data2 : string; dataout : Variant; begin // req := CoXMLHTTP.Create; // Interface erzeugen try req := Createoleobject('Msxml2.XMLHTTP.4.0') as IXMLHTTPRequest; except on E:Exception do begin E.Message := 'MSXML 4.0 or higher requiered!'#13#10+E.Message; raise; end; end; URL := BasisURL; StrReplace(URL, '$$FILENAME$$', ExtractFileName(filename), []); if not overwrite then begin req.open('HEAD', URL, False, user, pw); req.send(EmptyParam); if req.status = 200 then raise Exception.CreateFmt('%s already on webserver',[URL]); end; req.open(Method, URL, False, user, pw); // eigenen Request-Header setzen // req.setRequestHeader('ApplicationID', 'PSS'); // req.setRequestHeader('Content-Transfer-Encoding', 'binary'); data := FileToString(filename); req.setRequestHeader('Content-Type', 'application/octet-stream'); req.setRequestHeader('Content-Length', IntToStr(Length(data))); dataout := VarByteArrayCreate2(data); req.send(dataout); // Anfrage an Server senden und Antwort abwarten // Status auswerten if not (req.status in [200, 201, 204]) then raise Exception.CreateFmt('HTTP-Upload <%s> failed.'#13#10'%d - %s', [URL, req.status, req.statusText] ); if verify then begin req.open('GET', URL, False, user, pw); req.send(EmptyParam); if req.status <> 200 then raise Exception.CreateFmt('%s not found on webserver - %s',[URL, req.statusText]); data2 := VarByteArrayToString(req.responseBody); if data2 <> data then raise Exception.CreateFmt('%s verify failed (org:%d byte server:%d byte)'#13#10'%s', [URL, Length(data), Length(data2), req.getAllResponseHeaders]); end; end; procedure TForm1.AddToURLHist(const url: string); begin if CboURL.Items.IndexOf(url) = -1 then CboURL.Items.Add(url); end; procedure TForm1.BtnUploadClick(Sender: TObject); var i : Integer; basisURL : string; begin basisURL := CboURL.Text; if basisURL = '' then raise Exception.Create('URL is missing'); if basisURL[Length(basisURL)] <> '/' then basisURL := basisURL + '/'; if OpenDialog1.Execute then begin for i := 0 to OpenDialog1.Files.Count-1 do begin UploadFile(basisURL, EdtUser.Text , EdtPW.Text, OpenDialog1.Files[i], ChkOverwrite.Checked, ChkVerify.Checked, Cbomethod.Text); end; AddToURLHist(CboURL.Text); end; end; procedure TForm1.FormCreate(Sender: TObject); begin CboMethod.ItemIndex := 0; end; end.
unit MultiLog; {$REGION 'Xls: Comments section'} {§< @HTML( <b>Main unit of the Multilog logging system.</b> <br> <span style="color: #4169E1;">author of MultiLog: Luiz Américo Pereira Câmara; pascalive@bol.com.br</span> <br><br> <div style="border: solid windowtext .5pt; padding: 1.0pt 4.0pt 1.0pt 4.0pt;"> nb1: all units are encoded with UTF-8 without BOM, using EDI "file settings\encoding\UTF-8" contextual menu. <br> nb2: this HTML documentation has been made with PasDoc - program named "pasdoc_gui". The comment marker is the character "§", to include only comments that start with this merker, a documentation tool for the Object Pascal code: <a href="https://github.com/pasdoc/pasdoc/wiki">https://github.com/pasdoc/pasdoc/wiki</a> . The pasdoc_gui's configuration file, for those who want to update the documentation, is named "config.pds". </div>) } {$ENDREGION} { Main unit of the Multilog logging system Copyright (C) 2006 Luiz Américo Pereira Câmara pascalive@bol.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } {$ifdef fpc} {$mode objfpc}{$H+} {$endif} interface uses {$ifndef fpc}Types, fpccompat,{$endif} Classes, SysUtils, syncobjs, math; {$REGION 'Xls: Comments section'} {§ MessageTypes @br Below is the list of the Logger ***meth***od's list to log: } {$ENDREGION} const methInfo = 0; methError = 1; methWarning = 2; methValue = 3; methEnterMethod = 4; methExitMethod = 5; methConditional = 6; methCheckpoint = 7; methTStrings = 8; methCallStack = 9; methObject = 10; methException = 11; methBitmap = 12; methHeapInfo = 13; methMemory = 14; methCustomData = 15; { hole } methWatch = 20; methCounter = 21; methColor = 22; {§ We can use ltSubEventBetweenEnterAndExitMethods, to indent the Msg depending of it's level in the callstack, between EnterMethod..ExitMethod } methSubEventBetweenEnterAndExitMethods = 23; { hole } methClear = 100; {$REGION 'Xls: Comments section'} {§ LogClasses of stats, convention with lc prefix. @br It's possible to define the constants to suit any need distribution of statictics classes of WHAT msg are logged. Here's the lwThings ie *l*ogger*w*hichTrackingPurposes logged list: } {$ENDREGION} type TLogger = class; TMethodToLog = methInfo..methClear; TForWhichTrackingPurpose = (lwDebug=0, lwError, lwInfo, lwWarning, lwEvents, lw_5, lw_6, lw_7, lwStudyChainedEvents, lw_10,lw_11,lw_12,lw_13,lw_14,lw_15,lw_16,lw_17,lw_18,lw_19,lw_20,lw_21,lw_22,lw_23,lw_24,lw_25,lw_26,lw_27,lw_28,lw_29,lw_30, lwLast); TGroupOfForWhichTrackingPurposesMsgAreLogged = Set of TForWhichTrackingPurpose; const lwAll = [lwDebug, lwError, lwInfo, lwWarning, lwEvents, lw_5, lw_6, lw_7, lwStudyChainedEvents, lw_10,lw_11,lw_12,lw_13,lw_14,lw_15,lw_16,lw_17,lw_18,lw_19,lw_20,lw_21,lw_22,lw_23,lw_24,lw_25,lw_26,lw_27,lw_28,lw_29,lw_30, lwLast]; lwNone = []; type TLogMessage = record iMethUsed: Integer; setGroupOfForWhichTrackingPurposesMsgAreLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; dtMsgTime: TDateTime; sMsgText: String; pData: TStream; end; TCustomDataNotify = function (Sender: TLogger; Data: Pointer; var DoSend: Boolean): String of Object; TCustomDataNotifyStatic = function (Sender: TLogger; Data: Pointer; var DoSend: Boolean): String; { TLogChannel } TLogChannel = class private FbActive: Boolean; public procedure Clear; virtual; abstract; procedure Deliver(const AMsg: TLogMessage); virtual; abstract; procedure Init; virtual; property Active: Boolean read FbActive write FbActive; end; { TChannelList } TChannelList = class private FoList: TFpList; function GetCount: Integer; {$ifdef fpc}inline;{$endif} function GetItems(AIndex: Integer): TLogChannel; {$ifdef fpc}inline;{$endif} public constructor Create; destructor Destroy; override; function Add(AChannel: TLogChannel):Integer; procedure Remove(AChannel:TLogChannel); property Count: Integer read GetCount; property Items[AIndex:Integer]: TLogChannel read GetItems; default; end; { TLogger } {$REGION 'Xls: Comments section'} {§ Brief summmary of the processing of a TLogger's mathod call: @br @html(<pre> <u>step ❶:</u> | | Calling program sends events; There's a distibution of groups of each event can have its methods too, each group specialized in *Why*ThisLogging's justification. *How* to forward an event type towards its So, there's a distribution of groups of channel's target event's justifications .../... (lwEvents)→ (lwEvents)(methEnterMethod)→ .../... .../... (lwEvents)→ (lwEvents)(methExitMethod)→ (lwNone)→ (lwNone)(ltInfo)→ (lwNone)→ (lwNone)(ltInfo)→ (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ .../... .../... (lwNone)→ (lwNone)(methValue\@integer)→ (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ (lwNone)→ (lwNone)(methValue\@boolean)→ .../... <u>step ❷:</u> | | There's a distibution of groups of ActiveClasses acts like a wall: if the *How* to forward isn't present method, each group specialized in in the ActiveClasses's "set Of *How*" type, then, the event doesn't go further. *How* to forward an event type towards its channel's target. Let say that TargetedConstantGroup1_OfWhatCanBeLogged = [lwNone, methValue]: .../... ↺||| (lwEvents)(methEnterMethod)→ (lwEvents)(methEnterMethod)→ .../... ↺||| (lwEvents)(methExitMethod)→ (lwEvents)(methExitMethod)→ .../... ↺||| (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ ↺||| .../... ↺||| (lwNone)(methValue\@integer)→ (lwNone)(methValue\@integer)→ (lwStudyChainedEvents)(methSubEventBetweenEnterAndExitMethods)→ ↺||| (lwNone)(methValue\@boolean)→ (lwNone)(methValue\@boolean)→ (lwWarning)(methWarning)→ ↺||| .../... ↺||| <u>step ❸:</u>> | | ActiveClasses acts like a wall: if the *How* to forward isn't present For each specialized Channel leading in the ActiveClasses's "Set Of *How*" type, then, the event doesn't go further. to a display medium (TMemo □, TFileText ○,TLogTreeView ▶) Let say that ActiveClasses = [methEnterMethod, methExitMethod, methValue]: will receive the msg and display it. | (lwEvents)(methEnterMethod)→ ○ + □ | (lwEvents)(methExitMethod)→ □ | | .../... | (lwNone)(methValue\@integer)→ ○ | (lwNone)(methValue\@boolean)→ ○ + ▶ .../... </pre>) } {$ENDREGION} TLogger = class private FiMaxStackCount: Integer; FoChannels: TChannelList; FoLogStack: TStrings; FoCheckList: TStringList; FoCounterList: TStringList; FOnCustomData: TCustomDataNotify; FsetLast_TargetedConstantGroup1_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; // for remind FsetForWhichTrackingPurposesMsgAreLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; class var FoDefaultChannels: TChannelList; procedure GetCallStack(AStream:TStream); procedure SetEnabled(AValue: Boolean); class function GetDefaultChannels: TChannelList; static; function GetEnabled: Boolean; procedure Store_FsetForWhichTrackingPurposesMsgAreLogged(const setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged); procedure SetMaxStackCount(const AValue: Integer); procedure SetThreadSafe; protected procedure SendStream(AMethodUsed: Integer; const AText: String; o_AStream: TStream); procedure SendBuffer(AMethodUsed: Integer; const AText: String; var pBuffer; Count: LongWord); public {§ public field to allow use of include/exclude functions = [lwDebug, ...] =~ active which can be adjusted contextually in the calling program...} TargetedConstantGroup1_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; {§ public field to allow use of include/exclude functions = [lwDebug, ...] =~ ..."pass-filter"'s set, blocking or not the logging.} IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; constructor Create; destructor Destroy; override; function CalledBy(const AMethodName: String): Boolean; procedure Clear; //Helper functions function RectToStr(const ARect: TRect): String; //inline function PointToStr(const APoint: TPoint): String; //inline //Send functions procedure Send(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log for a purpose of lwInfo at last. } {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltInfo's logging method. } {$ENDREGION} procedure Send(const AText: String; Args: array of const);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a ltInfo's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Args: array of const);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method. } {$ENDREGION} procedure Send(const AText, AValue: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText,AValue: String); overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: Integer); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Integer);overload; {$ifdef fpc} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: Cardinal); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Cardinal);overload; {$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: Double); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Double);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: Int64); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Int64);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: QWord); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: QWord);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; AValue: Boolean); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Boolean);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; const ARect: TRect); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; const ARect: TRect);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure Send(const AText: String; const APoint: TPoint); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; const APoint: TPoint);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methTStrings's logging method.} {$ENDREGION} procedure Send(const AText: String; AStrList: TStrings); overload; {$ifdef fpc}inline;{$endif} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; o_AStrList: TStrings);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methObject's logging method.} {$ENDREGION} procedure Send(const AText: String; AObject: TObject); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methObject's method.} {$ENDREGION} procedure Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AObject: TObject);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methValue's logging method.} {$ENDREGION} procedure SendPointer(const AText: String; APointer: Pointer); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methValue's method.} {$ENDREGION} procedure SendPointer(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; APointer: Pointer);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCallStack's logging method.} {$ENDREGION} procedure SendCallStack(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCallStack's method.} {$ENDREGION} procedure SendCallStack(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methException's logging method.} {$ENDREGION} procedure SendException(const AText: String; AException: Exception);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methException's method.} {$ENDREGION} procedure SendException(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AException: Exception);overload; {$REGION 'Xls: Comments section'} {§ Explanations: check Exception hierarchy (ultimate ancestor=EDatabaseError || EStreamError || ...), to grab its specific fields into a dumped string.} {$ENDREGION} function GetExceptionDescriptionFields(AException: Exception): string; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methHeapInfo's logging method.} {$ENDREGION} procedure SendHeapInfo(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methHeapInfo's method.} {$ENDREGION} procedure SendHeapInfo(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methMemory's logging method.} {$ENDREGION} procedure SendMemory(const AText: String; Address: Pointer; Size: LongWord; Offset: Integer = 0); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methMemory's method.} {$ENDREGION} procedure SendMemory(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; pAddress: Pointer; iSize: LongWord; iOffset: Integer = 0);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methConditional's logging method.} {$ENDREGION} procedure SendIf(const AText: String; Expression: Boolean); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; this methConditional method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure SendIf(Classes: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Expression: Boolean); overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methConditional's logging method.} {$ENDREGION} procedure SendIf(const AText: String; Expression, IsTrue: Boolean); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methConditional's method.} {$ENDREGION} procedure SendIf(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; bExpression, bIsTrue: Boolean);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltWarning's logging method.} {$ENDREGION} procedure SendWarning(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a ltWarning's method.} {$ENDREGION} procedure SendWarning(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltError's logging method.} {$ENDREGION} procedure SendError(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a ltError's method.} {$ENDREGION} procedure SendError(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCustomData's logging method.} {$ENDREGION} procedure SendCustomData(const AText: String; Data: Pointer);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCustomData's logging method.} {$ENDREGION} procedure SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCustomData's method.} {$ENDREGION} procedure SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; this methCustomData method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer);overload; {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCustomData's method.} {$ENDREGION} procedure SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCustomData's logging method.} {$ENDREGION} procedure SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure AddCheckPoint;overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; This methCheckpoint method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure AddCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure AddCheckPoint(const sCheckName: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCheckpoint's method.} {$ENDREGION} procedure AddCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const sCheckName: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCounter's logging method.} {$ENDREGION} procedure IncCounter(const sCounterName: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCounter's method.} {$ENDREGION} procedure IncCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCounter's logging method.} {$ENDREGION} procedure DecCounter(const sCounterName: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCounter's method.} {$ENDREGION} procedure DecCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCounter's logging method.} {$ENDREGION} procedure ResetCounter(const sCounterName: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCounter's method.} {$ENDREGION} procedure ResetCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String);overload; function GetCounter(const CounterName: String): Integer; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure ResetCheckPoint;overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; This methCheckpoint method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure ResetCheckPoint(Classes: TGroupOfForWhichTrackingPurposesMsgAreLogged);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure ResetCheckPoint(const sCheckName: String);overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methCheckpoint's method.} {$ENDREGION} procedure ResetCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged;const CheckName: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltEntertMethod's logging method.} {$ENDREGION} procedure EnterMethod(const AMethodName: String; const AMessage: String = ''); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; This ltEntertMethod method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure EnterMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AMethodName: String; const AMessage: String = ''); overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltEntertMethod's logging method.} {$ENDREGION} procedure EnterMethod(Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methEnterMethod's method.} {$ENDREGION} procedure EnterMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; Sender: TObject; const AMethodName: String; const AMessage: String = '');overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methExitMethod's logging method.} {$ENDREGION} procedure ExitMethod(const AMethodName: String; const AMessage: String = ''); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methExitMethod's logging method.} {$ENDREGION} procedure ExitMethod(Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; This methExitMethod method with overloaded specific parameter Classes, that allows us to pass or not [lwDebug, ...], to verify an existing intersection with ActiveClasses.} {$ENDREGION} procedure ExitMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AMethodName: String; const AMessage: String = ''); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methExitMethod's method.} {$ENDREGION} procedure ExitMethod({%H-}IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; Sender: TObject; const AMethodName: String; const AMessage: String = '');overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methWatch's logging method.} {$ENDREGION} procedure Watch(const AText, AValue: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methWatch's method.} {$ENDREGION} procedure Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText,AValue: String);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methWatch's logging method.} {$ENDREGION} procedure Watch(const AText: String; AValue: Integer); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methWatch's method.} {$ENDREGION} procedure Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Integer);overload; {$ifdef fpc} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure Watch(const AText: String; AValue: Cardinal); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methWatch's method.} {$ENDREGION} procedure Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Cardinal);overload; {$endif} {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure Watch(const AText: String; AValue: Double); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methWatch's method.} {$ENDREGION} procedure Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Double);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW methCheckpoint's logging method.} {$ENDREGION} procedure Watch(const AText: String; AValue: Boolean); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methWatch's method.} {$ENDREGION} procedure Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Boolean);overload; {$REGION 'Xls: Comments section'} {§ Explanations: logging; using public DefaultClasses containing Why this logging = [lwDebug, ...] which must intersect with ActiveClasses, to pass this WHICH\HOW ltInfo's logging method.} {$ENDREGION} procedure SubEventBetweenEnterAndExitMethods(const AText: String); overload; {$ifdef fpc}inline;{$endif} {$REGION 'Xls: Comments section'} {§ Explanations: whe log with a methSubEventBetweenEnterAndExitMethods's method.} {$ENDREGION} procedure SubEventMethodBetweenEnterAndExitMethods(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String);overload; class property DefaultChannels: TChannelList read GetDefaultChannels; property Enabled: Boolean read GetEnabled write SetEnabled; property Channels: TChannelList read FoChannels; property LogStack: TStrings read FoLogStack; property MaxStackCount: Integer read FiMaxStackCount write SetMaxStackCount; property OnCustomData: TCustomDataNotify read FOnCustomData write FOnCustomData; end; { TLogChannelWrapper } TLogChannelWrapper = class(TComponent) private FoChannel: TLogChannel; protected {$REGION 'Xls: Comments section'} {§ Explanations: if AComponent - a specialized channel, like TMemoChannel - is in a @code(TComponentState = [opRemove]), and if there's a AComponent's FChannelWrapper that is memory managed by AComponent, then this FChannelWrapper must stop immediately any activity.} {$ENDREGION} procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property Channel: TLogChannel read FoChannel write FoChannel; end; TFixedCriticalSection = class(TCriticalSection) private {$WARN 5029 off : Private field "$1.$2" is never used} // FDummy not used anywhere so switch off such warnings FDummy: array [0..95] of Byte; // fix multiprocessor cache safety http://blog.synopse.info/post/2016/01/09/Safe-locks-for-multi-thread-applications end; TGuardian = TFixedCriticalSection; var goLogger: TLogger; implementation uses db; const DefaultCheckName = 'CheckPoint'; function FormatNumber(iValue: Integer):String; var sTempStr: String; i, iDigits: Integer; begin iDigits:= 0; Result:= ''; sTempStr:= IntToStr(iValue); for i := length(sTempStr) downto 1 do begin //todo: implement using mod() -> get rids of iDigits if iDigits = 3 then begin iDigits:=0; Result:= DefaultFormatSettings.ThousandSeparator+Result; end; Result:= sTempStr[i]+Result; Inc(iDigits); end; end; {$REGION 'Xls: Comments section'} {§ Explanations: global procedure returns the literal description of the "sender" component that is at the origin of the event.} {$ENDREGION} function GetObjectDescription(Sender: TObject): String; begin Result:= Sender.ClassName; if (Sender is TComponent) and (TComponent(Sender).Name <> '') then Result := Result + '(' + TComponent(Sender).Name + ')'; end; var goGuardian: TGuardian; { TLogger } procedure TLogger.GetCallStack(AStream: TStream); {$ifdef fpc} var i: Longint; prevbp: Pointer; caller_frame, caller_addr, bp: Pointer; S: String; {$endif} begin {$ifdef fpc} //routine adapted from fpc source //This trick skip SendCallstack item //bp:=get_frame; //get_frame=IP's frame bp:= get_caller_frame(get_frame); //BP = number of the current base frame try prevbp:=bp-1; //prev_BP = number of the precedent base frame *) i:=0; //is_dev:=do_isdevice(textrec(f).Handle); while bp > prevbp Do // while we can pop... begin caller_addr := get_caller_addr(bp); //we get the IP's caller caller_frame := get_caller_frame(bp); //and its BP if (caller_addr=nil) then break; //We are back at the start point: all has been "poped" //todo: see what is faster concatenate string and use writebuffer or current S:=BackTraceStrFunc(caller_addr)+LineEnding; //EI name AStream.WriteBuffer(S[1],Length(S)); Inc(i); if (i>=FiMaxStackCount) or (caller_frame=nil) then break; prevbp:=bp; //previous variable is set with the IP bp:=caller_frame; //the IP becomes the courent caller of the courrent frame: we backward from one call frame end; except { prevent endless dump if an exception occured } end; {$endif} end; procedure TLogger.SetEnabled(AValue: Boolean); begin if AValue then begin if TargetedConstantGroup1_OfWhatCanBeLogged = [] then TargetedConstantGroup1_OfWhatCanBeLogged := FsetLast_TargetedConstantGroup1_OfWhatCanBeLogged; end else begin FsetLast_TargetedConstantGroup1_OfWhatCanBeLogged := TargetedConstantGroup1_OfWhatCanBeLogged; TargetedConstantGroup1_OfWhatCanBeLogged := []; end; end; class function TLogger.GetDefaultChannels: TChannelList; begin if FoDefaultChannels = nil then FoDefaultChannels := TChannelList.Create; Result := FoDefaultChannels; end; function TLogger.GetEnabled: Boolean; begin Result:= TargetedConstantGroup1_OfWhatCanBeLogged <> []; end; procedure TLogger.Store_FsetForWhichTrackingPurposesMsgAreLogged(const setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged); begin FsetForWhichTrackingPurposesMsgAreLogged:= setGroupIntersection; end; procedure DispatchLogMessage(o_Channels: TChannelList; const Msg: TLogMessage); var i: Integer; o_Channel: TLogChannel; begin for i := 0 to o_Channels.Count - 1 do begin o_Channel := o_Channels[i]; if o_Channel.Active then o_Channel.Deliver(Msg); end; end; procedure TLogger.SendStream(AMethodUsed: Integer; const AText: String; o_AStream: TStream); var recMsg: TLogMessage; setOldForWhichTrackingPurposesMsgAreLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin with recMsg do begin iMethUsed := AMethodUsed; dtMsgTime := Now; sMsgText := AText; pData := o_AStream; end; setOldForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged; if (AMethodUsed = methSubEventBetweenEnterAndExitMethods) or (AMethodUsed = methEnterMethod) or (AMethodUsed = methExitMethod) then recMsg.setGroupOfForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged + [lwStudyChainedEvents] else if (AMethodUsed = methError) or ((AMethodUsed = methException)) then recMsg.setGroupOfForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged + [lwError] else if (AMethodUsed = methWarning) then recMsg.setGroupOfForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged + [lwWarning] else if (AMethodUsed = methInfo) then recMsg.setGroupOfForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged + [lwInfo] else recMsg.setGroupOfForWhichTrackingPurposesMsgAreLogged:= FsetForWhichTrackingPurposesMsgAreLogged; (*IsMultiThread == true, when unit cthreads is used by a project*) if IsMultiThread then //Yes: it's a global variable created in this unit, and used in this unit only ;-) goGuardian.Enter; if FoDefaultChannels <> nil then DispatchLogMessage(FoDefaultChannels, recMsg); DispatchLogMessage(Channels, recMsg); FsetForWhichTrackingPurposesMsgAreLogged:= setOldForWhichTrackingPurposesMsgAreLogged; if IsMultiThread then goGuardian.Leave; end; procedure TLogger.SendBuffer(AMethodUsed: Integer; const AText: String; var pBuffer; Count: LongWord); var oStream: TStream; begin try if Count > 0 then begin oStream:= TMemoryStream.Create; oStream.Write(pBuffer,Count); end else oStream:= nil; SendStream(AMethodUsed,AText,oStream); //nb: SendStream will free oStream finally oStream.Free; end; end; procedure TLogger.SetMaxStackCount(const AValue: Integer); begin if AValue < 256 then FiMaxStackCount := AValue else FiMaxStackCount := 256; end; procedure TLogger.SetThreadSafe; begin if IsMultiThread and not Assigned(goGuardian) then goGuardian:= TGuardian.Create else if (not IsMultiThread) and Assigned(goGuardian) then FreeAndNil(goGuardian); end; constructor TLogger.Create; begin SetThreadSafe; FoChannels := TChannelList.Create; FiMaxStackCount := 20; FoLogStack := TStringList.Create; FoCheckList := TStringList.Create; with FoCheckList do begin CaseSensitive := False; Sorted := True; //Faster IndexOf? end; FoCounterList := TStringList.Create; with FoCounterList do begin CaseSensitive := False; Sorted := True; //Faster IndexOf? end; TargetedConstantGroup1_OfWhatCanBeLogged := [lwDebug]; //categor{y|ies} of What is logged; lwDebug = 0 IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged := [lwDebug]; //categor{y|ies} of What is logged; lwDebug = 0 end; destructor TLogger.Destroy; begin FoChannels.Destroy; FoLogStack.Destroy; FoCheckList.Destroy; FoCounterList.Destroy; if Assigned(goGuardian) then FreeAndNil(goGuardian); end; function TLogger.CalledBy(const AMethodName: String): Boolean; begin Result:= FoLogStack.IndexOf(UpperCase(AMethodName)) <> -1; end; procedure ClearChannels(o_Channels: TChannelList); var i: Integer; o_Channel: TLogChannel; begin for i := 0 to o_Channels.Count - 1 do begin o_Channel := o_Channels[i]; if o_Channel.Active then o_Channel.Clear; end; end; procedure TLogger.Clear; begin if FoDefaultChannels <> nil then ClearChannels(FoDefaultChannels); ClearChannels(Channels); end; function TLogger.RectToStr(const ARect: TRect): String; begin with ARect do Result:= Format('(Left: %d; Top: %d; Right: %d; Bottom: %d)',[Left,Top,Right,Bottom]); end; function TLogger.PointToStr(const APoint: TPoint): String; begin with APoint do Result:= Format('(X: %d; Y: %d)',[X,Y]); end; procedure TLogger.Send(const AText: String); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; procedure TLogger.Send(const AText: String; Args: array of const); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Args); end; procedure TLogger.Send(const AText, AValue: String); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Send(const AText: String; AValue: Integer); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; {$ifdef fpc} procedure TLogger.Send(const AText: String; AValue: Cardinal); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; {$endif} procedure TLogger.Send(const AText: String; AValue: Double); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Send(const AText: String; AValue: Int64); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Send(const AText: String; AValue: QWord); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Send(const AText: String; AValue: Boolean); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged, AText, AValue); end; procedure TLogger.Send(const AText: String; const ARect: TRect); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,ARect); end; procedure TLogger.Send(const AText: String; const APoint: TPoint); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,APoint); end; procedure TLogger.Send(const AText: String; AStrList: TStrings); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AStrList); end; procedure TLogger.Send(const AText: String; AObject: TObject); begin Send(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AObject); end; procedure TLogger.SendPointer(const AText: String; APointer: Pointer); begin SendPointer(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,APointer); end; procedure TLogger.SendCallStack(const AText: String); begin SendCallStack(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; procedure TLogger.SendException(const AText: String; AException: Exception); begin SendException(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AException); end; procedure TLogger.SendHeapInfo(const AText: String); begin SendHeapInfo(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; procedure TLogger.SendMemory(const AText: String; Address: Pointer; Size: LongWord; Offset: Integer); begin SendMemory(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Address,Size,Offset) end; procedure TLogger.SendIf(const AText: String; Expression: Boolean); begin SendIf(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Expression,True); end; procedure TLogger.SendIf(Classes: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Expression: Boolean); begin SendIf(Classes,AText,Expression,True); end; procedure TLogger.SendIf(const AText: String; Expression, IsTrue: Boolean); begin SendIf(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Expression,IsTrue); end; procedure TLogger.SendWarning(const AText: String); begin SendWarning(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; procedure TLogger.SendError(const AText: String); begin SendError(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; procedure TLogger.SendCustomData(const AText: String; Data: Pointer); begin SendCustomData(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Data,FOnCustomData); end; procedure TLogger.SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer); begin SendCustomData(IntersectingGroup2_OfWhatCanBeLogged,AText,Data,FOnCustomData); end; procedure TLogger.SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); begin SendCustomData(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Data,CustomDataFunction); end; procedure TLogger.SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); begin SendCustomData(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,Data,CustomDataFunction); end; procedure TLogger.AddCheckPoint; begin AddCheckPoint(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,DefaultCheckName); end; procedure TLogger.AddCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged); begin AddCheckPoint(IntersectingGroup2_OfWhatCanBeLogged,DefaultCheckName); end; procedure TLogger.AddCheckPoint(const sCheckName: String); begin AddCheckPoint(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,sCheckName); end; procedure TLogger.ResetCheckPoint; begin ResetCheckPoint(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,DefaultCheckName); end; procedure TLogger.ResetCheckPoint(Classes: TGroupOfForWhichTrackingPurposesMsgAreLogged); begin ResetCheckPoint(Classes,DefaultCheckName); end; procedure TLogger.ResetCheckPoint(const sCheckName: String); begin ResetCheckPoint(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,sCheckName); end; procedure TLogger.IncCounter(const sCounterName: String); begin IncCounter(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,sCounterName); end; procedure TLogger.DecCounter(const sCounterName: String); begin DecCounter(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,sCounterName); end; procedure TLogger.ResetCounter(const sCounterName: String); begin ResetCounter(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,sCounterName); end; procedure TLogger.EnterMethod(const AMethodName: String; const AMessage: String); begin EnterMethod(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,nil,AMethodName,AMessage); end; procedure TLogger.EnterMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AMethodName: String; const AMessage: String); begin EnterMethod(IntersectingGroup2_OfWhatCanBeLogged,nil,AMethodName,AMessage); end; procedure TLogger.EnterMethod(Sender: TObject; const AMethodName: String; const AMessage: String); begin EnterMethod(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,Sender,AMethodName,AMessage); end; procedure TLogger.ExitMethod(const AMethodName: String; const AMessage: String); begin ExitMethod(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,nil,AMethodName,AMessage); end; procedure TLogger.ExitMethod(Sender: TObject; const AMethodName: String; const AMessage: String); begin ExitMethod(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,Sender,AMethodName,AMessage); end; procedure TLogger.ExitMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AMethodName: String; const AMessage: String); begin ExitMethod(IntersectingGroup2_OfWhatCanBeLogged,nil,AMethodName,AMessage); end; procedure TLogger.Watch(const AText, AValue: String); begin Watch(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Watch(const AText: String; AValue: Integer); begin Watch(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; {$ifdef fpc} procedure TLogger.Watch(const AText: String; AValue: Cardinal); begin Watch(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; {$endif} procedure TLogger.Watch(const AText: String; AValue: Double); begin Watch(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.Watch(const AText: String; AValue: Boolean); begin Watch(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText,AValue); end; procedure TLogger.SubEventBetweenEnterAndExitMethods(const AText: String); begin SubEventMethodBetweenEnterAndExitMethods(IntersectingGroup2ForProcWithoutParamGroup2_OfWhatCanBeLogged,AText); end; (* -- filtred method through intersection of Classes's set and ActivesClasses's set -- *) procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwInfo]); SendStream(methInfo,AText,nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Args: array of const); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwInfo]); SendStream(methInfo, Format(AText,Args),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText, AValue: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+AValue,nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Integer); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+IntToStr(AValue),nil); end; {$ifdef fpc} procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Cardinal); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+IntToStr(AValue),nil); end; {$endif} procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Double); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+FloatToStr(AValue),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Int64); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+IntToStr(AValue),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: QWord); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+IntToStr(AValue),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Boolean); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue, AText + ' = ' + BoolToStr(AValue, True), nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String;const ARect: TRect); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+ ' = '+RectToStr(ARect),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; const APoint: TPoint); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue,AText+' = '+PointToStr(APoint),nil); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; o_AStrList: TStrings); var sStr: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); if Assigned(o_AStrList) then if o_AStrList.Count>0 then sStr:= o_AStrList.Text else sStr:= ' ' { fake o_AStrList.Text } else sStr:= ' '; { fake o_AStrList.Text } SendBuffer(methTStrings, AText, sStr[1], Length(sStr)); end; procedure TLogger.Send(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AObject: TObject); var sTempStr: String; oStream: TStream; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); try oStream := nil; sTempStr := AText + ' ['; if AObject <> nil then begin if AObject is TComponent then begin oStream := TMemoryStream.Create; oStream.WriteComponent(TComponent(AObject)); end else sTempStr := sTempStr + GetObjectDescription(AObject) + ' / '; end; sTempStr := sTempStr + ('$' + HexStr(AObject) + ']'); SendStream(methObject, sTempStr, oStream); finally oStream.Free; end; end; procedure TLogger.SendPointer(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; APointer: Pointer); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methValue, AText + ' = $' + HexStr(APointer), nil); end; procedure TLogger.SendCallStack(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); var oStream: TStream; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); try oStream:=TMemoryStream.Create; GetCallStack(oStream); SendStream(methCallStack,AText,oStream); //nb: SendStream will free oStream finally oStream.Free; end; end; function TLogger.GetExceptionDescriptionFields(AException: Exception): string; var sDescrFields: string; begin sDescrFields:= ''; if (AException is EDatabaseError) then if (AException is EUpdateError) then begin with (AException as EUpdateError) do begin sDescrFields:= sDescrFields + '- Context:' + Context + LineEnding; sDescrFields:= sDescrFields + '- ErrorCode:' + IntToStr(ErrorCode) + LineEnding; sDescrFields:= sDescrFields + '- PreviousError:' + IntToStr(PreviousError) + LineEnding; sDescrFields:= sDescrFields + '- OriginalException:' + OriginalException.ClassName + ' - ' + AException.Message + LineEnding; result:= sDescrFields; Exit; end end { else if (AException is EDomError) then begin .../... end else if (AException is EStreamError) .../... then begin .../... end } end; procedure TLogger.SendException(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AException: Exception); {$ifdef fpc} var i: Integer; pFrames: PPointer; sStr: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; {$endif} begin {$ifdef fpc} setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwError]); if (AException <> nil) then sStr:= AException.ClassName + ' - ' + AException.Message + LineEnding + GetExceptionDescriptionFields(AException); sStr:= sStr + BackTraceStrFunc(ExceptAddr); pFrames:= ExceptFrames; for i:= 0 to ExceptFrameCount - 1 do sStr:= sStr + (LineEnding + BackTraceStrFunc(pFrames[i])); SendBuffer(methException,AText,sStr[1],Length(sStr)); {$endif} end; procedure TLogger.SendHeapInfo(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); {$ifdef fpc} var sStr: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; {$endif} begin {$ifdef fpc} setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); with GetFPCHeapStatus do begin sStr:= 'All values are in [bytes]:'+LineEnding +'MaxHeapSize: '+FormatNumber(MaxHeapSize)+LineEnding +'MaxHeapUsed: '+FormatNumber(MaxHeapUsed)+LineEnding +'CurrHeapSize: '+FormatNumber(CurrHeapSize)+LineEnding +'CurrHeapUsed: '+FormatNumber(CurrHeapUsed)+LineEnding +'CurrHeapFree: '+FormatNumber(CurrHeapFree); end; SendBuffer(methHeapInfo,AText,sStr[1],Length(sStr)); {$endif} end; procedure TLogger.SendMemory(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; pAddress: Pointer; iSize: LongWord; iOffset: Integer); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); if pAddress <> nil then begin if iOffset <> 0 then pAddress := pAddress + iOffset; end else begin //empty pAddress := Self; iSize := 0; end; SendBuffer(methMemory,AText,pAddress^,iSize); end; procedure TLogger.SendIf(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; bExpression, bIsTrue: Boolean); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if (setGroupIntersection = []) or (bExpression <> bIsTrue) then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methConditional,AText,nil); end; procedure TLogger.SendWarning(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwWarning]); SendStream(methWarning,AText,nil); end; procedure TLogger.SendError(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwError]); SendStream(methError,AText,nil); end; procedure TLogger.SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); var bDoSend: Boolean; sTempStr: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if (setGroupIntersection = []) or (not Assigned(CustomDataFunction)) then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); bDoSend:=True; sTempStr:=CustomDataFunction(Self,Data,bDoSend); if bDoSend then SendBuffer(methCustomData,AText,sTempStr[1],Length(sTempStr)); end; procedure TLogger.SendCustomData(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); var bDoSend: Boolean; sTempStr: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if (setGroupIntersection = []) or (not Assigned(CustomDataFunction)) then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); bDoSend:=True; sTempStr:=CustomDataFunction(Self,Data,bDoSend); if bDoSend then SendBuffer(methCustomData,AText,sTempStr[1],Length(sTempStr)); end; procedure TLogger.AddCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const sCheckName: String); var i: Integer; pOnObj: PtrInt; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); i:=FoCheckList.IndexOf(sCheckName); if i <> -1 then begin //Add a custom CheckList pOnObj:=PtrInt(FoCheckList.Objects[i])+1; FoCheckList.Objects[i]:=TObject(pOnObj); end else begin FoCheckList.AddObject(sCheckName,TObject(0)); pOnObj:=0; end; SendStream(methCheckpoint,sCheckName+' #'+IntToStr(pOnObj),nil); end; procedure TLogger.IncCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String ); var i: Integer; pOnObject: PtrInt; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin pOnObject := PtrInt(FoCounterList.Objects[i]) + 1; FoCounterList.Objects[i] := TObject(pOnObject); end else begin FoCounterList.AddObject(CounterName, TObject(1)); pOnObject := 1; end; SendStream(methCounter,CounterName+'='+IntToStr(pOnObject),nil); end; procedure TLogger.DecCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String); var i: Integer; pOnObj: PtrInt; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin pOnObj := PtrInt(FoCounterList.Objects[i]) - 1; FoCounterList.Objects[i] := TObject(pOnObj); end else begin FoCounterList.AddObject(CounterName, TObject(-1)); pOnObj := -1; end; SendStream(methCounter,CounterName+'='+IntToStr(pOnObj),nil); end; procedure TLogger.ResetCounter(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CounterName: String); var i: Integer; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin FoCounterList.Objects[i] := TObject(0); SendStream(methCounter, FoCounterList[i] + '=0', nil); end; end; function TLogger.GetCounter(const CounterName: String): Integer; var i: Integer; begin i := FoCounterList.IndexOf(CounterName); if i <> -1 then Result := PtrInt(FoCounterList.Objects[i]) else Result := 0; end; procedure TLogger.ResetCheckPoint(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const CheckName:String); var i: Integer; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); i:= FoCheckList.IndexOf(CheckName); if i <> -1 then begin FoCheckList.Objects[i] := TObject(0); SendStream(methCheckpoint, CheckName+' #0',nil); end; end; procedure TLogger.EnterMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; Sender: TObject; const AMethodName: String; const AMessage: String); var sAText: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwEvents]); FoLogStack.Insert(0, UpperCase(AMethodName)); if AMessage <> '' then sAText := AMessage else if Sender <> nil then sAText := GetObjectDescription(Sender) + '.' + AMethodName else sAText := AMethodName; SendStream(methEnterMethod, sAText, nil); end; procedure TLogger.ExitMethod(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; Sender: TObject; const AMethodName: String; const AMessage: String); var i: Integer; sAText: String; setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin //ensure that ExitMethod will be called always even if there's an unpaired Entermethod (!) if FoLogStack.Count = 0 then Exit; setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection + [lwEvents]); //todo: see if is necessary to do Uppercase (set case sensitive to false?) i := FoLogStack.IndexOf(UpperCase(AMethodName)); if i <> -1 then FoLogStack.Delete(i) else Exit; if AMessage <> '' then sAText := AMessage else if Sender <> nil then sAText := GetObjectDescription(Sender) + '.' + AMethodName else sAText := AMethodName; SendStream(methExitMethod, sAText, nil); end; procedure TLogger.Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Integer); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methWatch,AText+'='+IntToStr(AValue),nil); end; {$ifdef fpc} procedure TLogger.Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Cardinal); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methWatch,AText+'='+IntToStr(AValue),nil); end; {$endif} procedure TLogger.Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Double); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methWatch,AText+'='+FloatToStr(AValue),nil); end; procedure TLogger.Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String; AValue: Boolean); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methWatch,AText+'='+BoolToStr(AValue),nil); end; procedure TLogger.Watch(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText, AValue: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methWatch,AText+'='+AValue,nil); end; procedure TLogger.SubEventMethodBetweenEnterAndExitMethods(IntersectingGroup2_OfWhatCanBeLogged: TGroupOfForWhichTrackingPurposesMsgAreLogged; const AText: String); var setGroupIntersection: TGroupOfForWhichTrackingPurposesMsgAreLogged; begin setGroupIntersection:= IntersectingGroup2_OfWhatCanBeLogged * TargetedConstantGroup1_OfWhatCanBeLogged; if setGroupIntersection = [] then Exit; //pre-conditions: the intersection of IntersectingGroup2_OfWhatCanBeLogged and ActivesClasses must not be empty Store_FsetForWhichTrackingPurposesMsgAreLogged(setGroupIntersection); SendStream(methSubEventBetweenEnterAndExitMethods,AText,nil); end; { TChannelList } function TChannelList.GetCount: Integer; begin Result := FoList.Count; end; function TChannelList.GetItems(AIndex:Integer): TLogChannel; begin Result := TLogChannel(FoList[AIndex]); end; constructor TChannelList.Create; begin FoList := TFPList.Create; end; destructor TChannelList.Destroy; var i: Integer; begin //free the registered channels for i := FoList.Count - 1 downto 0 do Items[i].Free; FoList.Destroy; end; function TChannelList.Add(AChannel: TLogChannel):Integer; begin Result := FoList.Add(AChannel); AChannel.Init; end; procedure TChannelList.Remove(AChannel: TLogChannel); begin FoList.Remove(AChannel); end; { TLogChannel } procedure TLogChannel.Init; begin //must be overriden in its descendants end; procedure TLogChannelWrapper.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FoChannel <> nil) then FoChannel.Active := False; end; initialization goLogger:=TLogger.Create; finalization TLogger.FoDefaultChannels.Free; goLogger.Free; end.
unit Cloud.Core; interface uses System.SysUtils, System.Classes, System.IOUtils, System.JSON, App.Intf, DEX.Types, Cloud.Types, Cloud.Consts, Cloud.Client, Cloud.Log, Cloud.Utils; type TInfoProc = reference to procedure(const Info: TCloudResponseInfo); TErrorProc = reference to procedure(const Error: TCloudResponseError); TOfferAccountProc = reference to procedure(AccountID: Integer); TCloudCore = class(TCloudDelegate) private CloudHost: string; CloudPort: Word; KeepAlive: Boolean; procedure ReadConfig(jsConfig: TJSONObject); private Queue: array of TProc; procedure Enqueue(const Name: string; Proc: TProc); procedure Dequeue; private Client: TCloudClient; OfferAccount: Int64; FShowEventMessages: Boolean; procedure DoExcept(const Text: string); procedure DoConnection; procedure ExecuteBeginProc; private DoRegistrationProc: TProc; DoLoginProc: TProc; DoConnectProc: TProc; DoBeginProc: TProc; DoErrorProcDefault: TErrorProc; DoErrorProc: TErrorProc; DoInfoProc: TInfoProc; DoCreateAddressProc: TProc; DoSendToProc: TProc; DoOfferAccountProc: TOfferAccountProc; DoCreateOfferProc: TProc; private procedure OnEvent(Event: TCloudEvent; const Text: string); override; procedure OnInit(const Init: TCloudResponseInit); override; procedure OnError(const Error: TCloudResponseError); override; procedure OnRegistration(const Registration: TCloudResponseRegistration); override; procedure OnLogin(const Login: TCloudResponseLogin); override; procedure OnAddresses(const Addresses: TCloudResponseGetAddresses); override; procedure OnCreateAddress(const Address: TCloudResponseCreateAddress); override; procedure OnTransactions(const Transactions: TCloudResponseTransactions); override; procedure OnAddress(const Address: TCloudResponseCurrentAddresses); override; procedure OnInfo(const Info: TCloudResponseInfo); override; procedure OnSendTo(const SendTo: TCloudResponseSendTo); override; procedure OnRatio(const Ratio: TCloudResponseRatio); override; procedure OnRequestForging(const Forging: TCloudRequestForging); override; procedure OnForging(const Forging: TCloudResponseForging); override; procedure OnRequestAccountBalance(const AccountBalance: TCloudRequestAccountBalance); override; procedure OnCreateOffer(const Offer: TCloudResponseCreateOffer); override; procedure OnOffers(const Offers: TCloudResponseOffers); override; procedure OnOfferAccount(const Account: TCloudResponseOfferAccount); override; procedure OnRequestTransfer(const Transfer: TCloudRequestTransfer); override; procedure OnKillOffers(const Offers: TCloudResponseKillOffers); override; procedure OnActiveOffers(const Offers: TCloudResponseOffers); override; procedure OnClosedOffers(const Offers: TCloudResponseOffers); override; procedure OnHistoryOffers(const Offers: TCloudResponseOffers); override; procedure OnPairsSummary(const Pairs: TCloudResponsePairs); override; procedure OnSetNotifications(const Notifications: TCloudResponseNotifications); override; procedure OnNotifyEvent(const NotifyEvent: TCloudResponseNotifyEvent); override; procedure OnCandles(const Candles: TCloudResponseCandles); override; procedure OnTradingHistory(const Trades: TCloudResponseTrades); override; public constructor Create; overload; destructor Destroy; override; function Workloaded: Boolean; procedure Connect; procedure Disconnect; procedure Unauthorized; procedure Cancel; function Ready: Boolean; procedure SetNetwork(const NetworkName: string; jsConfig: TJSONObject); procedure SetAuth(const Email,Password: string; AccountID: Int64); procedure SetKeepAlive(KeepAlive: Boolean; RecoveryInterval: Cardinal); procedure SendRequestLogin; procedure SendRequestBalance(const Symbol: string); procedure SendRequestTransfer(const Symbol,Address: string; Amount: Extended); procedure SendRequestRatio; procedure SendRequestForging(Owner,TokenID: Int64; const Symbol: string; BuyAmount,PayAmount,Ratio,Commission1,Commission2: Extended); procedure SendRequestCreateOffer(Direction: Integer; const Symbol1,Symbol2: string; Amount,Ratio: Extended; EndDate: TDateTime); procedure SendRequestOffers(const Symbol1,Symbol2: string); procedure SendRequestKillOffers(const Offers: TArray<Int64>); procedure SendRequestActiveOffer; procedure SendRequestClosedOffer(BeginDate,EndDate: TDateTime); procedure SendRequestHistoryOffer(BeginDate,EndDate: TDateTime); procedure SendRequestPairsSummary; procedure SendRequestCandles(const Symbol1,Symbol2: string; BeginDate: TDateTime; IntervalType: Integer); procedure SendRequestSetNotifications(Enabled: Boolean); procedure SendRequestTradingHistory(const Symbol1,Symbol2: string; Count: Integer); property ShowEventMessages: Boolean read FShowEventMessages write FShowEventMessages; end; implementation constructor TCloudCore.Create; begin Client:=TCloudClient.Create; Client.SetDelegate(Self); DoErrorProcDefault:=procedure(const Error: TCloudResponseError) begin if Error.Code='816' then DoRegistrationProc else DoExcept(Error.ErrorString); end; SetAuth('','',0); end; destructor TCloudCore.Destroy; begin Client.Free; inherited; end; procedure TCloudCore.ReadConfig(jsConfig: TJSONObject); var jsCloud: TJSONObject; begin if Assigned(jsConfig) then begin jsCloud:=jsConfig.GetValue<TJSONObject>('cloud',nil); if Assigned(jsCloud) then begin CloudHost:=jsCloud.GetValue<string>('host'); CloudPort:=jsCloud.GetValue<Word>('port'); KeepAlive:=jsCloud.GetValue<Boolean>('keepalive',False); end; end; end; function TCloudCore.Workloaded: Boolean; begin Result:=Client.Workloaded; end; procedure TCloudCore.Enqueue(const Name: string; Proc: TProc); begin if Length(Queue)>10 then begin Cancel; UI.ShowException('too many requests'); end else begin Queue:=Queue+[Proc]; ToLog('Add procedure '+Name+' to queue['+High(Queue).ToString+']'); if Length(Queue)=1 then Queue[0](); end; end; procedure TCloudCore.Dequeue; begin Delete(Queue,0,1); if Length(Queue)>0 then Queue[0]() else DoBeginProc:=nil; end; procedure TCloudCore.DoExcept(const Text: string); begin ToLog('error:'+Text); UI.WaitCancel; UI.ShowException(Text); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.DoConnection; begin if not Client.Connected then Client.Connect else if not Client.Authorized then DoLoginProc else ExecuteBeginProc; end; procedure TCloudCore.OnEvent(Event: TCloudEvent; const Text: string); begin ToLog(Text); if ShowEventMessages then case Event of EVENT_REQUEST: UI.ShowMessage('>'+Text); EVENT_RESPONSE: UI.ShowMessage('<'+Text); else UI.ShowMessage(Text); end; end; procedure TCloudCore.OnError(const Error: TCloudResponseError); begin ToLog(Error); DoErrorProc(Error); end; procedure TCloudCore.OnInit(const Init: TCloudResponseInit); begin DoConnectProc; end; procedure TCloudCore.OnRegistration(const Registration: TCloudResponseRegistration); begin DoLoginProc; end; procedure TCloudCore.OnLogin(const Login: TCloudResponseLogin); begin AppCore.DoCloudLogin; ExecuteBeginProc; end; procedure TCloudCore.OnInfo(const Info: TCloudResponseInfo); begin DoInfoProc(Info); end; procedure TCloudCore.OnAddresses(const Addresses: TCloudResponseGetAddresses); begin end; procedure TCloudCore.OnCreateAddress(const Address: TCloudResponseCreateAddress); begin DoCreateAddressProc; end; procedure TCloudCore.OnTransactions(const Transactions: TCloudResponseTransactions); begin end; procedure TCloudCore.OnAddress(const Address: TCloudResponseCurrentAddresses); begin end; procedure TCloudCore.OnSendTo(const SendTo: TCloudResponseSendTo); begin DoSendToProc; end; procedure TCloudCore.OnRatio(const Ratio: TCloudResponseRatio); begin UI.WaitCancel; AppCore.DoCloudRatio(Ratio.RatioBTC,Ratio.RatioLTC,Ratio.RatioETH); UI.WaitUnlock; Dequeue; end; // on owner RLC and GTN tokens node procedure TCloudCore.OnRequestForging(const Forging: TCloudRequestForging); var R: string; begin R:='0'; // failed try AppCore.DoForging(Forging.Owner,Forging.Buyer,Forging.BuyToken,Forging.BuyAmount, Forging.Commission1,Forging.Commission2); R:='1'; // success except on E: Exception do ToLog('Exception: '+E.Message); end; Client.SendResponseForging(Forging.Request,R); // response to cloud end; procedure TCloudCore.OnForging(const Forging: TCloudResponseForging); begin if Forging.Result=1 then begin UI.WaitCancel; AppCore.DoCloudForgingResult(Forging.Tx); UI.WaitUnlock; Dequeue; end else DoExcept('error'); end; // on cloud node procedure TCloudCore.OnRequestAccountBalance(const AccountBalance: TCloudRequestAccountBalance); var AmountRLC,AmountGTN: Extended; begin AmountRLC:=AppCore.GetSymbolBalance('RLC'); AmountGTN:=AppCore.GetSymbolBalance('GTN'); Client.SendResponseAccountBalance(AmountRLC,AmountGTN); // response to cloud end; procedure TCloudCore.OnCreateOffer(const Offer: TCloudResponseCreateOffer); begin UI.WaitCancel; AppCore.DoCloudCreateOffer(Offer.OfferID); UI.WaitUnlock; Dequeue; end; function CloudOfferToOffer(const Offer: TCloudOffer): TOffer; begin Result.Status:=Offer.Status; Result.ID:=Offer.ID; Result.AccountID:=Offer.AccountID; Result.Direction:=Offer.Direction; Result.Symbol1:=SymbolBy(Offer.SymbolID1); Result.Symbol2:=SymbolBy(Offer.SymbolID2); Result.Ratio:=Offer.Ratio; Result.StrtAmount:=Offer.StrtAmount; Result.CrrntAmount:=Offer.CrrntAmount; Result.StartDate:=Offer.StartDate; Result.LastDate:=Offer.LastDate; Result.EndDate:=Offer.EndDate; end; function CloudOffersToOffers(const Offers: TCloudOffers): TOffers; begin Result:=nil; for var Offer in Offers do Result:=Result+[CloudOfferToOffer(Offer)]; end; function CloudPairToPair(const Pair: TCloudPair): TPair; begin Result.Symbol1:=SymbolBy(Pair.SymbolID1); Result.Symbol2:=SymbolBy(Pair.SymbolID2); Result.Ratio:=Pair.Ratio; Result.Volume:=Pair.Volume; Result.LastDate:=Pair.LastDate; Result.Ratio24hAgo:=Pair.Ratio24hAgo; Result.Low:=Pair.Low; Result.High:=Pair.High; if Result.Ratio24hAgo>0 then Result.Percent:=100*(Result.Ratio/Result.Ratio24hAgo-1) else Result.Percent:=0; end; function CloudPairsToPairs(const Pairs: TCloudPairs): TPairs; begin Result:=nil; for var Pair in Pairs do Result:=Result+[CloudPairToPair(Pair)]; end; procedure TCloudCore.OnOffers(const Offers: TCloudResponseOffers); begin UI.WaitCancel; AppCore.DoCloudOffers(CloudOffersToOffers(Offers.Offers)); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnOfferAccount(const Account: TCloudResponseOfferAccount); begin DoOfferAccountProc(Account.AccountID); end; function AnyOf(const S: string; const Values: array of string): Boolean; begin Result:=False; for var V in Values do if SameText(S,V) then Exit(True); end; // on cloud node procedure TCloudCore.OnRequestTransfer(const Transfer: TCloudRequestTransfer); var Symbol: string; begin Symbol:=SymbolBy(Transfer.SymbolID); if not AnyOf(Symbol,['RLC','GTN']) then Client.SendResponseError(1109,'wrong coin') else if not (Transfer.Amount>0) then Client.SendResponseError(1111,'wrong amount') else if Transfer.Amount>AppCore.GetSymbolBalance(Symbol) then Client.SendResponseError(782,'insufficient funds') else try // blockchain transfer AppCore.DoTransferToken2(SymbolBy(Transfer.SymbolID),Transfer.ToAccountID.ToString,Transfer.Amount); Client.SendResponseTransfer; // success response to cloud except on E: Exception do Client.SendResponseError(781,E.Message); // any transfer exception end; end; procedure TCloudCore.OnKillOffers(const Offers: TCloudResponseKillOffers); begin UI.WaitCancel; AppCore.DoCloudKillOffers(Offers.Offers); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnActiveOffers(const Offers: TCloudResponseOffers); begin UI.WaitCancel; AppCore.DoCloudActiveOffers(CloudOffersToOffers(Offers.Offers)); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnClosedOffers(const Offers: TCloudResponseOffers); begin UI.WaitCancel; AppCore.DoCloudClosedOffers(CloudOffersToOffers(Offers.Offers)); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnHistoryOffers(const Offers: TCloudResponseOffers); begin UI.WaitCancel; AppCore.DoCloudHistoryOffers(CloudOffersToOffers(Offers.Offers)); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnPairsSummary(const Pairs: TCloudResponsePairs); begin UI.WaitCancel; AppCore.DoCloudPairsSummary(CloudPairsToPairs(Pairs.Pairs)); UI.WaitUnlock; Dequeue; end; procedure TCloudCore.OnSetNotifications(const Notifications: TCloudResponseNotifications); begin AppCore.DoCloudSetNotifications(Notifications.Enabled); Dequeue; end; procedure TCloudCore.OnNotifyEvent(const NotifyEvent: TCloudResponseNotifyEvent); begin AppCore.DoCloudNotifyEvent(SymbolBy(NotifyEvent.SymbolID1),SymbolBy(NotifyEvent.SymbolID2), NotifyEvent.EventCode); Dequeue; end; function CloudCandleToCandle(const Candle: TCloudCandle): TDataCandle; begin Result.DateTime:=Candle.DateTime; Result.Time:=Candle.UnixTime; Result.Open:=Candle.Open; Result.Close:=Candle.Close; Result.Min:=Candle.Min; Result.Max:=Candle.Max; Result.Volume:=Candle.Volume; end; function CloudCandlesToCandles(const Candles: TCloudCandles): TDataCandles; begin Result:=nil; for var Candle in Candles do Result:=Result+[CloudCandleToCandle(Candle)]; end; procedure TCloudCore.OnCandles(const Candles: TCloudResponseCandles); begin UI.WaitCancel; AppCore.DoCloudCandles(SymbolBy(Candles.SymbolID1),SymbolBy(Candles.SymbolID2), Candles.IntervalCode,CloudCandlesToCandles(Candles.Candles)); UI.WaitUnlock; Dequeue; end; function CloudTradeToTrade(const Trade: TCloudTrade): TDataTrade; begin Result.Direction:=Trade.Direction; Result.Volume:=Trade.Volume; Result.Ratio:=Trade.Ratio; Result.Date:=Trade.Date; end; function CloudTradesToTrades(const Trades: TCloudTrades): TDataTrades; begin Result:=nil; for var Trade in Trades do Result:=Result+[CloudTradeToTrade(Trade)]; end; procedure TCloudCore.OnTradingHistory(const Trades: TCloudResponseTrades); begin AppCore.DoCloudTradingHistory(SymbolBy(Trades.SymbolID1),SymbolBy(Trades.SymbolID2), CloudTradesToTrades(Trades.Trades)); Dequeue; end; procedure TCloudCore.Connect; begin Cancel; DoConnectProc:=procedure begin end; Client.Connect; end; procedure TCloudCore.Disconnect; begin UI.ShowMessage('Disconnected'); Client.Disconnect; end; procedure TCloudCore.Unauthorized; begin UI.ShowMessage('Unauthorized'); Client.Unauthorized; end; procedure TCloudCore.Cancel; begin Queue:=nil; DoBeginProc:=nil; Client.Cancel; end; function TCloudCore.Ready: Boolean; begin Result:=Client.Ready; end; procedure TCloudCore.ExecuteBeginProc; begin if Assigned(DoBeginProc) then DoBeginProc; end; procedure TCloudCore.SetNetwork(const NetworkName: string; jsConfig: TJSONObject); begin {$IFDEF STAGE} if NetworkName='mainnet' then CloudHost:=CLOUD_HOST_MAINNET else CloudHost:=CLOUD_HOST_TESTNET; {$ELSE} CloudHost:=CLOUD_HOST_DEVNET; {$ENDIF} CloudPort:=CLOUD_PORT_DEFAULT; KeepAlive:=False; OfferAccount:=0; ReadConfig(jsConfig); Client.SetEndPoint(CloudHost,CloudPort); SetAuth('','',0); end; procedure TCloudCore.SetAuth(const Email,Password: string; AccountID: Int64); begin Client.Unauthorized; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoRegistrationProc:=procedure begin Client.SendRequestRegistration(Email,Password,AccountID); end; DoLoginProc:=procedure begin Client.SendRequestLogin(Email,Password); end; end; procedure TCloudCore.SetKeepAlive(KeepAlive: Boolean; RecoveryInterval: Cardinal); begin Client.KeepAlive:=KeepAlive or Self.KeepAlive; Client.SetRecoveryInterval(RecoveryInterval); if Client.KeepAlive then SendRequestLogin; end; procedure TCloudCore.SendRequestLogin; begin Enqueue('SendRequestLogin',procedure begin ToLog('Execute login'); Client.Unauthorized; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin UI.WaitCancel; UI.WaitUnlock; Dequeue; end; UI.WaitLock; DoConnection; end); end; procedure TCloudCore.SendRequestBalance(const Symbol: string); begin Enqueue('SendRequestBalance',procedure var Port: string; begin ToLog('Execute request balance '+Symbol); UI.WaitLock; Port:=SymbolToPort(Symbol); DoConnectProc:=DoLoginProc; DoErrorProc:=procedure(const Error: TCloudResponseError) begin if Error.Code='780' then Client.SendRequestCreateAddress(Port) else DoErrorProcDefault(Error); end; DoBeginProc:=procedure begin Client.SendRequestInfo(Port); end; DoCreateAddressProc:=DoBeginProc; DoInfoProc:=procedure(const Info: TCloudResponseInfo) begin UI.WaitCancel; AppCore.DoCloudBalance(Info.Address,Info.Amount,PortToSymbol(Info.Port,Symbol)); UI.WaitUnlock; Dequeue; end; if Port='' then DoExcept('forbidden coin') else DoConnection; end); end; procedure TCloudCore.SendRequestTransfer(const Symbol,Address: string; Amount: Extended); begin Enqueue('SendRequestTransfer',procedure var Port: string; begin ToLog('Execute request transfer '+AmountToStr(Amount)+' '+Symbol+' to '+ Address); UI.WaitLock; Port:=SymbolToPort(Symbol); DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestSendTo(Address,Amount,6,Port); end; DoInfoProc:=procedure(const Info: TCloudResponseInfo) begin UI.WaitCancel; AppCore.DoCloudBalance(Info.Address,Info.Amount,PortToSymbol(Info.Port,Symbol)); UI.WaitUnlock; Dequeue; end; DoSendToProc:=procedure begin Client.SendRequestInfo(Port); end; if Port='' then DoExcept('forbidden coin') else DoConnection; end); end; procedure TCloudCore.SendRequestRatio; begin Enqueue('SendRequestRatio',procedure begin ToLog('Execute request ratio'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestRatio; end; DoConnection; end); end; procedure TCloudCore.SendRequestForging(Owner,TokenID: Int64; const Symbol: string; BuyAmount,PayAmount,Ratio,Commission1,Commission2: Extended); begin Enqueue('SendRequestForging',procedure var Port: string; begin ToLog('Execute request forging TokenID='+TokenID.ToString+' '+AmountToStr(BuyAmount)+' '+ AmountToStr(PayAmount)+' '+Symbol+' to AccountID='+Owner.ToString); UI.WaitLock; Port:=SymbolToPort(Symbol); DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestForging(Owner,TokenID,Port,BuyAmount,PayAmount,Ratio, Commission1,Commission2); end; if Port='' then DoExcept('forbidden coin') else DoConnection; end); end; procedure TCloudCore.SendRequestCreateOffer(Direction: Integer; const Symbol1,Symbol2: string; Amount,Ratio: Extended; EndDate: TDateTime); begin Enqueue('SendRequestCreateOffer',procedure var Coin1,Coin2: Integer; begin ToLog('Execute request create offer '+Symbol1+'-'+Direction.ToString+'->'+Symbol2+' '+ 'Amount='+AmountToStr(Amount)+' Ratio='+AmountToStr(Ratio)); UI.WaitLock; Coin1:=SymbolID(Symbol1,0); Coin2:=SymbolID(Symbol2,0); DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoCreateOfferProc:=procedure begin try AppCore.DoOfferTransfer(Direction,Symbol1,Symbol2,OfferAccount,Amount,Ratio); Client.SendRequestCreateOffer(Direction,Coin1,Coin2,Amount,Ratio,EndDate); except on E: Exception do DoExcept(E.Message); end; end; if OfferAccount=0 then begin DoBeginProc:=procedure begin Client.SendRequestOfferAccount; end; DoOfferAccountProc:=procedure(AccountID: Integer) begin OfferAccount:=AccountID; DoCreateOfferProc; end; end else DoBeginProc:=DoCreateOfferProc; if (Coin1=0) or (Coin2=0) then DoExcept('forbidden coin') else DoConnection; end); end; procedure TCloudCore.SendRequestOffers(const Symbol1,Symbol2: string); begin Enqueue('SendRequestOffers',procedure begin ToLog('Execute request offers list'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestOffers(SymbolID(Symbol1),SymbolID(Symbol2)); end; DoConnection; end); end; procedure TCloudCore.SendRequestKillOffers(const Offers: TArray<Int64>); begin Enqueue('SendRequestKillOffer',procedure begin // ToLog('Execute request kill offer id='+Cloud.Utils.ToString(Offers,', ')); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestKillOffers(Offers); end; DoConnection; end); end; procedure TCloudCore.SendRequestActiveOffer; begin Enqueue('SendRequestActiveOffer',procedure begin ToLog('Execute request active offers list'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestActiveOffers; end; DoConnection; end); end; procedure TCloudCore.SendRequestClosedOffer(BeginDate,EndDate: TDateTime); begin Enqueue('SendRequestClosedOffer',procedure begin ToLog('Execute request closed offers list'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestClosedOffers(BeginDate,EndDate); end; DoConnection; end); end; procedure TCloudCore.SendRequestHistoryOffer(BeginDate,EndDate: TDateTime); begin Enqueue('SendRequestHistoryOffer',procedure begin ToLog('Execute request offers history list'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestHistoryOffers(BeginDate,EndDate); end; DoConnection; end); end; procedure TCloudCore.SendRequestPairsSummary; begin Enqueue('SendRequestPairsSummary',procedure begin ToLog('Execute request pairs summary list'); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestPairsSummary; end; DoConnection; end); end; procedure TCloudCore.SendRequestCandles(const Symbol1,Symbol2: string; BeginDate: TDateTime; IntervalType: Integer); begin Enqueue('SendRequestCandles',procedure begin ToLog('Execute request candles data '+Symbol1+'/'+Symbol2); UI.WaitLock; DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestCandles(SymbolID(Symbol1),SymbolID(Symbol2),BeginDate,IntervalType); end; DoConnection; end); end; procedure TCloudCore.SendRequestSetNotifications(Enabled: Boolean); begin Enqueue('SendRequestSetNotifications',procedure begin ToLog('Execute request set notifications'); DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestSetNotifications(Enabled); end; DoConnection; end); end; procedure TCloudCore.SendRequestTradingHistory(const Symbol1,Symbol2: string; Count: Integer); begin Enqueue('SendRequestTradingHistory',procedure begin ToLog('Execute request trading history'); DoConnectProc:=DoLoginProc; DoErrorProc:=DoErrorProcDefault; DoBeginProc:=procedure begin Client.SendRequestTradingHistory(SymbolID(Symbol1),SymbolID(Symbol2),Count); end; DoConnection; end); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2018 * } { *********************************************************** } unit tfEngines; interface {$I TFL.inc} uses SysUtils, tfTypes, tfOpenSSL, tfWindows, tfExceptions; //type // EOSSLError = class(Exception); procedure LoadLibCrypto(const FolderName: string = ''); function OpenSSLVersion: string; // procedure OSSLResCheck(Res: Integer); implementation procedure LoadLibCrypto(const FolderName: string); var Code: TF_RESULT; begin Code:= TryLoadLibCrypto(FolderName); if Code < 0 then ForgeError(TF_E_LOADERROR, 'OpenSSL Load Error'); end; function OpenSSLVersion: string; begin if Assigned(OpenSSL_version) then begin Result:= string(OpenSSL_version(_SSLEAY_VERSION)); end else ForgeError(TF_E_LOADERROR, 'OpenSSL Load Error'); end; { not used procedure OSSLResCheck(Res: Integer); begin if Res <> 1 then raise EOSSLError.Create('OpenSSL Error'); end; } end.
unit Model.Acareacoes; interface uses Common.ENum, FireDAC.Comp.Client,System.SysUtils, DAO.Conexao, Control.Sistema; type TAcareacoes = class private FSequencia: Integer; FId: String; FData: TDateTime; FNossonumero: String; FEntregador: Integer; FBase: Integer; FDataEntrega: TDateTime; FMotivo: String; FTratativa: String; FApuracao: String; FResultado: String; FExtravio: Double; FMulta: Double; FEnvio: String; FRetorno: String; FObs: String; FFinalizar: Boolean; FExecutor: String; FManutencao: TDateTime; FDataRetorno: TDateTime; FConsumidor: String; FUnidade: String; FProduto: String; FBairro: String; FDocumento: String; FCEP: String; FRemetente: String; FIdentificacao: String; FRecebedor: String; FCidade: String; FEndereco: String; FConexao : TConexao; FAcao: TAcao; FNumero: String; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public property Sequencia: Integer read FSequencia write FSequencia; property Id: String read FId write FId; property Data: TDateTime read FData write FData; property Nossonumero: String read FNossonumero write FNossonumero; property Entregador: Integer read FEntregador write FEntregador; property Base: Integer read FBase write FBase; property DataEntrega: TDateTime read FDataEntrega write FDataEntrega; property Motivo: String read FMotivo write FMotivo; property Tratativa: String read FTratativa write FTratativa; property Apuracao: String read FApuracao write FApuracao; property Resultado: String read FResultado write FResultado; property Extravio: Double read FExtravio write FExtravio; property Multa: Double read FMulta write FMulta; property Envio: String read FEnvio write FEnvio; property Retorno: String read FRetorno write FRetorno; property Obs: String read FObs write FObs; property Finalizar: Boolean read FFinalizar write FFinalizar; property Executor: String read FExecutor write FExecutor; property Manutencao: TDateTime read FManutencao write FManutencao; property DataRetorno: TDateTime read FDataRetorno write FDataRetorno; property Unidade: String read FUnidade write FUnidade; property Consumidor: String read FConsumidor write FConsumidor; property Endereco: String read FEndereco write FEndereco; property Numero: String read FNumero write FNumero; property Bairro: String read FBairro write FBairro; property Cidade: String read FCidade write FCidade; property CEP: String read FCEP write FCEP; property Remetente: String read FRemetente write FRemetente; property Produto: String read FProduto write FProduto; property Recebedor: String read FRecebedor write FRecebedor; property Identificacao: String read FIdentificacao write FIdentificacao; property Documento: String read FDocumento write FDocumento; property Acao: TAcao read FAcao write FAcao; constructor Create(); function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function GetID(): Integer; function AcareacaoExiste(): Boolean; end; const TABLENAME = 'tbacareacoes'; implementation { TAcareacoes } function TAcareacoes.AcareacaoExiste: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME + ' where ID_ACAREACAO = :ID_ACAREACAO and NUM_NOSSONUMERO = :NUM_NOSSONUMERO'); FDQuery.ParamByName('ID_ACAREACAO').AsString := Id; FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := Nossonumero; FDQuery.Open(); if FDQuery.IsEmpty then Exit; Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TAcareacoes.Alterar(): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET ' + 'ID_ACAREACAO = :ID_ACAREACAO, DAT_ACAREACAO = :DAT_ACAREACAO, ' + 'NUM_NOSSONUMERO = :NUM_NOSSONUMERO, COD_ENTREGADOR = :COD_ENTREGADOR, COD_BASE = :COD_BASE, ' + 'DAT_ENTREGA = :DAT_ENTREGA, DES_MOTIVO = :DES_MOTIVO, DES_TRATATIVA = :DES_TRATATIVA, ' + 'DES_APURACAO = :DES_APURACAO, DES_RESULTADO = :DES_RESULTADO, VAL_EXTRAVIO = :VAL_EXTRAVIO, ' + 'VAL_MULTA = :VAL_MULTA, DES_ENVIO_CORRESPONDENCIA = :DES_ENVIO_CORRESPONDENCIA, ' + 'DES_RETORNO_CORRESPONDENCIA = :DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES = :DES_OBSERVACOES, ' + 'DOM_FINALIZAR = :DOM_FINALIZAR, DES_EXECUTOR = :DES_EXECUTOR, DAT_MANUTENCAO = :DAT_MANUTENCAO, ' + 'DAT_RETORNO = :DAT_RETORNO, DES_UNIDADE = :DES_UNIDADE, NOM_CONSUMIDOR = :NOM_CONSUMIDOR, ' + 'DES_ENDERECO = :DES_ENDERECO, NUM_ENDERECO = :NUM_ENDERECO, DES_BAIRRO = :DES_BAIRRO, ' + 'DES_CIDADE = :DES_CIDADE, NUM_CEP = :NUM_CEP, ' + 'DES_REMETENTE = :DES_REMETENTE, DES_PRODUTO = :DES_PRODUTO, NOM_RECEBEDOR = :NOM_RECEBEDOR, ' + 'DES_IDENTIFICACAO = :DES_IDENTIFICACAO, DES_DOCUMENTO = :DES_DOCUMENTO ' + 'WHERE SEQ_ACAREACAO = :SEQ_ACAREACAO;',[Id, Data,Nossonumero, Entregador, Base, DataEntrega, Motivo, Tratativa, Apuracao, Resultado, Extravio, Multa, Envio, Retorno, Obs, Finalizar, Executor, Manutencao, DataRetorno, Unidade, Consumidor, Endereco, Numero, Bairro, Cidade, CEP, Remetente, Produto, Recebedor, Identificacao, Documento, Sequencia]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end;end; constructor TAcareacoes.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TAcareacoes.Excluir(): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where SEQ_ACAREACAO = :SEQ_ACAREACAO', [Sequencia]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TAcareacoes.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(SEQ_ACAREACAO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcareacoes.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Inserir(); Common.ENum.tacAlterar: Result := Alterar(); Common.ENum.tacExcluir: Result := Excluir(); end; end; function TAcareacoes.Inserir(): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Self.Sequencia := GetID(); FDQuery.ExecSQL('insert into ' + TABLENAME + '(SEQ_ACAREACAO, ID_ACAREACAO, DAT_ACAREACAO, NUM_NOSSONUMERO, ' + 'COD_ENTREGADOR, COD_BASE, DAT_ENTREGA, DES_MOTIVO, DES_TRATATIVA, DES_APURACAO, DES_RESULTADO, ' + 'VAL_EXTRAVIO, VAL_MULTA, DES_ENVIO_CORRESPONDENCIA, DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES, ' + 'DOM_FINALIZAR, DES_EXECUTOR, DAT_MANUTENCAO, DAT_RETORNO, DES_UNIDADE, NOM_CONSUMIDOR, DES_ENDERECO, ' + 'NUM_ENDERECO, DES_BAIRRO, DES_CIDADE, NUM_CEP, DES_REMETENTE, DES_PRODUTO, NOM_RECEBEDOR, DES_IDENTIFICACAO, ' + 'DES_DOCUMENTO) ' + 'VALUES ' + '(:SEQ_ACAREACAO, :ID_ACAREACAO, :DAT_ACAREACAO, :NUM_NOSSONUMERO, ' + ':COD_ENTREGADOR, :COD_BASE, :DAT_ENTREGA, :DES_MOTIVO, :DES_TRATATIVA, :DES_APURACAO, :DES_RESULTADO, ' + ':VAL_EXTRAVIO, :VAL_MULTA, :DES_ENVIO_CORRESPONDENCIA, :DES_RETORNO_CORRESPONDENCIA, :DES_OBSERVACOES, ' + ':DOM_FINALIZAR, :DES_EXECUTOR, :DAT_MANUTENCAO, :DAT_RETORNO, :DES_UNIDADE, :NOM_CONSUMIDOR, :DES_ENDERECO, ' + ':NUM_ENDERECO, :DES_BAIRRO, :DES_CIDADE, :NUM_CEP, :DES_REMETENTE, :DES_PRODUTO, :NOM_RECEBEDOR, :DES_IDENTIFICACAO, ' + ':DES_DOCUMENTO);', [Sequencia, Id, Data, Nossonumero, Entregador, Base, DataEntrega, Motivo, Tratativa, Apuracao, Resultado, Extravio, Multa, Envio, Retorno, Obs, Finalizar, Executor, Manutencao, DataRetorno, Unidade, Consumidor, Endereco, Numero, Bairro, Cidade, CEP, Remetente, Produto, Recebedor, Identificacao, Documento]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcareacoes.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('WHERE SEQ_ACAREACAO = :SEQ_ACAREACAO'); FDQuery.ParamByName('SEQ_ACAREACAO').AsInteger := aParam[1]; end; if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_ACAREACAO = :ID_ACAREACAO'); FDQuery.ParamByName('ID_ACAREACAO').AsString := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('WHERE DAT_ACAREACAO = :DAT_ACAREACAO'); FDQuery.ParamByName('WHERE DAT_ACAREACAO').AsDate := aParam[1]; end; if aParam[0] = 'NN' then begin FDQuery.SQL.Add('WHERE NUM_NOSSONUMERO = :NUM_NOSSONUMERO'); FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open; Result := FDQuery; end; end.
PROGRAM SLISTDEMO; TYPE Nodeptr = ^Listnode; Listnode = RECORD data : Integer; next : Nodeptr END; VAR Slhead : Nodeptr; VAR Nd : Nodeptr; VAR ind : Integer; FUNCTION MkListnode(d : Integer) : Nodeptr; VAR np : Nodeptr; BEGIN New(np); IF NOT Assigned(np) THEN BEGIN np := NIL; Writeln('Memory Allocation Error!') END ELSE WITH np^ DO BEGIN data := d; next := NIL END; MkListnode := np END; { PROCEDURE AddSlist(node : Nodeptr; VAR head : Nodeptr); VAR Visitor : Nodeptr; BEGIN // Visitor := head; // WHILE Visitor <> NIL DO // BEGIN // Visitor := Visitor^.next // END; // Visitor := node IF head = NIL THEN head := node ELSE BEGIN Visitor := head; WHILE Visitor^.next <> NIL DO BEGIN Visitor := Visitor^.next END; Visitor^.next := node END END; } PROCEDURE AddSlist(node : Nodeptr; VAR head : Nodeptr); VAR Visitor : ^Nodeptr; (* VAR aux : Nodeptr; *) BEGIN Visitor := @head; WHILE NOT (Visitor^ = NIL) DO BEGIN Visitor := @((Visitor^)^.next); END; Visitor^ := node END; BEGIN Slhead := NIL; ind := 1; WHILE ind < 100 DO BEGIN Nd := MkListnode(ind); AddSlist(Nd, Slhead); ind := ind + 4 END; Nd := Slhead; ind := 0; WHILE NOT (Nd = NIL) DO BEGIN Writeln('data field of node ', ind, ': ', Nd^.data); Nd := Nd^.next; Inc(ind) END; END.
unit ManagementSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, InternationalizerComponent; const tidCurrBlock = 'CurrBlock'; tidSecurityId = 'SecurityId'; tidUpgradeLevel = 'UpgradeLevel'; tidMaxUpgrade = 'MaxUpgrade'; tidUpgrading = 'Upgrading'; type TManagementHandler = class; TManagementSheetViewer = class(TVisualControl) Shape1: TShape; Label6: TLabel; Label8: TLabel; cbAcceptSettings: TCheckBox; Shape2: TShape; Label1: TLabel; cbForTownOnly: TCheckBox; cbForCompanyOnly: TCheckBox; btnClone: TFramedButton; InternationalizerComponent1: TInternationalizerComponent; fbUpgrade: TFramedButton; Shape3: TShape; Label2: TLabel; Label3: TLabel; xfer_UpgradeLevel: TLabel; procedure btnCloneClick(Sender: TObject); procedure cbAcceptSettingsClick(Sender: TObject); procedure fbUpgradeClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TManagementHandler; end; TManagementHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TManagementSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; fAcceptSettings : boolean; fUpgrading : boolean; private function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure SetAcceptSettings(accept : boolean); procedure CloneSettings(inTown, inComp : boolean); procedure UpgradeFacility(action : integer); procedure threadedUpgradeFacility(const parms : array of const); end; var ManagementSheetViewer: TManagementSheetViewer; function ManagementHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, Protocol, Literals; {$R *.DFM} // TManagementHandler function TManagementHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TManagementSheetViewer.Create(Owner); fControl.fHandler := self; result := fControl; end; function TManagementHandler.GetControl : TControl; begin result := fControl; end; procedure TManagementHandler.RenderProperties(Properties : TStringList); var aux : string; maxupgr : integer; upgrade : integer; canUpgrd : boolean; begin fControl.cbAcceptSettings.Enabled := fOwnsFacility; fControl.cbAcceptSettings.Checked := fAcceptSettings; fControl.cbForTownOnly.Enabled := fOwnsFacility; fControl.cbForCompanyOnly.Enabled := fOwnsFacility; fControl.btnClone.Enabled := fOwnsFacility; aux := Properties.Values[tidMaxUpgrade]; if aux <> '' then maxupgr := StrToInt(aux) else maxupgr := 0; aux := Properties.Values[tidUpgradeLevel]; if aux <> '' then upgrade := StrToInt(aux) else upgrade := 0; aux := Properties.Values[tidUpgrading]; fUpgrading := aux <> '0'; if not fUpgrading then fControl.fbUpgrade.Text := Literals.GetLiteral('Literal_Upgrade1') else fControl.fbUpgrade.Text := Literals.GetLiteral('Literal_Upgrade2'); canUpgrd := fOwnsFacility and (upgrade < maxupgr); fControl.xfer_UpgradeLevel.Caption := Properties.Values[tidUpgradeLevel]; fControl.fbUpgrade.Enabled := canUpgrd; fControl.xfer_UpgradeLevel.Visible := fOwnsFacility and (maxupgr > 1); fControl.fbUpgrade.Visible := fOwnsFacility and (maxupgr > 1); fControl.Shape3.Visible := fOwnsFacility and (maxupgr > 1); fControl.Label2.Visible := fOwnsFacility and (maxupgr > 1); fControl.Label3.Visible := fOwnsFacility and (maxupgr > 1); end; procedure TManagementHandler.SetFocus; begin if not fLoaded then begin inherited; fOwnsFacility := false; fControl.cbAcceptSettings.Checked := false; fControl.btnClone.Enabled := false; Threads.Fork(threadedGetProperties, priHigher, [fLastUpdate]); end; end; procedure TManagementHandler.Clear; begin inherited; fControl.cbAcceptSettings.Enabled := false; fControl.cbForTownOnly.Enabled := false; fControl.cbForCompanyOnly.Enabled := false; fControl.btnClone.Enabled := false; fControl.xfer_UpgradeLevel.Visible := false; fControl.fbUpgrade.Visible := false; fControl.Shape3.Visible := false; fControl.Label2.Visible := false; fControl.Label3.Visible := false; end; procedure TManagementHandler.threadedGetProperties(const parms : array of const); var Names : TStringList; Update : integer; Prop : TStringList; Proxy : OleVariant; aux : string; begin try Update := parms[0].vInteger; Names := TStringList.Create; Names.Add(tidCurrBlock); Names.Add(tidSecurityId); Names.Add(tidUpgradeLevel); Names.Add(tidMaxUpgrade); Names.Add(tidUpgrading); try if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; finally Names.Free; end; if Update = fLastUpdate then begin aux := Prop.Values[tidCurrBlock]; if aux <> '' then fCurrBlock := StrToInt(aux) else fCurrBlock := 0; fOwnsFacility := GrantAccess(GetContainer.GetClientView.getSecurityId, Prop.Values[tidSecurityId]); Proxy := GetContainer.GetMSProxy; if (Update = fLastUpdate) and not VarIsEmpty(Proxy) then begin try Proxy.BindTo(fCurrBlock); fAcceptSettings := Proxy.RDOAcceptCloning; except fAcceptSettings := false; end; if Update = fLastUpdate then Join(threadedRenderProperties, [Prop, Update]); end; end else Prop.Free; except end; end; procedure TManagementHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TManagementHandler.SetAcceptSettings(accept : boolean); var Proxy : OleVariant; begin if fOwnsFacility and (fCurrBlock <> 0) then begin Proxy := GetContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(fCurrBlock); Proxy.RDOAcceptCloning := accept; end; end; end; procedure TManagementHandler.CloneSettings(inTown, inComp : boolean); begin if fOwnsFacility and (fCurrBlock <> 0) then GetContainer.GetClientView.CloneFacility(GetContainer.getXPos, GetContainer.getYPos, inTown, inComp); end; procedure TManagementHandler.UpgradeFacility(action : integer); var fac : integer; begin fac := GetContainer.GetObjectId; if fOwnsFacility and (fac <> 0) then Threads.Fork(threadedUpgradeFacility, priHigher, [fac, action]); end; procedure TManagementHandler.threadedUpgradeFacility(const parms : array of const); var Proxy : OleVariant; facility : integer; action : integer; begin facility := parms[0].VInteger; action := parms[1].VInteger; if fOwnsFacility and (facility <> 0) then begin Proxy := GetContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(facility); if action = 0 then Proxy.RDOStartUpgrade else Proxy.RDOStopUpgrade; end; end; end; // TWorkforceSheetViewer procedure TManagementSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TManagementSheetViewer.btnCloneClick(Sender: TObject); begin fHandler.CloneSettings(cbForTownOnly.Checked, cbForCompanyOnly.Checked); end; procedure TManagementSheetViewer.cbAcceptSettingsClick(Sender: TObject); begin fHandler.SetAcceptSettings(cbAcceptSettings.Checked); end; procedure TManagementSheetViewer.fbUpgradeClick(Sender: TObject); begin if fHandler.fOwnsFacility then begin if not fHandler.fUpgrading then begin fHandler.UpgradeFacility(0); fbUpgrade.Text := Literals.GetLiteral('Literal_Upgrade2'); end else begin fHandler.UpgradeFacility(1); fbUpgrade.Text := Literals.GetLiteral('Literal_Upgrade1'); end; fHandler.fUpgrading := not fHandler.fUpgrading; end; end; // ManagementHandlerCreator function ManagementHandlerCreator : IPropertySheetHandler; begin result := TManagementHandler.Create; end; initialization SheetHandlerRegistry.RegisterSheetHandler('facManagement', ManagementHandlerCreator); end.