text
stringlengths
14
6.51M
unit UDeleteHandler; interface uses UPageSuper, UxlClasses; type TDeleteHandler = class private FRecycleBin: TPageSuper; public procedure SetRecycleBin (value: TPageSuper); procedure Remove (value, parent: TPageSuper); function CanRemove (value, parent: TPageSuper; var b_delete: boolean): boolean; // b_delete 用于决定菜单条目是“删除”还是“移除” end; function DeleteHandler(): TDeleteHandler; implementation uses UGlobalObj, UOptionManager, UPageStore, UPageFactory, UTypeDef; var FDeleteHandler: TDeleteHandler; function DeleteHandler(): TDeleteHandler; begin if FDeleteHandler = nil then FDeleteHandler := TDeleteHandler.Create; result := FDeleteHandler; end; procedure TDeleteHandler.SetRecycleBin (value: TPageSuper); begin FRecycleBin := value; end; procedure TDeleteHandler.Remove (value, parent: TPageSuper); var b_delete: boolean; i, n, id: integer; begin if not CanRemove (value, parent, b_delete) then exit; if parent.Childs <> nil then parent.Childs.RemoveChild (value.id) else PageCenter.EventNotify (pctRemoveChild, parent.id, value.id); if b_delete then begin if (FRecycleBin = nil) or (value.owner = FRecycleBin) or (not FRecycleBin.CanAddChild (value.pagetype)) then value.Delete else begin if parent <> value.owner then // 针对searchpage等无真正意义上子条目的页面 value.owner.childs.RemoveChild (value.id); PageStore.GetFirstPageId (ptFavorite, id); PageStore[id].Childs.RemoveChild (value.id); value.Owner := FRecycleBin; FRecycleBin.Childs.AddChild (value.id); n := FRecycleBin.Childs.Count; if (OptionMan.Options.RecyclerLimit >= 0) and (n > OptionMan.Options.RecyclerLimit) then for i := n - OptionMan.Options.RecyclerLimit -1 downto 0 do begin id := FRecycleBin.Childs.ChildId (i); FRecycleBin.Childs.RemoveChild (id); PageStore[id].delete; end; end; end; end; function TDeleteHandler.CanRemove (value, parent: TPageSuper; var b_delete: boolean): boolean; begin b_delete := false; if parent.isvirtualcontainer then // 收藏夹中的虚拟链接任何情况下都可删除 result := true else begin result := false; if value = nil then exit; if not value.CanDelete then exit; result := true; b_delete := not value.SingleInstance; end; end; //------------ initialization finalization FDeleteHandler.free; end. // FRemoveOnly: array of TPageSuper; // FNoRemovables: array of TPageSuper; // procedure AddRemoveOnly (value: TPageSuper); // 只移除不删除 // procedure AddNoRemovable (value: TPageSuper); // 不能移除 //procedure TDeleteHandler.AddRemoveOnly (value: TPageSuper); //var n: integer; //begin // n := Length (FRemoveOnly); // SetLength (FRemoveOnly, n + 1); // FRemoveOnly[n] := value; //end; // //procedure TDeleteHandler.AddNoRemovable (value: TPageSuper); //var n: integer; //begin // n := Length (FNoRemovables); // SetLength (FNoRemovables, n + 1); // FNoRemovables[n] := value; //end;
unit Server.Models.Cadastros.MotivosPausa; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('MOTIVOS_PAUSA','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TMotivosPausa = class(TTabelaBase) private fTEMPO_MAX_SEG: Integer; fDESCRICAO: String; function Getid: Integer; procedure Setid(const Value: Integer); procedure GetDESCRICAO(const Value: String); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('DESCRICAO', ftString, 50)] property DESCRICAO: String read fDESCRICAO write GetDESCRICAO; [Column('TEMPO_MAX_SEG', ftInteger)] property TEMPO_MAX_SEG: Integer read fTEMPO_MAX_SEG write fTEMPO_MAX_SEG; end; implementation { TMotivosPausa } uses Infotec.Utils; constructor TMotivosPausa.create; begin end; destructor TMotivosPausa.destroy; begin inherited; end; procedure TMotivosPausa.GetDESCRICAO(const Value: String); begin fDESCRICAO := TInfotecUtils.RemoverEspasDuplas(Value); end; function TMotivosPausa.Getid: Integer; begin Result := fid; end; procedure TMotivosPausa.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TMotivosPausa); end.
// "WinCrt Unit", Copyright (c) 2003-2010 by Stefan Berinde // Version: as WinGraph unit // // Source code: Free Pascal 2.4 (http://www.freepascal.org) & // Delphi 7 // // Unit dependences: // windows (standard) // messages (standard, only for Delphi) // wingraph // unit wincrt; interface {caret format: block or underline} var CaretBlock: boolean = true; {caret blink rate in tenths of a second} var BlinkRate: word = 2; {keyboard exported routines} procedure Delay(ms:word); function KeyPressed: boolean; procedure ReadBuf(var buf:shortstring; maxchar:byte); function ReadKey: char; procedure Sound(hz,dur:word); procedure WriteBuf(buf:shortstring); implementation uses windows{$IFNDEF FPC},messages{$ENDIF},wingraph; const KeyBufSize = 32; var protect_keyboard : TRTLCriticalSection; nr_readkey,nr_inputkey : longint; keyBuf : array[1..KeyBufSize] of char; old_TextSettings : TextSettingsType; textX,textY,textW,textH, maxX,maxY : smallint; {internal routines} procedure InitKeyBuf; begin nr_readkey:=1; nr_inputkey:=1; end; procedure IncKeyCyclic(var nr: longint); begin Inc(nr); if (nr > KeyBufSize) then nr:=1; end; procedure AddKey(c:char); begin EnterCriticalSection(protect_keyboard); KeyBuf[nr_inputkey]:=c; IncKeyCyclic(nr_inputkey); if (nr_readkey = nr_inputkey) then begin if (KeyBuf[nr_readkey] = #0) then IncKeyCyclic(nr_readkey); IncKeyCyclic(nr_readkey); end; LeaveCriticalSection(protect_keyboard); end; procedure AddExtKey(c:char); begin AddKey(#0); AddKey(c); end; procedure TranslateKeys(code:WPARAM); var shift_key,ctrl_key,alt_key: boolean; begin shift_key:=(GetKeyState(VK_SHIFT) < 0); ctrl_key:=(GetKeyState(VK_CONTROL) < 0); alt_key:=(GetKeyState(VK_MENU) < 0); case code of VK_SPACE: if alt_key then AddExtKey(#11); VK_TAB: if ctrl_key then AddKey(#30); VK_BACK: if alt_key then AddExtKey(#14); VK_RETURN: if alt_key then AddExtKey(#166); VK_APPS: AddExtKey(#151); VK_INSERT: if ctrl_key then AddExtKey(#146) else if alt_key then AddExtKey(#162) else AddExtKey(#82); VK_DELETE: if ctrl_key then AddExtKey(#147) else if alt_key then AddExtKey(#163) else AddExtKey(#83); VK_HOME: if ctrl_key then AddExtKey(#119) else if alt_key then AddExtKey(#164) else AddExtKey(#71); VK_END: if ctrl_key then AddExtKey(#117) else if alt_key then AddExtKey(#165) else AddExtKey(#79); VK_NEXT: if ctrl_key then AddExtKey(#118) else if alt_key then AddExtKey(#161) else AddExtKey(#81); VK_PRIOR: if ctrl_key then AddExtKey(#132) else if alt_key then AddExtKey(#153) else AddExtKey(#73); VK_UP: if ctrl_key then AddExtKey(#141) else if alt_key then AddExtKey(#152) else AddExtKey(#72); VK_DOWN: if ctrl_key then AddExtKey(#145) else if alt_key then AddExtKey(#160) else AddExtKey(#80); VK_LEFT: if ctrl_key then AddExtKey(#115) else if alt_key then AddExtKey(#155) else AddExtKey(#75); VK_RIGHT: if ctrl_key then AddExtKey(#116) else if alt_key then AddExtKey(#157) else AddExtKey(#77); VK_F1..VK_F10: if shift_key then AddExtKey(chr(code-28)) else if ctrl_key then AddExtKey(chr(code-18)) else if alt_key then AddExtKey(chr(code-8)) else AddExtKey(chr(code-53)); VK_F11,VK_F12: if shift_key then AddExtKey(chr(code+13)) else if ctrl_key then AddExtKey(chr(code+15)) else if alt_key then AddExtKey(chr(code+17)) else AddExtKey(chr(code+11)); VK_PAUSE: if alt_key then AddExtKey(#169) else if not(ctrl_key) then AddExtKey(#12); VK_CLEAR: if ctrl_key then AddExtKey(#143) else AddExtKey(#76); //this is numpad 5 + numlock off VK_DIVIDE: if ctrl_key then AddExtKey(#148) else if alt_key then AddExtKey(#69); VK_MULTIPLY: if ctrl_key then AddExtKey(#149) else if alt_key then AddExtKey(#70); VK_SUBTRACT: if ctrl_key then AddExtKey(#142) else if alt_key then AddExtKey(#74); VK_ADD: if ctrl_key then AddExtKey(#144) else if alt_key then AddExtKey(#78); VK_DECIMAL: if ctrl_key then AddExtKey(#150) else if alt_key then AddExtKey(#114); else if ctrl_key then case code of ord('0') : AddExtKey(#10); ord('1')..ord('9'): AddExtKey(chr(code-48)); end; if alt_key then case code of ord('A'): AddExtKey(#30); ord('B'): AddExtKey(#48); ord('C'): AddExtKey(#46); ord('D'): AddExtKey(#32); ord('E'): AddExtKey(#18); ord('F'): AddExtKey(#33); ord('G'): AddExtKey(#34); ord('H'): AddExtKey(#35); ord('I'): AddExtKey(#23); ord('J'): AddExtKey(#36); ord('K'): AddExtKey(#37); ord('L'): AddExtKey(#38); ord('M'): AddExtKey(#50); ord('N'): AddExtKey(#49); ord('O'): AddExtKey(#24); ord('P'): AddExtKey(#25); ord('Q'): AddExtKey(#16); ord('R'): AddExtKey(#19); ord('S'): AddExtKey(#31); ord('T'): AddExtKey(#20); ord('U'): AddExtKey(#22); ord('V'): AddExtKey(#47); ord('W'): AddExtKey(#17); ord('X'): AddExtKey(#45); ord('Y'): AddExtKey(#21); ord('Z'): AddExtKey(#44); ord('0') : AddExtKey(#129); ord('1')..ord('9'): AddExtKey(chr(code+71)); end; end; end; function WinCrtProc(grHandle:HWND; mess:UINT; wParam:WPARAM; lParam:LPARAM): LRESULT; stdcall; begin WinCrtProc:=0; case mess of WM_CREATE: begin InitializeCriticalSection(protect_keyboard); InitKeyBuf; end; WM_CHAR: AddKey(chr(wparam)); WM_KEYDOWN: if (wParam <> VK_SHIFT) and (wParam <> VK_CONTROL) then TranslateKeys(wParam); WM_SYSKEYDOWN: if (wParam <> VK_MENU) then TranslateKeys(wParam); WM_CLOSE: AddExtKey(#107); WM_DESTROY: DeleteCriticalSection(protect_keyboard); end; end; procedure CheckNewLine; var size : longword; screen: pointer; begin if (textX+textW > maxX) then begin textX:=0; Inc(textY,textH); end; if (textY+textH > maxY) then //scroll entire text upwards begin repeat Dec(textY,textH); until (textY+textH <= maxY); size:=ImageSize(0,textH,maxX,maxY); GetMem(screen,size); GetImage(0,textH,maxX,maxY,screen^); ClearViewPort; PutImage(0,0,screen^,CopyPut); FreeMem(screen); end; end; procedure DrawCaret(nr:longint); begin case nr of 0: SetFillStyle(SolidFill,GetBkColor); 1: SetFillStyle(SolidFill,GetColor); end; if CaretBlock or (nr = 0) then Bar(textX,textY,textX+textW,textY+textH) else Bar(textX,textY+textH-1,textX+textW,textY+textH); end; procedure TextSettings; var viewport: ViewPortType; begin with old_TextSettings do begin SetTextStyle(DefaultFont or (font div $10) shl 4,0,charsize); //keep font format SetTextJustify(LeftText,TopText); end; textX:=GetX; textY:=GetY; textW:=TextWidth('W'); textH:=TextHeight('H'); GetViewSettings(viewport); with viewport do begin maxX:=x2-x1; maxY:=y2-y1; end; end; {keyboard routines} procedure Delay(ms:word); begin Sleep(ms); end; function KeyPressed: boolean; begin KeyPressed:=(nr_readkey <> nr_inputkey); end; procedure ReadBuf(var buf:shortstring; maxchar:byte); var old_FillSettings : FillSettingsType; nrpass,nrchar,nrcaret: longint; ch : char; begin if GraphEnabled then begin GetTextSettings(old_TextSettings); GetFillSettings(old_FillSettings); TextSettings; CheckNewLine; nrpass:=0; nrcaret:=0; nrchar:=0; ch:=#0; if (maxchar <= 0) then maxchar:=255; repeat if (nrpass = 0) then begin nrcaret:=1-nrcaret; DrawCaret(nrcaret); nrpass:=10*BlinkRate; end else Dec(nrpass); if KeyPressed then begin ch:=ReadKey; case ch of #32..#126: begin if (nrcaret = 1) then begin DrawCaret(0); nrcaret:=0; end; Inc(nrchar); buf[nrchar]:=ch; OutTextXY(textX,textY,ch); Inc(textX,textW); CheckNewLine; nrpass:=0; end; #8: if (nrchar > 0) and (textX > 0) then begin if (nrcaret = 1) then begin DrawCaret(0); nrcaret:=0; end; Dec(nrchar); Dec(textX,textW); nrpass:=0; end; #0: ReadKey; end; end; Sleep(10); until (ch = #13) or (nrchar = maxchar) or CloseGraphRequest; if (nrcaret = 1) then DrawCaret(0); buf[0]:=Chr(nrchar); MoveTo(0,textY+textH); with old_TextSettings do begin SetTextStyle(font,direction,charsize); SetTextJustify(horiz,vert); end; with old_FillSettings do SetFillStyle(pattern,color); end; end; function ReadKey: char; begin if GraphEnabled then begin while (nr_readkey = nr_inputkey) do Sleep(10); EnterCriticalSection(protect_keyboard); ReadKey:=KeyBuf[nr_readkey]; IncKeyCyclic(nr_readkey); LeaveCriticalSection(protect_keyboard); end else ReadKey:=#0; end; procedure Sound(hz,dur:word); begin Beep(hz,dur); end; procedure WriteBuf(buf:shortstring); var old_FillSettings: FillSettingsType; nrchar : longint; ch : char; begin if GraphEnabled then begin GetTextSettings(old_TextSettings); GetFillSettings(old_FillSettings); TextSettings; CheckNewLine; for nrchar:=1 to Length(buf) do begin ch:=buf[nrchar]; case ch of #32..#126: begin DrawCaret(0); OutTextXY(textX,textY,ch); Inc(textX,textW); CheckNewLine; end; #13: begin textX:=maxX; CheckNewLine; end; end; end; MoveTo(textX,textY); with old_TextSettings do begin SetTextStyle(font,direction,charsize); SetTextJustify(horiz,vert); end; with old_FillSettings do SetFillStyle(pattern,color); end; end; initialization KeyboardHook:=@WinCrtProc; end.
unit model.Usuario; interface uses UConstantes, app.Funcoes, model.Loja, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants; type TUsuario = class(TObject) strict private aID : TGUID; aNome , aEmail , aSenha , aCpf , aCelular , aTokenID : String; aAtivo : Boolean; aEmpresa : TLoja; procedure SetNome(Value : String); procedure SetEmail(Value : String); procedure SetSenha(Value : String); procedure SetCpf(Value : String); procedure SetCelular(Value : String); procedure SetTokenID(Value : String); constructor Create(); destructor Destroy(); override; class var aInstance : TUsuario; private FID: TGUID; procedure SetID(const Value: TGUID); public property ID : TGUID read FID write SetID; property Nome : String read aNome write SetNome; property Email : String read aEmail write SetEmail; property Senha : String read aSenha write SetSenha; property Cpf : String read aCpf write SetCpf; property Celular : String read aCelular write SetCelular; property TokenID : String read aTokenID write SetTokenID; property Ativo : Boolean read aAtivo write aAtivo; property Empresa : TLoja read aEmpresa write aEmpresa; procedure NewID; function ToString : String; override; class function GetInstance : TUsuario; end; implementation { TUsuario } destructor TUsuario.Destroy; begin aEmpresa.DisposeOf; inherited Destroy; end; class function TUsuario.GetInstance: TUsuario; begin if not Assigned(aInstance) then aInstance := TUsuario.Create(); Result := aInstance; end; procedure TUsuario.NewID; var aGuid : TGUID; begin CreateGUID(aGuid); aId := aGuid; end; constructor TUsuario.Create; begin inherited Create; aID := GUID_NULL; aNome := EmptyStr; aEmail := EmptyStr; aSenha := EmptyStr; aCpf := EmptyStr; aCelular := EmptyStr; aTokenID := EmptyStr; aAtivo := False; aEmpresa := TLoja.Create; end; procedure TUsuario.SetCelular(Value: String); begin aCelular := Trim(Value); end; procedure TUsuario.SetCpf(Value: String); var aStr : String; begin aStr := SomenteNumero(AnsiLowerCase(Trim(Value))); if StrIsCPF(aStr) then aCpf := FormatarTexto('999.999.999-99;0', aStr) else aCpf := EmptyStr; end; procedure TUsuario.SetEmail(Value: String); begin aEmail := AnsiLowerCase(Trim(Value)); end; procedure TUsuario.SetID(const Value: TGUID); begin FID := Value; end; procedure TUsuario.SetNome(Value: String); begin aNome := Trim(Value); end; procedure TUsuario.SetSenha(Value: String); begin aSenha := AnsiLowerCase(Trim(Value)); end; procedure TUsuario.SetTokenID(Value: String); begin aTokenID := Trim(Value); end; function TUsuario.ToString: String; begin Result := aNome + ' <' + aEmail + '>'; end; end.
unit Spider; interface type HCkTask = Pointer; HCkSpider = Pointer; HCkString = Pointer; function CkSpider_Create: HCkSpider; stdcall; procedure CkSpider_Dispose(handle: HCkSpider); stdcall; function CkSpider_getAbortCurrent(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putAbortCurrent(objHandle: HCkSpider; newPropVal: wordbool); stdcall; function CkSpider_getAvoidHttps(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putAvoidHttps(objHandle: HCkSpider; newPropVal: wordbool); stdcall; procedure CkSpider_getCacheDir(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putCacheDir(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__cacheDir(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getChopAtQuery(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putChopAtQuery(objHandle: HCkSpider; newPropVal: wordbool); stdcall; function CkSpider_getConnectTimeout(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putConnectTimeout(objHandle: HCkSpider; newPropVal: Integer); stdcall; procedure CkSpider_getDebugLogFilePath(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putDebugLogFilePath(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__debugLogFilePath(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getDomain(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__domain(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getFetchFromCache(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putFetchFromCache(objHandle: HCkSpider; newPropVal: wordbool); stdcall; function CkSpider_getHeartbeatMs(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putHeartbeatMs(objHandle: HCkSpider; newPropVal: Integer); stdcall; procedure CkSpider_getLastErrorHtml(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastErrorHtml(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastErrorText(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastErrorText(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastErrorXml(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastErrorXml(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getLastFromCache(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_getLastHtml(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastHtml(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastHtmlDescription(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastHtmlDescription(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastHtmlKeywords(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastHtmlKeywords(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastHtmlTitle(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastHtmlTitle(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getLastMethodSuccess(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putLastMethodSuccess(objHandle: HCkSpider; newPropVal: wordbool); stdcall; procedure CkSpider_getLastModDateStr(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastModDateStr(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getLastUrl(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__lastUrl(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getMaxResponseSize(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putMaxResponseSize(objHandle: HCkSpider; newPropVal: Integer); stdcall; function CkSpider_getMaxUrlLen(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putMaxUrlLen(objHandle: HCkSpider; newPropVal: Integer); stdcall; function CkSpider_getNumAvoidPatterns(objHandle: HCkSpider): Integer; stdcall; function CkSpider_getNumFailed(objHandle: HCkSpider): Integer; stdcall; function CkSpider_getNumOutboundLinks(objHandle: HCkSpider): Integer; stdcall; function CkSpider_getNumSpidered(objHandle: HCkSpider): Integer; stdcall; function CkSpider_getNumUnspidered(objHandle: HCkSpider): Integer; stdcall; function CkSpider_getPreferIpv6(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putPreferIpv6(objHandle: HCkSpider; newPropVal: wordbool); stdcall; procedure CkSpider_getProxyDomain(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putProxyDomain(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__proxyDomain(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getProxyLogin(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putProxyLogin(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__proxyLogin(objHandle: HCkSpider): PWideChar; stdcall; procedure CkSpider_getProxyPassword(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putProxyPassword(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__proxyPassword(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getProxyPort(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putProxyPort(objHandle: HCkSpider; newPropVal: Integer); stdcall; function CkSpider_getReadTimeout(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putReadTimeout(objHandle: HCkSpider; newPropVal: Integer); stdcall; function CkSpider_getUpdateCache(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putUpdateCache(objHandle: HCkSpider; newPropVal: wordbool); stdcall; procedure CkSpider_getUserAgent(objHandle: HCkSpider; outPropVal: HCkString); stdcall; procedure CkSpider_putUserAgent(objHandle: HCkSpider; newPropVal: PWideChar); stdcall; function CkSpider__userAgent(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getVerboseLogging(objHandle: HCkSpider): wordbool; stdcall; procedure CkSpider_putVerboseLogging(objHandle: HCkSpider; newPropVal: wordbool); stdcall; procedure CkSpider_getVersion(objHandle: HCkSpider; outPropVal: HCkString); stdcall; function CkSpider__version(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_getWindDownCount(objHandle: HCkSpider): Integer; stdcall; procedure CkSpider_putWindDownCount(objHandle: HCkSpider; newPropVal: Integer); stdcall; procedure CkSpider_AddAvoidOutboundLinkPattern(objHandle: HCkSpider; pattern: PWideChar); stdcall; procedure CkSpider_AddAvoidPattern(objHandle: HCkSpider; pattern: PWideChar); stdcall; procedure CkSpider_AddMustMatchPattern(objHandle: HCkSpider; pattern: PWideChar); stdcall; procedure CkSpider_AddUnspidered(objHandle: HCkSpider; url: PWideChar); stdcall; function CkSpider_CanonicalizeUrl(objHandle: HCkSpider; url: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSpider__canonicalizeUrl(objHandle: HCkSpider; url: PWideChar): PWideChar; stdcall; procedure CkSpider_ClearFailedUrls(objHandle: HCkSpider); stdcall; procedure CkSpider_ClearOutboundLinks(objHandle: HCkSpider); stdcall; procedure CkSpider_ClearSpideredUrls(objHandle: HCkSpider); stdcall; function CkSpider_CrawlNext(objHandle: HCkSpider): wordbool; stdcall; function CkSpider_CrawlNextAsync(objHandle: HCkSpider): HCkTask; stdcall; function CkSpider_FetchRobotsText(objHandle: HCkSpider; outStr: HCkString): wordbool; stdcall; function CkSpider__fetchRobotsText(objHandle: HCkSpider): PWideChar; stdcall; function CkSpider_FetchRobotsTextAsync(objHandle: HCkSpider): HCkTask; stdcall; function CkSpider_GetAvoidPattern(objHandle: HCkSpider; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSpider__getAvoidPattern(objHandle: HCkSpider; index: Integer): PWideChar; stdcall; function CkSpider_GetBaseDomain(objHandle: HCkSpider; domain: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSpider__getBaseDomain(objHandle: HCkSpider; domain: PWideChar): PWideChar; stdcall; function CkSpider_GetFailedUrl(objHandle: HCkSpider; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSpider__getFailedUrl(objHandle: HCkSpider; index: Integer): PWideChar; stdcall; function CkSpider_GetOutboundLink(objHandle: HCkSpider; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSpider__getOutboundLink(objHandle: HCkSpider; index: Integer): PWideChar; stdcall; function CkSpider_GetSpideredUrl(objHandle: HCkSpider; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSpider__getSpideredUrl(objHandle: HCkSpider; index: Integer): PWideChar; stdcall; function CkSpider_GetUnspideredUrl(objHandle: HCkSpider; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSpider__getUnspideredUrl(objHandle: HCkSpider; index: Integer): PWideChar; stdcall; function CkSpider_GetUrlDomain(objHandle: HCkSpider; url: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSpider__getUrlDomain(objHandle: HCkSpider; url: PWideChar): PWideChar; stdcall; procedure CkSpider_Initialize(objHandle: HCkSpider; domain: PWideChar); stdcall; function CkSpider_RecrawlLast(objHandle: HCkSpider): wordbool; stdcall; function CkSpider_RecrawlLastAsync(objHandle: HCkSpider): HCkTask; stdcall; function CkSpider_SaveLastError(objHandle: HCkSpider; path: PWideChar): wordbool; stdcall; procedure CkSpider_SkipUnspidered(objHandle: HCkSpider; index: Integer); stdcall; procedure CkSpider_SleepMs(objHandle: HCkSpider; numMilliseconds: Integer); stdcall; implementation {$Include chilkatDllPath.inc} function CkSpider_Create; external DLLName; procedure CkSpider_Dispose; external DLLName; function CkSpider_getAbortCurrent; external DLLName; procedure CkSpider_putAbortCurrent; external DLLName; function CkSpider_getAvoidHttps; external DLLName; procedure CkSpider_putAvoidHttps; external DLLName; procedure CkSpider_getCacheDir; external DLLName; procedure CkSpider_putCacheDir; external DLLName; function CkSpider__cacheDir; external DLLName; function CkSpider_getChopAtQuery; external DLLName; procedure CkSpider_putChopAtQuery; external DLLName; function CkSpider_getConnectTimeout; external DLLName; procedure CkSpider_putConnectTimeout; external DLLName; procedure CkSpider_getDebugLogFilePath; external DLLName; procedure CkSpider_putDebugLogFilePath; external DLLName; function CkSpider__debugLogFilePath; external DLLName; procedure CkSpider_getDomain; external DLLName; function CkSpider__domain; external DLLName; function CkSpider_getFetchFromCache; external DLLName; procedure CkSpider_putFetchFromCache; external DLLName; function CkSpider_getHeartbeatMs; external DLLName; procedure CkSpider_putHeartbeatMs; external DLLName; procedure CkSpider_getLastErrorHtml; external DLLName; function CkSpider__lastErrorHtml; external DLLName; procedure CkSpider_getLastErrorText; external DLLName; function CkSpider__lastErrorText; external DLLName; procedure CkSpider_getLastErrorXml; external DLLName; function CkSpider__lastErrorXml; external DLLName; function CkSpider_getLastFromCache; external DLLName; procedure CkSpider_getLastHtml; external DLLName; function CkSpider__lastHtml; external DLLName; procedure CkSpider_getLastHtmlDescription; external DLLName; function CkSpider__lastHtmlDescription; external DLLName; procedure CkSpider_getLastHtmlKeywords; external DLLName; function CkSpider__lastHtmlKeywords; external DLLName; procedure CkSpider_getLastHtmlTitle; external DLLName; function CkSpider__lastHtmlTitle; external DLLName; function CkSpider_getLastMethodSuccess; external DLLName; procedure CkSpider_putLastMethodSuccess; external DLLName; procedure CkSpider_getLastModDateStr; external DLLName; function CkSpider__lastModDateStr; external DLLName; procedure CkSpider_getLastUrl; external DLLName; function CkSpider__lastUrl; external DLLName; function CkSpider_getMaxResponseSize; external DLLName; procedure CkSpider_putMaxResponseSize; external DLLName; function CkSpider_getMaxUrlLen; external DLLName; procedure CkSpider_putMaxUrlLen; external DLLName; function CkSpider_getNumAvoidPatterns; external DLLName; function CkSpider_getNumFailed; external DLLName; function CkSpider_getNumOutboundLinks; external DLLName; function CkSpider_getNumSpidered; external DLLName; function CkSpider_getNumUnspidered; external DLLName; function CkSpider_getPreferIpv6; external DLLName; procedure CkSpider_putPreferIpv6; external DLLName; procedure CkSpider_getProxyDomain; external DLLName; procedure CkSpider_putProxyDomain; external DLLName; function CkSpider__proxyDomain; external DLLName; procedure CkSpider_getProxyLogin; external DLLName; procedure CkSpider_putProxyLogin; external DLLName; function CkSpider__proxyLogin; external DLLName; procedure CkSpider_getProxyPassword; external DLLName; procedure CkSpider_putProxyPassword; external DLLName; function CkSpider__proxyPassword; external DLLName; function CkSpider_getProxyPort; external DLLName; procedure CkSpider_putProxyPort; external DLLName; function CkSpider_getReadTimeout; external DLLName; procedure CkSpider_putReadTimeout; external DLLName; function CkSpider_getUpdateCache; external DLLName; procedure CkSpider_putUpdateCache; external DLLName; procedure CkSpider_getUserAgent; external DLLName; procedure CkSpider_putUserAgent; external DLLName; function CkSpider__userAgent; external DLLName; function CkSpider_getVerboseLogging; external DLLName; procedure CkSpider_putVerboseLogging; external DLLName; procedure CkSpider_getVersion; external DLLName; function CkSpider__version; external DLLName; function CkSpider_getWindDownCount; external DLLName; procedure CkSpider_putWindDownCount; external DLLName; procedure CkSpider_AddAvoidOutboundLinkPattern; external DLLName; procedure CkSpider_AddAvoidPattern; external DLLName; procedure CkSpider_AddMustMatchPattern; external DLLName; procedure CkSpider_AddUnspidered; external DLLName; function CkSpider_CanonicalizeUrl; external DLLName; function CkSpider__canonicalizeUrl; external DLLName; procedure CkSpider_ClearFailedUrls; external DLLName; procedure CkSpider_ClearOutboundLinks; external DLLName; procedure CkSpider_ClearSpideredUrls; external DLLName; function CkSpider_CrawlNext; external DLLName; function CkSpider_CrawlNextAsync; external DLLName; function CkSpider_FetchRobotsText; external DLLName; function CkSpider__fetchRobotsText; external DLLName; function CkSpider_FetchRobotsTextAsync; external DLLName; function CkSpider_GetAvoidPattern; external DLLName; function CkSpider__getAvoidPattern; external DLLName; function CkSpider_GetBaseDomain; external DLLName; function CkSpider__getBaseDomain; external DLLName; function CkSpider_GetFailedUrl; external DLLName; function CkSpider__getFailedUrl; external DLLName; function CkSpider_GetOutboundLink; external DLLName; function CkSpider__getOutboundLink; external DLLName; function CkSpider_GetSpideredUrl; external DLLName; function CkSpider__getSpideredUrl; external DLLName; function CkSpider_GetUnspideredUrl; external DLLName; function CkSpider__getUnspideredUrl; external DLLName; function CkSpider_GetUrlDomain; external DLLName; function CkSpider__getUrlDomain; external DLLName; procedure CkSpider_Initialize; external DLLName; function CkSpider_RecrawlLast; external DLLName; function CkSpider_RecrawlLastAsync; external DLLName; function CkSpider_SaveLastError; external DLLName; procedure CkSpider_SkipUnspidered; external DLLName; procedure CkSpider_SleepMs; external DLLName; end.
unit UDBConnectionImpl; interface uses UDBConnectionIntf, FireDAC.Comp.Client; type TDBConnection = class(TInterfacedObject, IDBConnection) private FDConnection: TFDConnection; public function getDefaultConnection: TFDConnection; constructor Create; reintroduce; destructor Destroy; override; end; implementation uses System.SysUtils; { TDBConnection } constructor TDBConnection.Create; begin inherited; FDConnection := TFDConnection.Create(nil); FDConnection.LoginPrompt := False; FDConnection.DriverName := 'SQLITE'; FDConnection.Params.Values['DriverID'] := 'SQLite'; FDConnection.Params.Values['Database'] := GetCurrentDir + PathDelim + 'db' + PathDelim + 'pizzaria.s3db'; FDConnection.Params.Values['OpenMode'] := 'CreateUTF8'; FDConnection.Params.Values['LockingMode'] := 'Normal'; FDConnection.Params.Values['Synchronous'] := 'Full'; FDConnection.Connected := True; FDConnection.Open(); end; destructor TDBConnection.Destroy; begin FDConnection.Close; FDConnection.Free; inherited; end; function TDBConnection.getDefaultConnection: TFDConnection; begin Result := FDConnection; end; end.
unit TBGZeosDriver.View.Driver; interface uses TBGConnection.Model.Interfaces, System.Classes, TBGConnection.Model.Conexao.Parametros, System.Generics.Collections, ZConnection, ZDataSet, TBGConnection.Model.DataSet.Interfaces; Type TBGZeosDriverConexao = class(TComponent, iDriver) private FFConnection: TZConnection; FFQuery: TZQuery; FiConexao : iConexao; FiQuery : TList<iQuery>; FLimitCacheRegister : Integer; FLimitCache: Integer; FProxy : iDriverProxy; procedure SetFConnection(const Value: TZConnection); procedure SetFQuery(const Value: TZQuery); procedure SetLimitCache(const Value: Integer); function GetLimitCache: Integer; protected FParametros : iConexaoParametros; function Conexao : iConexao; function Query : iQuery; function DataSet : iDataSet; function Cache : iDriverProxy; public constructor Create; destructor Destroy; override; class function New : iDriver; function Conectar : iConexao; function &End: TComponent; function Parametros: iConexaoParametros; function LimitCacheRegister(Value : Integer) : iDriver; published property FConnection : TZConnection read FFConnection write SetFConnection; property LimitCache : Integer read GetLimitCache write SetLimitCache; end; procedure Register; implementation uses System.SysUtils, TBGZeosDriver.Model.Conexao, TBGZeosDriver.Model.Query, TBGConnection.Model.DataSet.Proxy, TBGZeosDriver.Model.DataSet; { TBGZeosDriverConexao } function TBGZeosDriverConexao.Cache: iDriverProxy; begin if not Assigned(FProxy) then FProxy := TTBGConnectionModelProxy.New(FLimitCacheRegister, Self); Result := FProxy; end; function TBGZeosDriverConexao.Conectar: iConexao; begin end; function TBGZeosDriverConexao.&End: TComponent; begin end; function TBGZeosDriverConexao.GetLimitCache: Integer; begin Result := FLimitCacheRegister; end; function TBGZeosDriverConexao.LimitCacheRegister(Value: Integer): iDriver; begin Result := Self; FLimitCacheRegister := Value; end; function TBGZeosDriverConexao.Conexao: iConexao; begin if not Assigned(FiConexao) then FiConexao := TZeosDriverModelConexao.New(FFConnection, FLimitCacheRegister, Self); Result := FiConexao; end; constructor TBGZeosDriverConexao.Create; begin FiQuery := TList<iQuery>.Create; LimitCache := 10; end; function TBGZeosDriverConexao.DataSet: iDataSet; begin if not Assigned(FProxy) then FProxy := TTBGConnectionModelProxy.New(FLimitCacheRegister, Self); Result := TConnectionModelZeosDataSet.New(FProxy.ObserverList); end; destructor TBGZeosDriverConexao.Destroy; begin FreeAndNil(FiQuery); inherited; end; class function TBGZeosDriverConexao.New: iDriver; begin Result := Self.Create; end; function TBGZeosDriverConexao.Parametros: iConexaoParametros; begin Result := FParametros; end; function TBGZeosDriverConexao.Query: iQuery; begin if Not Assigned(FiQuery) then FiQuery := TList<iQuery>.Create; if Not Assigned(FiConexao) then FiConexao := TZeosDriverModelConexao.New(FFConnection, FLimitCacheRegister, Self); FiQuery.Add(TZeosModelQuery.New(FFConnection, Self)); Result := FiQuery[FiQuery.Count-1]; end; procedure TBGZeosDriverConexao.SetFConnection(const Value: TZConnection); begin FFConnection := Value; end; procedure TBGZeosDriverConexao.SetFQuery(const Value: TZQuery); begin FFQuery := Value; end; procedure TBGZeosDriverConexao.SetLimitCache(const Value: Integer); begin FLimitCacheRegister := Value; end; procedure Register; begin RegisterComponents('TBGAbstractConnection', [TBGZeosDriverConexao]); end; end.
unit wordpress_featuredimage_model; {$mode objfpc}{$H+} interface uses Classes, SysUtils, database_lib; type { TFeaturedimage } TFeaturedimage = class(TSimpleModel) private public constructor Create(const DefaultTableName: string = ''); function GetFeaturedImageURLByID(const NewsID: integer): string; function GetFeaturedImageURLByPermalink(const NewsID: integer): string; end; implementation uses fastplaz_handler, common, wordpress_nggallery_model; constructor TFeaturedimage.Create(const DefaultTableName: string = ''); begin inherited Create('postmeta'); end; function TFeaturedimage.GetFeaturedImageURLByID(const NewsID: integer): string; var meta_value_string: string; wpnggallery: TWPNGGallery; begin Result := ''; Find(['meta_key=''_thumbnail_id''', 'post_id=' + i2s(NewsID)]); if Data.RecordCount = 0 then Exit; meta_value_string := Data.FieldValues['meta_value']; // if nggallery if Pos('ngg-', meta_value_string) > 0 then begin meta_value_string := StringReplace(meta_value_string, 'ngg-', '', [rfReplaceAll]); wpnggallery := TWPNGGallery.Create(); wpnggallery.AddJoin('ngg_gallery', 'gid', 'galleryid', ['path']); wpnggallery.FindFirst([AppData.tablePrefix + '_ngg_pictures.pid=' + meta_value_string], '', 'filename,alttext'); if wpnggallery.Data.RecordCount > 0 then Result := wpnggallery.Value['path'].AsString + '/' + wpnggallery.Value['filename'].AsString; FreeAndNil(wpnggallery); Exit; end; // if nggallery - end Find(['meta_key=''_wp_attached_file''', 'post_id=' + meta_value_string]); if Data.RecordCount = 0 then Exit; Result := 'wp-content/uploads/' + Data.FieldValues['meta_value']; end; function TFeaturedimage.GetFeaturedImageURLByPermalink(const NewsID: integer): string; begin Result := ''; end; end.
unit UClienteServiceImpl; interface uses UClienteServiceIntf, UClienteRepositoryIntf; type TClienteService = class(TInterfacedObject, IClienteService) private FClienteRepository: IClienteRepository; public function adquirirCodigoCliente(const ADocumentoCliente: string): Integer; constructor Create; reintroduce; end; implementation uses System.SysUtils, UClienteRepositoryImpl; { TClienteService } function TClienteService.adquirirCodigoCliente(const ADocumentoCliente: string): Integer; begin Result := Integer.MinValue; try Result := FClienteRepository.adquirirCodigoCliente(ADocumentoCliente); except on E: Exception do begin FClienteRepository.adicionarCliente(ADocumentoCliente); end; end; if (Result = Integer.MinValue) then Result := FClienteRepository.adquirirCodigoCliente(ADocumentoCliente); end; constructor TClienteService.Create; begin inherited; FClienteRepository := TClienteRepository.Create; end; end.
unit uPointCommand; interface uses System.Types , Vcl.ExtCtrls , VCL.Graphics , Spring.Collections , uPointInterfaces , System.UITypes ; type TPointPlacerCommand = class(TInterfacedObject, IPointCommand) private FCanvas: TCanvas; FPoint: TPoint; public constructor Create(aCanvas: TCanvas; aPoint: TPoint); procedure Execute; procedure Undo; end; implementation const CircleDiameter = 15; constructor TPointPlacerCommand.Create(aCanvas: TCanvas; aPoint: TPoint); begin inherited Create; FCanvas := aCanvas; FPoint := aPoint; end; procedure TPointPlacerCommand.Execute; var FOriginalColor: TColor; begin FOriginalColor := FCanvas.Brush.Color; try FCanvas.Brush.Color := clRed; FCanvas.Pen.Color := clRed; FCanvas.Ellipse(FPoint.X, FPoint.Y, FPoint.X + CircleDiameter, FPoint.Y + CircleDiameter); finally FCanvas.Brush.Color := FOriginalColor; FCanvas.Pen.Color := FOriginalColor; end; end; procedure TPointPlacerCommand.Undo; begin FCanvas.Ellipse(FPoint.X, FPoint.Y, FPoint.X + CircleDiameter, FPoint.Y + CircleDiameter); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de TalonarioCheque The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> t2ti.com@gmail.com @author Albert Eije (T2Ti.COM) @version 2.0 ******************************************************************************* } unit UTalonarioCheque; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, TalonarioChequeVO, TalonarioChequeController, Tipos, Atributos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, Controller; type [TFormDescription(TConstantes.MODULO_CADASTROS, 'Talonário Cheque')] TFTalonarioCheque = class(TFTelaCadastro) BevelEdits: TBevel; EditContaCaixa: TLabeledEdit; EditTalao: TLabeledEdit; EditIdContaCaixa: TLabeledCalcEdit; EditNumero: TLabeledCalcEdit; ComboboxStatusTalao: TLabeledComboBox; procedure FormCreate(Sender: TObject); procedure EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FTalonarioCheque: TFTalonarioCheque; implementation uses ULookup, Biblioteca, UDataModule, ContaCaixaVO, ContaCaixaController; {$R *.dfm} {$REGION 'Infra'} procedure TFTalonarioCheque.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TTalonarioChequeVO; ObjetoController := TTalonarioChequeController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFTalonarioCheque.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdContaCaixa.SetFocus; end; end; function TFTalonarioCheque.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdContaCaixa.SetFocus; end; end; function TFTalonarioCheque.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('TalonarioChequeController.TTalonarioChequeController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('TalonarioChequeController.TTalonarioChequeController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFTalonarioCheque.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TTalonarioChequeVO.Create; TTalonarioChequeVO(ObjetoVO).IdContaCaixa := EditIdContaCaixa.AsInteger; TTalonarioChequeVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TTalonarioChequeVO(ObjetoVO).Numero := EditNumero.AsInteger; TTalonarioChequeVO(ObjetoVO).Talao := EditTalao.Text; TTalonarioChequeVO(ObjetoVO).StatusTalao := Copy(ComboboxStatusTalao.Text, 1, 1); if StatusTela = stInserindo then begin TController.ExecutarMetodo('TalonarioChequeController.TTalonarioChequeController', 'Insere', [TTalonarioChequeVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TTalonarioChequeVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('TalonarioChequeController.TTalonarioChequeController', 'Altera', [TTalonarioChequeVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFTalonarioCheque.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TTalonarioChequeVO(TController.BuscarObjeto('TalonarioChequeController.TTalonarioChequeController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdContaCaixa.AsInteger := TTalonarioChequeVO(ObjetoVO).IdContaCaixa; EditContaCaixa.Text := TTalonarioChequeVO(ObjetoVO).ContaCaixaNome; EditTalao.Text := TTalonarioChequeVO(ObjetoVO).Talao; EditNumero.AsInteger := TTalonarioChequeVO(ObjetoVO).Numero; ComboboxStatusTalao.ItemIndex := AnsiIndexStr(TTalonarioChequeVO(ObjetoVO).StatusTalao, ['N', 'C', 'E', 'U']); // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes '} procedure TFTalonarioCheque.EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdContaCaixa.Value <> 0 then Filtro := 'ID = ' + EditIdContaCaixa.Text else Filtro := 'ID=0'; try EditIdContaCaixa.Clear; EditContaCaixa.Clear; if not PopulaCamposTransientes(Filtro, TContaCaixaVO, TContaCaixaController) then PopulaCamposTransientesLookup(TContaCaixaVO, TContaCaixaController); if CDSTransiente.RecordCount > 0 then begin EditIdContaCaixa.Text := CDSTransiente.FieldByName('ID').AsString; EditContaCaixa.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdContaCaixa.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
unit ChangeUserPassword; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BCControls.Edit, Vcl.ExtCtrls, BCDialogs.Dlg; type TChangeUserPasswordDialog = class(TDialog) BottomPanel: TPanel; CancelButton: TButton; ExportButton: TButton; PasswordEdit: TBCEdit; PasswordLabel: TLabel; Separator1Panel: TPanel; TopPanel: TPanel; procedure FormDestroy(Sender: TObject); private { Private declarations } FUserName: string; public { Public declarations } function GetSQL: string; function Open(UserName: string): Boolean; end; function ChangeUserPasswordDialog: TChangeUserPasswordDialog; implementation {$R *.dfm} uses BCCommon.StyleUtils; const CAPTION_TEXT = 'Change Password of %s'; var FChangeUserPasswordDialog: TChangeUserPasswordDialog; function ChangeUserPasswordDialog: TChangeUserPasswordDialog; begin if not Assigned(FChangeUserPasswordDialog) then Application.CreateForm(TChangeUserPasswordDialog, FChangeUserPasswordDialog); Result := FChangeUserPasswordDialog; SetStyledFormSize(Result); end; procedure TChangeUserPasswordDialog.FormDestroy(Sender: TObject); begin FChangeUserPasswordDialog := nil; end; function TChangeUserPasswordDialog.Open(UserName: string): Boolean; begin FUserName := UserName; Caption := Format(CAPTION_TEXT, [UserName]); Width := Canvas.TextWidth(Caption) + 80; Result := ShowModal = mrOk; end; function TChangeUserPasswordDialog.GetSQL: string; begin Result := Format('ALTER USER %s IDENTIFIED BY "%s"', [FUserName, PasswordEdit.Text]); end; end.
unit PersonU; interface uses MVCFramework.Serializer.Commons; type TPerson = class private FLastName: string; FDateOfBirth: TDate; FFirstName: string; procedure SetDateOfBirth(const Value: TDate); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); public property FirstName: string read FFirstName write SetFirstName; property LastName: string read FLastName write SetLastName; property DateOfBirth: TDate read FDateOfBirth write SetDateOfBirth; end; [MapperJSONNaming(TJSONNameCase.JSONNameUpperCase)] TPersonUpperCase = class(TPerson) end; [MapperJSONNaming(TJSONNameCase.JSONNameLowerCase)] TPersonLowerCase = class(TPerson) end; TPersonCustomCase = class private FPhoneNumber: string; FWorkEmail: string; FLastName: string; FFirstName: string; FDateOfBirth: TDate; procedure SetPhoneNumber(const Value: string); procedure SetWorkEmail(const Value: string); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); procedure SetDateOfBirth(const Value: TDate); public [MapperJSONSer('first_name')] property FirstName: string read FFirstName write SetFirstName; [MapperJSONSer('last_name')] property LastName: string read FLastName write SetLastName; [MapperJSONSer('date_of_birth')] property DateOfBirth: TDate read FDateOfBirth write SetDateOfBirth; [MapperJSONSer('phoneNumber')] property PhoneNumber: string read FPhoneNumber write SetPhoneNumber; [MapperJSONSer('workEmail')] property WorkEmail: string read FWorkEmail write SetWorkEmail; end; implementation { TPerson } procedure TPerson.SetDateOfBirth(const Value: TDate); begin FDateOfBirth := Value; end; procedure TPerson.SetFirstName(const Value: string); begin FFirstName := Value; end; procedure TPerson.SetLastName(const Value: string); begin FLastName := Value; end; { TPersonCustomCase } procedure TPersonCustomCase.SetDateOfBirth(const Value: TDate); begin FDateOfBirth := Value; end; procedure TPersonCustomCase.SetFirstName(const Value: string); begin FFirstName := Value; end; procedure TPersonCustomCase.SetLastName(const Value: string); begin FLastName := Value; end; procedure TPersonCustomCase.SetPhoneNumber(const Value: string); begin FPhoneNumber := Value; end; procedure TPersonCustomCase.SetWorkEmail(const Value: string); begin FWorkEmail := Value; end; end.
unit uGameTech; interface uses Classes, uEntities; type PTech = ^TTech; TTech = record ClassType_: cardinal; // de entity-class Name: string; // naam van de technology ButtonImage: string; // het plaatje voor op de knop CreationCosts: single; // de kosten om deze tech. te maken CreationDuration: integer; // de tijd (in seconden) om deze tech. te maken Available: boolean; // beschikbaar?? Action: TNotifyEvent; // de uit te voeren procedure (als men op de HUD-knop drukt) end; PTechTree = ^TTechTree; TTechTree = record // tree Parent: integer; //PTechTree; Children: array of integer; //PTechTree; // Tech: TTech; end; PGameTech = ^TGameTech; TGameTech = class(TObject) private procedure AddTechToTree(aParent: integer; //PTechTree; aClassType: cardinal; aName: string; aButtonImage: string; aCreationCosts: single; aCreationDuration: integer; aAction: TNotifyEvent); public TechTree: array of TTechTree; // constructor Create; destructor Destroy; override; // knoppen maken voor alle technology procedure CreateButtonSets(var aHUD: TEntityHUD; RootIndex: integer); overload; //PTechTree procedure CreateButtonSets(var aHUD: TEntityHUD); overload; // TNotifyEvent tbv. button.onup procedure SpawnNewOreMiner(Sender: TObject); procedure Spawn10NewOreMiner(Sender: TObject); procedure Spawn100NewOreMiner(Sender: TObject); procedure Spawn1000NewOreMiner(Sender: TObject); procedure UpgradeOreMiner(Sender: TObject); // procedure ConstructSpawnpoint(Sender: TObject); // kies een plek om een spawnpoint te bouwen procedure SpawnNewSpawnpoint(const X,Y: integer); // plaats een nieuw spawnpoint (X,Y = schermcoords) // procedure ConstructPowerpylon(Sender: TObject); // kies een plek om een powerpylon te bouwen procedure SpawnNewPowerpylon(const X,Y: integer); // plaats een nieuwe powerpylon // procedure ConstructPowerline(Sender: TObject); // kies een (andere) powerpylon om een powerline te bevestigen procedure SpawnNewPowerline(const X,Y: integer); // plaats een nieuwe powerline end; var GameTech: TGameTech; implementation uses u3DTypes, uCalc, uConst, OpenGL, uOpenGL, SysUtils, MMSystem; //----------------------------------------------- constructor TGameTech.Create; begin SetLength(TechTree, 0); // De technology-tree opbouwen: // de parameter "aParent" bepaalt onder welke tak een nieuwe tech komt te hangen. // 0 AddTechToTree(-1, cltEntityRoot, 'Root', '', 0.0, 0, nil); // een dummy als root-node (om de children te bevatten) // 1 AddTechToTree(0, cltEntityRoot, 'Spawnpoint', 'button_windmill.tga', 1000.0, 30, ConstructSpawnpoint); // 2 AddTechToTree(1, cltEntitySpawnpoint, 'Oreminer', 'button_oreminer.tga', 300.0, 20, SpawnNewOreMiner); // 3 AddTechToTree(2, cltEntityOreMiner, 'OreminerUpgrade1', 'button_oreminer_upgrade1.tga', 500.0, 60, UpgradeOreMiner); // 4 AddTechToTree(2, cltEntityOreMiner, 'OreminerUpgrade2', 'button_oreminer_upgrade2.tga', 500.0, 60, UpgradeOreMiner); // 5 AddTechToTree(2, cltEntityOreMiner, 'OreminerUpgrade3', 'button_oreminer_upgrade3.tga', 500.0, 60, UpgradeOreMiner); // 6 AddTechToTree(2, cltEntityOreMiner, 'OreminerUpgrade4', 'button_oreminer_upgrade4.tga', 500.0, 60, UpgradeOreMiner); // 7 AddTechToTree(2, cltEntityOreMiner, 'OreminerUpgrade5', 'button_oreminer_upgrade5.tga', 500.0, 60, UpgradeOreMiner); // 8 AddTechToTree(1, cltEntitySpawnpoint, 'SpawnpointUpgrade1', 'button_oreminer.tga', 300.0, 20, Spawn10NewOreMiner); // 9 AddTechToTree(1, cltEntitySpawnpoint, 'SpawnpointUpgrade2', 'button_oreminer.tga', 300.0, 20, Spawn100NewOreMiner); // 10 AddTechToTree(1, cltEntitySpawnpoint, 'SpawnpointUpgrade3', 'button_oreminer.tga', 300.0, 20, Spawn1000NewOreMiner); // 11 AddTechToTree(0, cltEntityRoot, 'Powerpylon', 'button_powerpylon.tga', 200.0, 5, ConstructPowerpylon); // 12 AddTechToTree(11, cltEntityPowerpylon, 'Powerline', 'button_powerline.tga', 100.0, 20, ConstructPowerline); end; destructor TGameTech.Destroy; begin SetLength(TechTree, 0); inherited; end; //----------------------------------------------- procedure TGameTech.AddTechToTree(aParent: integer; //PTechTree; aClassType: cardinal; aName: string; aButtonImage: string; aCreationCosts: single; aCreationDuration: integer; aAction: TNotifyEvent); var TT, NewTT: TTechTree; LenT, LenC, t: integer; begin with NewTT.Tech do begin ClassType_ := aClassType; Name := aName; ButtonImage := aButtonImage; CreationCosts := aCreationCosts; CreationDuration := aCreationDuration; Available := (aParent = -1); Action := aAction; end; NewTT.Parent := aParent; // de nieuwe entry toevoegen aan de tree LenT := Length(TechTree); Setlength(TechTree, LenT+1); TechTree[LenT] := NewTT; if (aParent>=LenT) then raise Exception.Create('Foute parent opgegeven in de TechTree.'); // toevoegen (als child) aan een reeds bestaande parent?? if aParent <> -1 then begin LenC := Length(TechTree[aParent].Children); SetLength(TechTree[aParent].Children, LenC+1); TechTree[aParent].Children[LenC] := LenT; end; end; procedure TGameTech.CreateButtonSets(var aHUD: TEntityHUD; RootIndex: integer); // var LenBS, LenB, LenC, c,t,sibling: integer; begin if Length(TechTree)=0 then Exit; with TechTree[RootIndex] do begin // check of dit geen Root-tech is.. if Parent <> -1 then begin // een buttonset bijmaken with Tech do begin LenBS := Length(aHUD.ButtonSets); aHUD.CreateButtonSet(Name,ClassType_); end; // Een non root-tech zit altijd in een button-set met zijn siblings. for c:=Low(TechTree[Parent].Children) to High(TechTree[Parent].Children) do begin sibling := TechTree[Parent].Children[c]; with TechTree[sibling].Tech do begin // maak een knop LenB := Length(aHUD.ButtonSets[LenBS].Buttons); aHUD.ButtonSets[LenBS].AddButton(Name,ButtonImage); aHUD.ButtonSets[LenBS].Buttons[LenB].OnUp:= Action; aHUD.ButtonSets[LenBS].Buttons[LenB].TechIndex := sibling; end; end; end; end; end; procedure TGameTech.CreateButtonSets(var aHUD: TEntityHUD); begin CreateButtonSets(aHUD, 0); end; //----------------------------------------------- procedure TGameTech.SpawnNewOreMiner(Sender: TObject); var V: TVector; x,z: single; Len: integer; Entity: PEntity; TileX, TileY: integer; begin Game.isConstructing := false; // bepaal het geselecteerde spawnpoint Entity := Game.HUD[0].ButtonsPtr.AssignedEntity; if Entity^.ClassType_<>cltEntitySpawnPoint then Exit; // het moet wel een geselecteerd spawnpoint zijn.. // * Maak een unit TileX := (Entity^ as TEntitySpawnPoint).TileX; TileY := (Entity^ as TEntitySpawnPoint).TileY; x := Game.Map.Terrain.Tiles[TileX,TileY].CenterX; z := Game.Map.Terrain.Tiles[TileX,TileY].CenterY; V := Vector(x,Game.Map.Terrain.GetHeightAt(x,z),z); Len := Length(Game.Map.Units); Game.Map.AddUnit(c_UNIT_OREMINER,0,V); with Game.Map.Units[Len] do begin case ClassType_ of cltEntityOreMiner: with (Game.Map.Units[Len] as TEntityOreMiner) do begin MaxSpeed := c_MAXSPEED_OREMINER; isReturning := true; CalcNextRoute; end; end; end; end; procedure TGameTech.Spawn10NewOreMiner(Sender: TObject); var i: integer; begin for i:=0 to 9 do SpawnNewOreMiner(Sender); end; procedure TGameTech.Spawn100NewOreMiner(Sender: TObject); var i: integer; begin for i:=0 to 99 do SpawnNewOreMiner(Sender); end; procedure TGameTech.Spawn1000NewOreMiner(Sender: TObject); var i: integer; begin for i:=0 to 999 do SpawnNewOreMiner(Sender); end; //----------------------------------------------- procedure TGameTech.UpgradeOreMiner(Sender: TObject); var Entity: PEntity; begin // Game.ConstructingEntity bevat de entity die iets bouwt Game.isConstructing := false; Entity := Game.ConstructingEntity; {Entity := Game.HUD[0].ButtonsPtr.AssignedEntity;} if Entity^.ClassType_ <> cltEntityOreMiner then Exit; // het moet wel een geselecteerde oreminer zijn.. (Entity^ as TEntityOreMiner).Upgrade; //opnieuw afbeelden voor deze entity (indien deze entity nu is geselecteerd) if Game.HUD[0].ButtonsPtr.AssignedEntity = Game.ConstructingEntity then Game.HUD[0].AssignEntity(Entity); end; //----------------------------------------------- procedure TGameTech.ConstructSpawnpoint(Sender: TObject); begin Game.StartConstructing(cltEntitySpawnpoint); end; procedure TGameTech.SpawnNewSpawnpoint(const X, Y: integer); var objX,objY,objZ: GLdouble; V: TVector; Len, TileX,TileY: integer; s: string; begin // bepaal de object-coords OGL.ScreenToObjectCoords(X,Y, objX,objY,objZ); V := Vector(objX,objY,objZ); // controleer of op de map is geklikt if not Game.Map.IsOnTerrain(V) then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // test of de tile nog vrij is Game.Map.LocationToTile(V, TileX,TileY); if Game.Map.Terrain.Tiles[TileX,TileY].Team <> c_NOTEAM then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // voeg een spawnpoint toe Len := Length(Game.Map.Spawnpoints); s := '<GAME.MAP.SPAWNPOINT'+IntToStr(Len)+' NAME>'; Game.Map.AddSpawnpoint(s,0, TileX,TileY); PlaySound(Soundacknowledged,0,SND_ASYNC+SND_NODEFAULT); Game.StopConstructing; end; //----------------------------------------------- procedure TGameTech.ConstructPowerpylon(Sender: TObject); begin Game.StartConstructing(cltEntityPowerpylon); end; procedure TGameTech.SpawnNewPowerpylon(const X, Y: integer); var objX,objY,objZ: GLdouble; V: TVector; Len, TileX,TileY: integer; s: string; begin // bepaal de object-coords OGL.ScreenToObjectCoords(X,Y, objX,objY,objZ); V := Vector(objX,objY,objZ); // controleer of op de map is geklikt if not Game.Map.IsOnTerrain(V) then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // test of de tile nog vrij is Game.Map.LocationToTile(V, TileX,TileY); if Game.Map.Terrain.Tiles[TileX,TileY].Team <> c_NOTEAM then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // voeg een powerpylon toe Len := Length(Game.Map.Powerpylons); s := '<GAME.MAP.POWERPYLON'+IntToStr(Len)+' NAME>'; Game.Map.AddPowerpylon(s,0, TileX,TileY); PlaySound(Soundacknowledged,0,SND_ASYNC+SND_NODEFAULT); Game.StopConstructing; end; //----------------------------------------------- procedure TGameTech.ConstructPowerline(Sender: TObject); begin Game.StartConstructing(cltEntityPowerline); end; procedure TGameTech.SpawnNewPowerline(const X, Y: integer); var objX,objY,objZ: GLdouble; V: TVector; Len, TileX,TileY, i: integer; s: string; pFound: PEntity; begin // if Game.ConstructingEntity^.ClassType_ <> cltEntityPowerpylon then Exit; // bepaal de object-coords OGL.ScreenToObjectCoords(X,Y, objX,objY,objZ); V := Vector(objX,objY,objZ); // controleer of op de map is geklikt if not Game.Map.IsOnTerrain(V) then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // de tile moet niet meer vrij zijn, maar in bezit van het eigen team Game.Map.LocationToTile(V, TileX,TileY); if Game.Map.Terrain.Tiles[TileX,TileY].Team <> c_TEAM0 then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // test of de powerline is verbonden tussen 2 geldige entities // Het moet zijn: Game.ConstructingEntity & (een powerpylon of spawnpoint) pFound := nil; for i:=0 to Length(Game.Map.Spawnpoints)-1 do if (Game.Map.Spawnpoints[i].TileX=TileX) and (Game.Map.Spawnpoints[i].TileY=TileY) then begin pFound := @Game.Map.Spawnpoints[i]; if PEntitySpawnpoint(pFound)^.ConnectedTo <> nil then pFound := nil; // al verbonden.. Break; end; if pFound=nil then for i:=0 to Length(Game.Map.Powerpylons)-1 do if (Game.Map.Powerpylons[i].TileX=TileX) and (Game.Map.Powerpylons[i].TileY=TileY) then begin pFound := @Game.Map.Powerpylons[i]; if pFound = Game.ConstructingEntity then pFound := nil; // niet aan zichzelf verbinden.. if pFound <> nil then if PEntityPowerpylon(pFound)^.ConnectedTo1 <> nil then pFound := nil; // al verbonden.. Break; end; if pFound=nil then begin PlaySound(SoundNoOperation,0,SND_ASYNC+SND_NODEFAULT); Exit; end; // voeg een powerline toe Len := Length(Game.Map.Powerlines); s := '<GAME.MAP.POWERLINE'+IntToStr(Len)+' NAME>'; Game.Map.AddPowerline(s,0, TileX,TileY, Game.ConstructingEntity, pFound); PlaySound(Soundacknowledged,0,SND_ASYNC+SND_NODEFAULT); Game.StopConstructing; end; //----------------------------------------------- initialization GameTech := TGameTech.Create; finalization GameTech.Free; end.
// ################################## // ###### IT PAT 2017 ####### // ###### PHASE 3 ####### // ###### Tiaan van der Riel ####### // ################################## unit frmCreateNewAccount_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, ExtCtrls, math; type TfrmCreateNewAccount = class(TForm) lblCreateNewAccountHeading: TLabel; lblDateOfBirth: TLabel; lblGender: TLabel; lblGenderM: TLabel; lblGenderF: TLabel; spnedtDayOfBirth: TSpinEdit; lbledtName: TLabeledEdit; lbledtID: TLabeledEdit; lbledtEmailAdress: TLabeledEdit; lbledtCellphoneNumber: TLabeledEdit; lbledtPassword: TLabeledEdit; lbledtPasswordRetype: TLabeledEdit; lbledtSurname: TLabeledEdit; lbledtUsername: TLabeledEdit; rbFemale: TRadioButton; rbMale: TRadioButton; btnSignUp: TButton; btnBack: TButton; btnCreateNewAccountHelp: TButton; spnedtYearOfBirth: TSpinEdit; cbxMonth: TComboBox; procedure btnCreateNewAccountHelpClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnBackClick(Sender: TObject); procedure btnSignUpClick(Sender: TObject); private { Private declarations } sName: string; sSurname: string; sUsername: string; iIDNumber: integer; sGender: string; sEmailAdress: string; sCellphoneNumber: string; sPassword: string; sPleaseRetypePassword: string; iEnteredBirthDay: integer; iEnteredBirthMonth: integer; iEnteredBirthYear: integer; ///============= Custom Procedures =========// procedure ShowHelpAfterIncorrectAttempt; procedure ResetAll; // Resets form to the way it initially looked procedure ShowHelp; // Shows the user a help file //========= Custom Functions ===============// Function IsAllFieldsPresent: boolean; // Determines if all fields are entered Function IsNameValid: boolean; // Determines if name is valid Function IsSurnameValid: boolean; // Determine if surname is valid Function IsUsernameExists: boolean; // Determines if the user entered a new username Function IsCellphoneNumberValid: boolean; // Determines if cellphone number is 10 DIGITS long Function IsPasswordValid: boolean; // Checks that password is at least 8 characters long, and contains at least // one uppercase letter, one lowercase letter and at least one number. Function IsIDNumberValidNumbers: boolean; // Function that checks that the ID Number contains only numbers and is 13 digits long Function IsIDNumberValidBirthDate: boolean; // Checks that the user`s enterd bithdates match ID Function IsIDNumberValidGender: boolean; // Checks that the user`s gender matches his ID`s Function IsIDNumberValidCheckDigit: boolean; // Checks that the check digit validates according to Luhn`s equation /// //////////////////// Function GetPlayersID: integer; // gets the pleyers unique player ID to add as a primary key in the database Function DeterminePlayerAge: integer; // Determines the user`s age Procedure CreateNewUserMatchHistory; // Creates the text file that saves the user`s match history; public { Public declarations } end; var frmCreateNewAccount: TfrmCreateNewAccount; implementation Uses frmLansLandia_u, dmAccounts_u, frmUserHomePage_u; {$R *.dfm} /// ============ Function to detirmine if all fields are entered ============== Function TfrmCreateNewAccount.IsAllFieldsPresent: boolean; { The purpose of this procedure is to determine if all of the fields are entered} begin IsAllFieldsPresent := True; // Name sName := lbledtName.Text; if sName = '' then Begin ShowMessage('Please enter a name.'); lbledtName.EditLabel.Font.Color := clRed; lbledtName.EditLabel.Caption := '*** Name:'; IsAllFieldsPresent := False; End; // Surname sSurname := lbledtSurname.Text; if sSurname = '' then Begin ShowMessage('Please enter a surname.'); lbledtSurname.EditLabel.Font.Color := clRed; lbledtSurname.EditLabel.Caption := '*** Surname:'; IsAllFieldsPresent := False; End; // Username sUsername := lbledtUsername.Text; if sUsername = '' then Begin ShowMessage('Please enter a username.'); lbledtUsername.EditLabel.Font.Color := clRed; lbledtUsername.EditLabel.Caption := '*** Username:'; IsAllFieldsPresent := False; End; // ID Number if lbledtID.Text = '' then Begin ShowMessage('Please enter a ID'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID:'; IsAllFieldsPresent := False; End; // Gender if (rbMale.Checked = False) AND (rbFemale.Checked = False) then Begin ShowMessage('Please select a gender. '); lblGender.Font.Color := clRed; lblGender.Caption := '*** Gender:'; IsAllFieldsPresent := False; End; // Email sEmailAdress := lbledtEmailAdress.Text; if sEmailAdress = '' then Begin ShowMessage('Please enter a Email Adress.'); lbledtEmailAdress.EditLabel.Font.Color := clRed; lbledtEmailAdress.EditLabel.Caption := '*** Email Aress:'; IsAllFieldsPresent := False; End; // Cellphone Number sCellphoneNumber := lbledtCellphoneNumber.Text; if sCellphoneNumber = '' then Begin ShowMessage('Please enter a Cellphone Number.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsAllFieldsPresent := False; End; // Password sPassword := lbledtPassword.Text; if sPassword = '' then Begin ShowMessage('Please enter a password.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsAllFieldsPresent := False; End; // Please Retype Password sPleaseRetypePassword := lbledtPasswordRetype.Text; if sPleaseRetypePassword = '' then Begin ShowMessage('Please retype your password.'); lbledtPasswordRetype.EditLabel.Font.Color := clRed; lbledtPasswordRetype.EditLabel.Caption := '*** Please Retype Your Password:'; IsAllFieldsPresent := False; End; end; /// ==================== Function to detirmine is name is valid =============== function TfrmCreateNewAccount.IsNameValid: boolean; { This function checks that the name contains only letters and spaces} var i: integer; begin IsNameValid := True; sName := lbledtName.Text; for i := 1 to Length(sName) do Begin sName[i] := Upcase(sName[i]); if not(sName[i] in ['A' .. 'Z']) AND (sName[i] <> ' ') then begin ShowMessage('Your name can only contain letters and spaces.'); lbledtName.EditLabel.Font.Color := clRed; lbledtName.EditLabel.Caption := '*** Name:'; IsNameValid := False; end; End; end; /// ================= Function to determine if surname is valid =============== function TfrmCreateNewAccount.IsSurnameValid: boolean; { This function checks that the surname contains only letters and spaces} var i: integer; begin IsSurnameValid := True; sName := lbledtSurname.Text; for i := 1 to Length(sSurname) do Begin sSurname[i] := Upcase(sSurname[i]); if not(sSurname[i] in ['A' .. 'Z']) AND (sSurname[i] <> ' ') then begin ShowMessage('Your surname can only contain letters and spaces.'); lbledtSurname.EditLabel.Font.Color := clRed; lbledtSurname.EditLabel.Caption := '*** Surname:'; IsSurnameValid := False; end; End; end; /// ====== Function to determine if the user entered a new username ========== Function TfrmCreateNewAccount.IsUsernameExists: boolean; { This function takes the username the user chose and determines wheter or not that username already existst in the database by searching for it} begin sUsername := lbledtUsername.Text; dmAccounts.tblAccounts.First; while not dmAccounts.tblAccounts.Eof do Begin if sUsername = dmAccounts.tblAccounts['username'] then Begin ShowMessage( 'This username has already been taken. Please enter a new one.'); lbledtUsername.EditLabel.Font.Color := clRed; lbledtUsername.EditLabel.Caption := '*** Username:'; IsUsernameExists := True; End; dmAccounts.tblAccounts.Next; End; end; /// ===== Function that determines if cellphone number is 10 DIGITS long ======= Function TfrmCreateNewAccount.IsCellphoneNumberValid; { This function checks that the cellphone number is 10 digits long, and contains only numbers} var i: integer; begin IsCellphoneNumberValid := True; sCellphoneNumber := lbledtCellphoneNumber.Text; if Length(sCellphoneNumber) <> 10 then Begin ShowMessage('Your cellphone number is not the correct lenght.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsCellphoneNumberValid := False; End; for i := 1 to Length(sCellphoneNumber) do Begin if NOT(sCellphoneNumber[i] In ['0' .. '9']) then Begin ShowMessage('Your cellphone number can only contain numbers.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsCellphoneNumberValid := False; end; end; end; /// ===================== Function that validates password ==================== Function TfrmCreateNewAccount.IsPasswordValid: boolean; { Checks that password is at least 8 characters long, and contaains at least one uppercase letter, one lowercase letter and at least one number. } var i: integer; bContainsUppercase: boolean; bContainsLowercase: boolean; bContainsNumber: boolean; begin IsPasswordValid := True; sPassword := lbledtPassword.Text; if Length(sPassword) < 8 then Begin ShowMessage('Your password needs to be at least 8 characters long.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsPasswordValid := False; End; bContainsUppercase := False; bContainsLowercase := False; bContainsNumber := False; for i := 1 to Length(sPassword) do Begin if sPassword[i] IN ['a' .. 'z'] then Begin bContainsLowercase := True; End; if sPassword[i] IN ['A' .. 'Z'] then Begin bContainsUppercase := True; End; if sPassword[i] IN ['0' .. '9'] then Begin bContainsNumber := True; End; end; if bContainsUppercase = False then ShowMessage('Your password does not contain an uppercase letter.'); if bContainsLowercase = False then ShowMessage('Your password does not contain a lowercase letter.'); if bContainsNumber = False then ShowMessage('Your password does not contain a number letter.'); if (bContainsUppercase = False) OR (bContainsLowercase = False) OR (bContainsNumber = False) then Begin ShowMessage( 'Your password needs to contain at least one uppercase letter, lowercase letter and number.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsPasswordValid := False; End; end; /// ====== Function that checks that the ID Number contains only numbers and is // 13 digits long ============================================================ Function TfrmCreateNewAccount.IsIDNumberValidNumbers: boolean; var sEnteredID: string; i: integer; begin IsIDNumberValidNumbers := True; // Checks that ID Number only contains numbers sEnteredID := lbledtID.Text; i := 0; for i := 1 to Length(sEnteredID) do Begin if NOT(sEnteredID[i] In ['0' .. '9']) then Begin ShowMessage('Your ID number can only contain numbers.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidNumbers := False; end; End; if Length(sEnteredID) <> 13 then Begin ShowMessage('Your ID number must be 13 digits long.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidNumbers := False; End; end; // ============== Checks that the user`s enterd bithdates match ID ========= Function TfrmCreateNewAccount.IsIDNumberValidBirthDate: boolean; { This function determines what the user`s bith date is suppose to be according to his ID, and then checks to see that the match} var iIDday: integer; iIDmonth: integer; sIDyear: string; iIDYear: integer; sIDNumber: string; begin IsIDNumberValidBirthDate := True; // Gets User entered birth information iEnteredBirthDay := StrToInt(spnedtDayOfBirth.Text); iEnteredBirthMonth := cbxMonth.ItemIndex + 1; iEnteredBirthYear := StrToInt(spnedtYearOfBirth.Text); // Gets birth dates from ID Number sIDNumber := lbledtID.Text; iIDday := StrToInt(Copy(sIDNumber, 5, 2)); iIDmonth := StrToInt(Copy(sIDNumber, 3, 2)); sIDyear := Copy(sIDNumber, 1, 2); if StrToInt(sIDyear) IN [0 .. 17] then iIDYear := 2000 + StrToInt(sIDyear) else iIDYear := 1900 + StrToInt(sIDyear); // Compares the two // Day if iEnteredBirthDay <> iIDday then Begin ShowMessage('Your ID number`s day of birth does not match your birth day.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; // Month if iEnteredBirthMonth <> iIDmonth then Begin ShowMessage( 'Your ID number`s month of birth does not match your birth month.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; // Year if iEnteredBirthYear <> iIDYear then Begin ShowMessage ('Your ID number`s year of birth does not match your birth year.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; end; // =============== Checks that the user`s gender matches his ID`s ============= function TfrmCreateNewAccount.IsIDNumberValidGender: boolean; { This function determines what the user`s gender is suppose to be according to his ID, and then checks to see that the match} var sEnteredID: string; begin IsIDNumberValidGender := True; sEnteredID := lbledtID.Text; if NOT(((StrToInt(sEnteredID[7]) > 4) AND (rbMale.Checked = True)) OR ((StrToInt(sEnteredID[7]) < 4) AND (rbFemale.Checked = True))) then begin ShowMessage('Your ID number does not match your gender.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidGender := False; end; end; // =========== Function that validates that the check digit matches // what it should be according to Luhn`s equation ================== Function TfrmCreateNewAccount.IsIDNumberValidCheckDigit: boolean; { This function calculates the what the user`s check digit is suppose to be according to Luhn`s formula, and then checks to see wheter or not it matches the user`s enered ID check digit} var i: integer; iSumOdds: integer; iSumEvens: integer; iTotal: integer; iCheck: integer; sEvens: string; sNumFromEvens: string; sEnteredID: string; begin IsIDNumberValidCheckDigit := True; sEnteredID := lbledtID.Text; // Calculate the sum of all the odd digits in the Id number - excluding the last one i := 1; iSumOdds := 0; while i <= 11 do begin iSumOdds := iSumOdds + StrToInt(sEnteredID[i]); Inc(i, 2); end; // Create a new number: Using the even positions and multiplying the number by 2 sEvens := ''; i := 2; while i <= 12 do begin sEvens := sEvens + sEnteredID[i]; Inc(i, 2); end; sNumFromEvens := IntToStr(StrToInt(sEvens) * 2); // Add up all the digits in this new number iSumEvens := 0; for i := 1 to Length(sNumFromEvens) do begin iSumEvens := iSumEvens + StrToInt(sNumFromEvens[i]); end; // Add the two numbers iTotal := iSumOdds + iSumEvens; // Subtract the second digit form 10 iCheck := (iTotal MOD 10); if iCheck = 0 then begin iCheck := 10; end; iCheck := 10 - iCheck; // Check if the calculated check digit matches the last digit in the ID Number if Not(iCheck = StrToInt(sEnteredID[13])) then Begin ShowMessage ('Your ID Number is incorrect. Please re-enter it and try again.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidCheckDigit := False; End; end; /// ========= Function that calculates the players new player ID /// - primary key in database =========================================== Function TfrmCreateNewAccount.GetPlayersID: integer; var iLarge: integer; begin with dmAccounts do begin tblAccounts.DisableControls; tblAccounts.First; iLarge := -1; while NOT tblAccounts.Eof do begin if tblAccounts['Player ID'] > iLarge then begin iLarge := tblAccounts['Player ID']; end; tblAccounts.Next; end; // while tblAccounts.EnableControls; end; // with Result := iLarge + 1; end; // ================== Function that determines the user`s age ================= Function TfrmCreateNewAccount.DeterminePlayerAge: integer; var iDay: integer; iMonth: integer; iYear: integer; sToday: string; iThisDay, iThisMonth, iThisYear: integer; iAge: integer; begin // Gets User entered birth information iDay := StrToInt(spnedtDayOfBirth.Text); iMonth := cbxMonth.ItemIndex + 1; iYear := StrToInt(spnedtYearOfBirth.Text); // Determine Today`s date sToday := DateToStr(Date); iThisDay := StrToInt(Copy(sToday, 1, 2)); iThisMonth := StrToInt(Copy(sToday, 4, 2)); iThisYear := StrToInt(Copy(sToday, 7, 4)); // Calculate the age the person will become this year iAge := iThisYear - iYear; // Determine if the person has already had his/her birthday if iMonth > iThisMonth then // birthday will be later this year Dec(iAge) else if iMonth = iThisMonth then // test if birthday is later in the month or has already happened if iDay > iThisDay then // bithday will be later in the MonthDays Dec(iAge); Result := iAge; end; /// ======================== Create A New Account Button ====================== procedure TfrmCreateNewAccount.btnSignUpClick(Sender: TObject); { The function of this code is to initialise the checking of all of the criteria and then, if all criteria are met, initialise the creation of a new account, or, if one is not met, initialise the showing of an error message and a help file} var bAllFieldsEntered: boolean; bNamevalid: boolean; bSurnamevalid: boolean; bUsernameExists: boolean; bCellphoneNumberValid: boolean; bPasswordValid: boolean; // Boolaens calling functions for ID Validation bIDNumberValidNumbers: boolean; bIDNumberValidBirthDate: boolean; bIDNumberValidGender: boolean; bIDNumberValidCheckDigit: boolean; // Gets calculated when user`s account gets created iPlayersID: integer; sPlayerGender: string; // Determine from function iPlayersAge: integer; begin // Presence check bAllFieldsEntered := IsAllFieldsPresent; // Calls function if bAllFieldsEntered = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Name Valid bNamevalid := IsNameValid; // Calls function if bNamevalid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Surname Valid bSurnamevalid := IsSurnameValid; // Calls function if bSurnamevalid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Username New bUsernameExists := IsUsernameExists; // Calls function if bUsernameExists = True then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Cellphone Number Valid bCellphoneNumberValid := IsCellphoneNumberValid; if bCellphoneNumberValid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Password Valid bPasswordValid := IsPasswordValid; if bPasswordValid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Password Retype sPleaseRetypePassword := lbledtPasswordRetype.Text; if NOT(sPleaseRetypePassword = sPassword) then begin ShowMessage( 'One of your passwords was entered incorectly and they don`t match.'); if MessageDlg( 'You entered your information incorrectly. Would you like to veiw help as to how to enter your information ?', mtInformation, [mbYes, mbNo], 0) = mrYes then Begin ShowHelp; End Else Begin Exit; End; end; // ========================================================================== // Is ID Numeber valid - Only Numbers bIDNumberValidNumbers := IsIDNumberValidNumbers; if bIDNumberValidNumbers = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Checks that the user`s enterd bithdates match ID bIDNumberValidBirthDate := IsIDNumberValidBirthDate; if bIDNumberValidBirthDate = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Checks that the user`s gender matches his ID bIDNumberValidGender := IsIDNumberValidGender; if bIDNumberValidGender = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Checks that the check digit matches what it should be according to Luhn`s equation bIDNumberValidCheckDigit := IsIDNumberValidCheckDigit; if bIDNumberValidCheckDigit = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ========================================================================== // Get Gender if rbFemale.Checked = True then sPlayerGender := 'F'; if rbMale.Checked = True then sPlayerGender := 'M'; // Generate a new player ID for the user iPlayersID := GetPlayersID; // Determine the user`s age and check that he/she is at least 16 years old iPlayersAge := DeterminePlayerAge; if iPlayersAge < 16 then Begin ShowMessage('Sorry, you are currently ' + IntToStr(iPlayersAge) + ' of age. You need to be at least 16 years old to partake in the event.' ); Exit; End; // Enter the data into the database with dmAccounts do begin dmAccounts.tblAccounts.Last; tblAccounts.Insert; tblAccounts['Player ID'] := iPlayersID; tblAccounts['Username'] := lbledtUsername.Text; tblAccounts['Name'] := lbledtName.Text; tblAccounts['Surname'] := lbledtSurname.Text; tblAccounts['Total Matches Played'] := 0; tblAccounts['Matches Won'] := 0; tblAccounts['Matches Lost'] := 0; tblAccounts['Total Rounds Played'] := 0; tblAccounts['Rounds Won'] := 0; tblAccounts['Rounds Lost'] := 0; tblAccounts['Kills'] := 0; tblAccounts['Deaths'] := 0; tblAccounts['Age'] := iPlayersAge; tblAccounts['Gender'] := sPlayerGender; tblAccounts['Email Adress'] := lbledtEmailAdress.Text; tblAccounts['Cellphone Number'] := lbledtCellphoneNumber.Text; tblAccounts['ID Number'] := lbledtID.Text; tblAccounts['Password'] := lbledtPassword.Text; tblAccounts.Post; end; CreateNewUserMatchHistory; // Creates the text file that saves the user`s match history; ShowMessage('Your account has been created.'); ShowMessage('Sighn Up Seccessfull. Welcome to The Kingdom Of Gamers ' + lbledtName.Text + ' ' + lbledtSurname.Text + '.'); { The function of the next code is to initialize the user`s homepage, since he has successfully created a new account. The variable sLoggedInUser must be set to the user`s username, so that the next forms know which user`s data to use. } frmUserHomePage.sLoggedInUser := lbledtUsername.Text; ResetAll; frmCreateNewAccount.Hide; frmCreateNewAccount.Close; frmUserHomePage.ShowModal; end; /// ======= Create a new match history file in the user`s name ================ procedure TfrmCreateNewAccount.CreateNewUserMatchHistory; var UserMatchHistorty: TextFile; sFileName: string; sUsername: string; sDate: string; begin sDate := DateToStr(Date); sUsername := lbledtUsername.Text; sFileName := 'UserMatchHistory_' + sUsername + '.txt'; AssignFile(UserMatchHistorty, sFileName); Rewrite(UserMatchHistorty); Writeln(UserMatchHistorty, 'Account Created: ' + sDate); Writeln(UserMatchHistorty, '========================================================='); CloseFile(UserMatchHistorty); end; /// ======================= Back Button ======================================= procedure TfrmCreateNewAccount.btnBackClick(Sender: TObject); begin frmCreateNewAccount.Close; end; /// =============== Show user help after incorrect attempt =================== procedure TfrmCreateNewAccount.ShowHelpAfterIncorrectAttempt; begin if MessageDlg( 'You entered your information incorrectly. Would you like to veiw help as to how to enter your information ?', mtInformation, [mbYes, mbNo], 0) = mrYes then Begin ShowHelp; End Else Begin Exit; End; end; /// ======================== Procedure Show Help ============================= procedure TfrmCreateNewAccount.ShowHelp; { This procedure gets called whenever the porgram detects that a user entered some piece of information incorrectly. It asks the user if he/she wants help in entereing their information, by displaying a list of the criteeria that have to be met} var tHelp: TextFile; sLine: string; sMessage: string; begin sMessage := '========================================'; AssignFile(tHelp, 'Help_CreateNewAccount.txt'); try { Code that checks to see if the file about the sponsors can be opened - displays error if not } reset(tHelp); Except ShowMessage('ERROR: The help file could not be opened.'); Exit; end; while NOT Eof(tHelp) do begin Readln(tHelp, sLine); sMessage := sMessage + #13 + sLine; end; sMessage := sMessage + #13 + '========================================'; CloseFile(tHelp); ShowMessage(sMessage); end; /// ======================= Close Form ======================================== procedure TfrmCreateNewAccount.FormClose(Sender: TObject; var Action: TCloseAction); begin ResetAll; frmWelcome.Show; end; /// ======================= Help Button ======================================= procedure TfrmCreateNewAccount.btnCreateNewAccountHelpClick(Sender: TObject); begin ShowHelp; end; /// ========================= Procedure ResetAll ============================== procedure TfrmCreateNewAccount.ResetAll; begin // Name lbledtName.EditLabel.Font.Color := clWhite; lbledtName.EditLabel.Caption := 'Name:'; lbledtName.Text := ''; // Surname lbledtSurname.EditLabel.Font.Color := clWhite; lbledtSurname.EditLabel.Caption := 'Surname:'; lbledtSurname.Text := ''; // Username lbledtUsername.EditLabel.Font.Color := clWhite; lbledtUsername.EditLabel.Caption := 'Username:'; lbledtUsername.Text := ''; // ID lbledtID.EditLabel.Font.Color := clWhite; lbledtID.EditLabel.Caption := 'ID Number:'; lbledtID.Text := ''; // Gender lblGender.Font.Color := clWhite; lblGender.Caption := 'Gender: '; rbFemale.Checked := False; rbMale.Checked := False; // Email lbledtEmailAdress.EditLabel.Font.Color := clWhite; lbledtEmailAdress.EditLabel.Caption := 'Email Adress:'; lbledtEmailAdress.Text := ''; // Cellphone Number lbledtCellphoneNumber.EditLabel.Font.Color := clWhite; lbledtCellphoneNumber.EditLabel.Caption := 'Cellphone Number:'; lbledtCellphoneNumber.Text := ''; // Password lbledtPassword.EditLabel.Font.Color := clWhite; lbledtPassword.EditLabel.Caption := 'Password:'; lbledtPassword.Text := ''; // Please Retype Your Password lbledtPasswordRetype.EditLabel.Font.Color := clWhite; lbledtPasswordRetype.EditLabel.Caption := 'Please Retype Your Password:'; lbledtPasswordRetype.Text := ''; end; end.
unit MathBasics; {$mode objfpc}{$H+}{$interfaces corba} interface uses Classes, SysUtils; type TIMathSet = interface; TIMathObject = interface function IsIn(S:TIMathSet):Boolean; end; TIMathSet = interface(TIMathObject) function Contains(x:TIMathObject):Boolean; function IsSubSet(S:TIMathSet):Boolean; function Complement(S:TIMathSet):TIMathSet; function Cross(S:TIMathSet):TIMathSet; function Intersection(S:TIMathSet):TIMathSet; function Union(S:TIMathSet):TIMathSet; end; TMathRelation = function(const x,y:TIMathObject):Boolean; //operator in(const x:TIMathObject;const S:TIMathSet):Boolean; operator +(const S:TIMathSet;const E:TIMathSet):TIMathSet; operator -(const S:TIMathSet;const E:TIMathSet):TIMathSet; operator *(const S:TIMathSet;const E:TIMathSet):TIMathSet; operator **(const S:TIMathSet;const E:TIMathSet):TIMathSet; implementation //operator in(const x:TIMathObject;const S:TIMathSet):Boolean; //begin // result := x.IsIn(S); //end; operator +(const S:TIMathSet;const E:TIMathSet):TIMathSet; begin result := S.Union(E); end; operator -(const S:TIMathSet;const E:TIMathSet):TIMathSet; begin result := S.Complement(E); end; operator *(const S:TIMathSet;const E:TIMathSet):TIMathSet; begin result := S.Intersection(E); end; operator **(const S:TIMathSet;const E:TIMathSet):TIMathSet; begin result := S.Cross(E); end; end.
Unit IO_Byte; Interface Uses Dos,Declare; Procedure OpenFiles (InF,OutF : String); FUNCTION Endinput: BOOLEAN ; FUNCTION Readbyte: Byte ; PROCEDURE Writebyte( b: INTEGER) ; Type FileType = Record IOFIle : File; CurLength, CurPos : LongInt; end; Var InFile,OutFile : FileType; Implementation Procedure OpenFiles (InF,OutF : String); begin With InFile do begin Assign(IOFile,InF); {$I-} Reset(IOFIle,1); {$I+} If IOResult <> 0 then begin Writeln('ERROR : File ',InF,' Not Found.'); Halt(1); end Else begin CurPos := -1; CurLength := FileSize(IOFile) end; end; With OutFile do begin Assign(IOFile,OutF); {$I-} ReWrite(IOFile,1); {$I+} If IOResult <> 0 then begin Writeln('ERROR # ',IOResult:3,' While Opening File ',OutF); Halt(1); end Else begin CurPos := -1; CurLength := 0; end; end; end; FUNCTION Endinput: BOOLEAN ; BEGIN With InFile do begin IF (CurPos+1 = CurLength) THEN Endinput := true ELSE Endinput := false end; END { Endinput } ; FUNCTION Readbyte: Byte ; VAR Temp : Byte; BEGIN IF (EndInput) THEN ReadByte := 0 Else begin Inc(InFile.CurPos); BlockRead(InFile.IOFile,Temp,1); ReadByte := Temp; end; end; PROCEDURE Writebyte (b: INTEGER) ; BEGIN With OutFile do begin BlockWrite(IOFile,b,1); Inc(CurPos); Inc(CurLength); end; END { Writebyte } ; end. 
unit MediaEncodeMgr; interface uses Windows, MediaCommon; const CLSID_CFileFormatInfos: TGUID = '{f1eb87e5-6940-42b6-b4ce-208aa7695819}'; IID_IFileFormatInfos: TGUID = '{5C9908D7-FDCD-4827-BC0B-94CB3ECCF8BD}'; IID_IFileFormatInfo: TGUID = '{72BE4AD5-A6B3-4c75-92E2-15BEACE01F72}'; IID_IEncoderInfos: TGUID = '{A6F06C44-8115-47c5-A98A-F2E44744B378}'; IID_IEncoderInfo: TGUID = '{D5B71CE2-3957-413c-9DF4-2587CBD20BE4}'; SEncMgrAPI = 'WS_EncMgr.dll'; type IEncoderInfo = interface(IUnknown) ['{D5B71CE2-3957-413c-9DF4-2587CBD20BE4}'] function GetFourCC(): UINT; stdcall; function GetName(var pName: WideString): HRESULT; stdcall; function GetDescription(var pDescription: WideString): HRESULT; stdcall; end; IEncoderInfos = interface(IUnknown) ['{A6F06C44-8115-47c5-A98A-F2E44744B378}'] function GetCount(): Integer; stdcall; function GetItem(nIndex: Integer; var pEncoderInfo: IEncoderInfo): HRESULT; stdcall; end; IFileFormatInfo = interface(IUnknown) ['{72BE4AD5-A6B3-4c75-92E2-15BEACE01F72}'] function GetFourCC(): UINT; stdcall; function GetExName(var pName: UnicodeString): HRESULT; stdcall; function GetFormatName(var pFormatName: UnicodeString): HRESULT; stdcall; function GetDescription(var pDescription: UnicodeString): HRESULT; stdcall; function GetAudioEncoderInfos(var pEncoderInfos: IEncoderInfos): HRESULT; stdcall; function GetVideoEncoderInfos(var pEncoderInfos: IEncoderInfos): HRESULT; stdcall; end; IFileFormatInfos = interface(IUnknown) ['{5C9908D7-FDCD-4827-BC0B-94CB3ECCF8BD}'] function GetCount(): Integer; stdcall; function GetItem(nIndex: Integer; var pFileFormatInfo: IFileFormatInfo): HRESULT; stdcall; end; const RESERVEDSIZE = 1024; type //WMV格式的扩展参数 WMV_VideoParamEx = record Quality: Longint; // 质量等级 0-4 4为最好 默认为0 VBRType: Longint; // 可变长编码类型 m_VBRType 0 1 默认为0 动态码率VBR 0 平均码率ABR 1(暂时不支持) MaxBuffer: Longint; // 缓冲大小 0~10秒 默认为0 IFrameInterval: Longint; // 默认为25 end; VC1_VideoParamEx = record dwProfile: Cardinal; dwComplexityLevel: Cardinal; dwQP: Cardinal; dwMaxKeyFrameDistance: Cardinal; dwNumOfBFrames: Cardinal; dwRateControlMode: Cardinal; dwVBVBufferInBytes: Cardinal; dPeakBitRate: Double; end; Xvid_EncodeParamEx = record Quality: Integer; VHQMODE: Integer; end; TVideoParamEx = record dwFourCC: DWORD; // 视频编码器 FourCC : '1VMW'/'2VMW'/'3VMW' /'DIVX'/'462H' case Integer of 0: (wmvParamEx: WMV_VideoParamEx); 1: (vc1ParamEx: VC1_VideoParamEx); 2: (xvidParamEx: Xvid_EncodeParamEx); 3: (reserved : array[0..RESERVEDSIZE-1] of Longint); //保留字段 为了分配固定大小结构 end; TAudioParamEx = record dwFourCC: DWORD; // 音频编码器 FourCC : '1AMW'/'2AMW'/'3AMW' /' 3PM' case Integer of 0: (reserved : array[0..RESERVEDSIZE div 2-1] of Longint); //保留字段 为了分配固定大小结构 end; PEncodeParamEx = ^TEncodeParamEx; TEncodeParamEx = record dwFourCC: DWORD; // 文件格式FourCC useflg: Longint; // 有效标志 0 未使用 1 视频扩展参数 2音频扩展参数 3 音视频扩展参数 m_TwoPass: Longint; // 二次编码标志 0 一次编码; 1 二次编码只送一次数据; 2 二次编码送二次数据 默认为0 videoEx: TVideoParamEx; // 视频扩展参数 audioEx: TAudioParamEx; // 音频扩展参数 end; // 视频参数 PVideoParam = ^TVideoParam; TVideoParam = record dwFourCC : DWORD; // 视频编码器 FourCC : 'V2PM' nWidth : Longint; // 分辨率宽度 720 nHeight : Longint; // 分辨率高度 480或576(国内) dFrameRate : double; // 帧率 0表示自动选择 30000.0 / 1001 或25(国内) nBitrate : Longint; // 码率 bps (恒定码率、可变最小码率) 9800,000或4000,000 bIsVBR : BOOL; // 是否使用变码率 nMaxBitrate : Longint; // 最大码率 nResizeStyle : IMAGE_RESIZE_METHOD; // 图像缩放方式 nInterpolation : IMAGE_INTERPOLATION; // 图像插值算法 dwCompression : DWORD; // 图像格式 ‘21VY’ nBitsDepth : Longint; // 图像位深度 12 //=============== MPEG 编码器参数 ===========================// // 使用Mpeg编码请参考 mpeg_param.pas // dwFormat : DWORD; // 编码格式 // dwNorm : DWORD; // 电视制式 // dwAspect : DWORD; // 比例 // bFieldEnc : BOOL; // 是否使用交错模式 // //=============== MPEG 编码器参数 ===========================// VideoParamEx: TEncodeParamEx; end; // 音频参数 PAudioParam = ^TAudioParam; TAudioParam = record dwFourCC : DWORD; // 音频编码器 FourCC : ' 3CA' nSampleRate : Longint; // 采样率 Hz DVD默认48000 nChannels : Longint; // 声道数量 2 nBitrate : Longint; // 码率 bps (恒定码率、可变最小码率)128,000 bIsVBR : BOOL; // 是否使用变码率 nMaxBitrate : Longint; // 最大码率 nBitsPerSample : Longint; // Number of bits per sample of mono data 16 end; // 编码参数 PEncodeParam = ^TEncodeParam; TEncodeParam = record Video : TVideoParam; // 视频参数 Audio : TAudioParam; // 音频参数 bVideoDisable : BOOL; // 禁用视频 bAudioDisable : BOOL; // 禁用音频 // case Longint of // 0: (format : EncoderFormat); // 文件格式 // 1: (dwFourCC: DWORD); //视频编码器 dwFourCC: DWORD; // 文件格式FourCC:' 4PM' ’2gpm' end; PEncoderInfo = ^TEncoderInfo; TEncoderInfo = record dwFourCC : DWORD; szEncName : array [0..63] of WideChar; szDescription : array [0..127] of WideChar; end; PPEncoderInfo = ^PEncoderInfo; PFileFormatInfo = ^TFileFormatInfo; TFileFormatInfo = record dwFourCC : DWORD; szExtName : array [0..9] of WideChar; szFormatName : array [0..63] of WideChar; szDescription : array [0..127] of WideChar; nAudioEncs : Longint; nVideoEncs : Longint; ppAudioEncInfos : PPEncoderInfo; ppVideoEncInfos : PPEncoderInfo; end; // 应用程序启动时调用 TFCInitPlugins = function () : BOOL; stdcall; // 应用程序退出时调用 TFCUninitPlugins = procedure (); stdcall; // 获取已加载支持的所有文件格式,需在FCInitPlugins()调用成功后才可调用 TFCGetFileFormatInfos = function () : PFILEFORMATINFO; stdcall; TMediaEncodeMgrAPI = record private FAPIHandle: THandle; FFCInitPlugins: TFCInitPlugins; FFCUninitPlugins: TFCUninitPlugins; FPluginsInited: BOOL; FFileFormatInfoHead: PFileFormatInfo; public function Init: Boolean; procedure Free; function FCInitPlugins() : BOOL; procedure FCUninitPlugins(); function FCGetFileFormatInfos() : PFILEFORMATINFO; end; var MediaEncodeMgrAPI: TMediaEncodeMgrAPI; implementation uses MediaEncode; const SFCInitPlugins = PAnsiChar(5); SFCUninitPlugins = PAnsiChar(6); { TMediaEncodeMgrAPI } function TMediaEncodeMgrAPI.FCGetFileFormatInfos: PFILEFORMATINFO; begin end; function TMediaEncodeMgrAPI.FCInitPlugins: BOOL; var pFileFormatInfos: IFileFormatInfos; pFileFormatInfo: IFileFormatInfo; pVidEncoderInfos: IEncoderInfos; pVidEncoderInfo: IEncoderInfo; pAudEncoderInfos: IEncoderInfos; pAudEncoderInfo: IEncoderInfo; pEncInfo: PEncoderInfo; pEnc: PPEncoderInfo; I, J: Integer; pStr: UnicodeString; begin Result:=FPluginsInited; if not FPluginsInited then begin if Init then begin if Assigned(FFCInitPlugins) then begin InterlockedExchange(Longint(FPluginsInited), Ord(FFCInitPlugins())); Result := FPluginsInited; if Result then begin pFileFormatInfos := nil; WSCoCreateInstance(CLSID_CFileFormatInfos, nil, 0, IID_IFileFormatInfos, pFileFormatInfos); if Assigned(pFileFormatInfos) then begin FFileFormatInfoHead := GetMemory((pFileFormatInfos.GetCount + 1) * SizeOf(TFileFormatInfo)); for I := 0 to pFileFormatInfos.GetCount - 1 do begin pFileFormatInfo := nil; pFileFormatInfos.GetItem(I, pFileFormatInfo); if Assigned(pFileFormatInfo) then begin with FFileFormatInfoHead^ do begin dwFourCC := pFileFormatInfo.GetFourCC; pFileFormatInfo.GetExName(pStr); StringToWideChar(pStr, szExtName, length(pStr)); pFileFormatInfo.GetFormatName(pStr); StringToWideChar(pStr, szFormatName, Length(pStr)); pFileFormatInfo.GetDescription(pStr); StringToWideChar(pStr, szDescription, Length(pStr)); pVidEncoderInfos := nil; pFileFormatInfo.GetVideoEncoderInfos(pVidEncoderInfos); if Assigned(pVidEncoderInfos) then begin nVideoEncs := pVidEncoderInfos.GetCount; if nVideoEncs > 0 then begin ppVideoEncInfos := GetMemory(nVideoEncs * SizeOf(PEncoderInfo)); pEnc := ppVideoEncInfos; for J := 0 to nVideoEncs - 1 do begin pVidEncoderInfo := nil; pVidEncoderInfos.GetItem(J, pVidEncoderInfo); if Assigned(pVidEncoderInfo) then begin pEncInfo := pEnc^; pEncInfo := GetMemory(SizeOf(TEncoderInfo)); with pEncInfo^ do begin dwFourCC := pVidEncoderInfo.GetFourCC; pVidEncoderInfo.GetName(pStr); StringToWideChar(pStr, szEncName, Length(pStr)); pVidEncoderInfo.GetDescription(pStr); StringToWideChar(pStr, szDescription, Length(pStr)); end; Inc(pEnc); pVidEncoderInfo._Release; end; end; ppAudioEncInfos := GetMemory(nAudioEncs * SizeOf(PEncoderInfo)); pEnc := ppAudioEncInfos; for J := 0 to nAudioEncs - 1 do begin pAudEncoderInfo := nil; pAudEncoderInfos.GetItem(J, pAudEncoderInfo); if Assigned(pAudEncoderInfo) then begin pEncInfo := pEnc^; pEncInfo := GetMemory(SizeOf(TEncoderInfo)); with pEncInfo^ do begin dwFourCC := pAudEncoderInfo.GetFourCC; pAudEncoderInfo.GetName(pStr); StringToWideChar(pStr, szEncName, Length(pStr)); pAudEncoderInfo.GetDescription(pStr); StringToWideChar(pStr, szDescription, Length(pStr)); end; Inc(pEnc); pAudEncoderInfo._Release; end; end; end; pVidEncoderInfos._Release; end; end; Inc(FFileFormatInfoHead); end; end; end; end; end; end; end; end; procedure TMediaEncodeMgrAPI.FCUninitPlugins; begin if FPluginsInited then begin if Assigned(FFCUninitPlugins) then FFCUninitPlugins; InterlockedExchange(Longint(FPluginsInited), 0); end; end; procedure TMediaEncodeMgrAPI.Free; begin if FAPIHandle <> 0 then begin FCUninitPlugins; // 卸载插件 FreeLibrary(FAPIHandle); FAPIHandle := 0; FillChar(Self, SizeOf(Self), 0); end; end; function TMediaEncodeMgrAPI.Init: Boolean; begin if FAPIHandle=0 then begin FAPIHandle := LoadLibrary(SEncMgrAPI); if FAPIHandle <> 0 then begin FFCInitPlugins := GetProcAddress(FAPIHandle, (SFCInitPlugins)); FFCUninitPlugins := GetProcAddress(FAPIHandle, (SFCUninitPlugins)); end else RaiseLoadLibError(SEncMgrAPI); end; Result := FAPIHandle<>0; end; end.
unit UDisplayManager; interface uses SysUtils, Windows, UxlWindow, UxlExtClasses, UxlClasses, UxlWinClasses, UQueryManager, UDisplay, UWordBox; type TTestModeType = (tmtExpDelay, tmtWordDelay, tmtRandom); TDisplayManager = class (TxlInterfacedObject, IOptionObserver, ICommandExecutor, IMemorizer) private FQueryMan: TQueryManager; FDisplayFactory: TDisplayFactory; FDisplay: TDisplaySuper; FSwitchTimer: TxlTimer; FDelayTimer: TxlTimer; FDisplayMode: TDisplayMode; FFullScreen: boolean; FTrackMouse: boolean; FActive: boolean; FTestMode: boolean; FTestModeCycle: integer; FTestModeType: TTestModeType; FWord: TWord; procedure f_DetermineDisplay (); procedure f_OnSwitchTimer (Sender: TObject); procedure f_OnDelayTimer (Sender: TObject); public constructor Create (AWin: TxlWindow); destructor Destroy (); override; procedure Pause (); procedure Resume (); procedure OptionChanged (); procedure ExecuteCommand (opr: word); function CheckCommand (opr: word): boolean; procedure SaveMemory (); procedure RestoreMemory (); end; implementation uses Messages, UxlMath, UGlobalObj, Resource; constructor TDisplayManager.Create (AWin: TxlWindow); begin FQueryMan := TQueryManager.Create (AWin); FQueryMan.OnBoxChange := f_OnSwitchTimer; FDisplayFactory := TDisplayFactory.Create (AWin); FSwitchTimer := TimerCenter.NewTimer; FSwitchTimer.OnTimer := f_OnSwitchTimer; FDelayTimer := TimerCenter.NewTimer; FDelayTimer.OnTimer := f_OnDelayTimer; OptionMan.AddObserver (self); CommandMan.AddExecutor (self); MemoryMan.AddObserver (self); end; destructor TDisplayManager.Destroy (); begin MemoryMan.RemoveObserver (self); CommandMan.RemoveExecutor (self); OptionMan.RemoveObserver (self); TimerCenter.ReleaseTimer (FSwitchTimer); TimerCenter.ReleaseTimer (FDelayTimer); FDisplayFactory.Free; FQueryMan.Free; inherited; end; procedure TDisplayManager.Pause (); begin FSwitchTimer.Stop; end; procedure TDisplayManager.Resume (); begin if FActive then FSwitchTimer.Start; end; procedure TDisplayManager.OptionChanged (); begin FDisplayMode := OptionMan.Options.DisplayMode; f_DetermineDisplay; FSwitchTimer.Interval := OptionMan.Options.SwitchWordInterval * 1000; FDelayTimer.Interval := OptionMan.Options.TestModeDelay * 1000; FTestModeType := OptionMan.Options.TestModeType; if OptionMan.Options.AutoTestMode then FTestModeCycle := OptionMan.Options.TestModeCycle else FTestModeCycle := 0; end; procedure TDisplayManager.f_DetermineDisplay (); var dm: TDisplayMode; begin if not FActive then dm := dmNone else if FDisplayMode = dmEmbed then dm := dmEmbed else if FFullScreen then dm := dmFullScreen else if FTrackMouse then dm := dmTrack else dm := dmFixed; FDisplay := FDisplayFactory.GetDisplay (dm); // CommandMan.CheckCommands; CommandMan.ItemEnabled[m_fullscreen] := CheckCommand (m_fullscreen); CommandMan.ItemEnabled[m_trackmouse] := CheckCommand (m_trackmouse); if FActive then begin FSwitchTimer.Start; f_OnSwitchTimer (self); end; end; procedure TDisplayManager.ExecuteCommand (opr: word); begin case opr of m_start: begin FActive := not CommandMan.ItemChecked [m_start]; CommandMan.ItemChecked [m_start] := FActive; FSwitchTimer.Enabled := FActive; f_DetermineDisplay; end; m_testmode: begin FTestMode := not CommandMan.ItemChecked [m_testmode]; CommandMan.ItemChecked [m_testmode] := FTestMode; end; m_fullscreen: begin FFullScreen := not CommandMan.ItemChecked [m_fullscreen]; CommandMan.ItemChecked [m_fullscreen] := FFullScreen; f_DetermineDisplay; end; m_trackmouse: begin FTrackMouse := not CommandMan.ItemChecked [m_trackmouse]; CommandMan.ItemChecked [m_trackmouse] := FTrackMouse; f_DetermineDisplay; end; m_next: if FDelayTimer.Enabled then FDelayTimer.TimerEvent else begin FSwitchTimer.TimerEvent; FSwitchTimer.Reset; // 重新计时 end; m_Copy: begin Clipboard.TExt := FDisplay.ExportWord; ProgTip.ShowTip ('当前项已复制到剪贴板!'); end; end; end; function TDisplayManager.CheckCommand (opr: word): boolean; begin case opr of m_fullscreen: result := FDisplayMode <> dmEmbed; m_trackmouse: result := (FDisplayMode <> dmEmbed) and (not FFullScreen); else result := true; end; end; procedure TDisplayManager.SaveMemory (); begin MemoryMan.TestMode := FTestMode; MemoryMan.Started := FActive; MemoryMan.TrackMouse := FTrackMouse; end; procedure TDisplayManager.RestoreMemory (); begin if MemoryMan.TestMode then ExecuteCommand (m_testmode); if MemoryMan.Started then ExecuteCommand (m_start); if MemoryMan.TrackMouse then ExecuteCommand (m_trackmouse); end; procedure TDisplayManager.f_OnSwitchTimer (Sender: TObject); var o_word: TWord; i: integer; {$J+} const cCycleCount: integer = 0; {$J-} // 记忆前一次切换时的 Cycle 数 begin try FWord := FQueryMan.GetWord; o_word := FWord; if (FTestModeCycle > 0) then begin if (cCycleCount < FTestModeCycle) and (FQueryMan.CycleCount >= FTestModeCycle) then // 自动进入测验模式 FTestMode := true else if (cCycleCount >= FTestModeCycle) and (FQueryMan.CycleCount < FTestModeCycle) then // 自动退出测验模式 FTestMode := false; CommandMan.ItemChecked [m_testmode] := FTestMode; end; cCycleCount := FQueryMan.CycleCount; if FTestMode and (o_word.word <> '') and (o_word.exp <> '') then begin case FTestModeType of tmtExpDelay: o_word.Exp := '?'; tmtWordDelay: o_Word.Word := '? '; else begin i := RandomInt (0, 1); if i = 0 then o_word.Word := '? ' else o_word.Exp := '?'; end; end; if FDelayTimer.Interval < FSwitchTimer.Interval then FDelayTimer.Start; end; FDisplay.ShowWord (o_word); except On E: Exception do FDisplay.ShowString (E.Message); end; end; procedure TDisplayManager.f_OnDelayTimer (Sender: TObject); begin FDelayTimer.Stop; FDisplay.ShowWord (FWord); end; end.
unit UMensagens; interface resourcestring //Geral STR_ATENCAO = 'Atenção'; STR_CAPTION_ABA_CONSULTAS = '%d - %s...'; STR_TODOS = 'Todos'; STR_ATUALIZADO = 'atualizado(a)'; STR_GRAVADO = 'gravado(a)'; STR_EXCLUIDO = 'excluido(a)'; STR_OPERACAO_COM_SUCESSO = '%s com código %d %s com sucesso.'; STR_ENTIDADE_NAO_ENCONTRADA = '%s com código %d não foi encontrado(a)'; //Entidade STR_ENTIDADE_GRAVADA_COM_SUCESSO = '%s gravado(a) com sucesso! Código gerado: %d.'; STR_ENTIDADE_ATUALIZADO_COM_SUCESSO = '%s atualizado(a) com sucesso!'; STR_ENTIDADE_DESEJA_EXCLUIR = 'Deseja realmente excluir este(a) %s?'; //CRUD STR_CRUD_CABECALHO = 'Cadastro de %s'; //Transação STR_JA_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel abrir uma nova transação! Motivo: Já existe uma transação ativa.'; STR_NAO_EXISTE_TRANSACAO_ATIVA = 'Não foi possivel %s a transação! Motivo: Não existe uma transação ativa.'; STR_VALIDA_TRANSACAO_ATIVA = 'Operação abortada! Motivo: Para realizar esta operação é necessário ter uma transação ativa.'; STR_ABORTAR = 'abortar'; STR_FINALIZAR = 'finalizar'; //Material STR_MATERIAL_DESCRICAO_NAO_INFORMADO = 'Campo DESCRIÇÃO não informado'; STR_MATERIAL_VALOR_UNITARIO_NAO_INFORMADO = 'Campo VALOR UNITÁRIO não informado'; //Cliente STR_CLIENTE_NOME_NAO_INFORMADO = 'Campo NOME não informado'; STR_CLIENTE_SOLICITANTE_NAO_INFORMADO = 'Campo SOLICITANTE não informado'; STR_CLIENTE_CPF_CNPJ_NAO_INFORMADO = 'Campo CPF ou CNPJ não informado'; STR_CLIENTE_TELEFONE_NAO_INFORMADO = 'Campo TELEFONE não informado'; STR_CLIENTE_CIDADE_NAO_INFORMADO = 'Campo CIDADE não informado'; STR_CLIENTE_ENDERECO_NAO_INFORMADO = 'Campo ENDEREÇO não informado'; STR_CLIENTE_CPF = 'CPF'; STR_CLIENTE_CNPJ = 'CNPJ'; //Os STR_OS_CLIENTE_NAO_INFORMADO = 'Campo CLIENTE não informado'; STR_OS_EQUIPAMENTO_NAO_INFORMADO = 'Campo EQUIPAMENTO não informado'; STR_OS_DATA_ENTRADA_NAO_INFORMADO = 'Campo DATA DE ENTRADA não informado'; //Cidade STR_CIDADE_NOME_NAO_INFORMADO = 'Campo CIDADE não informado'; STR_CIDADE_ESTADO_NAO_INFORMADO = 'Campo ESTADO não informado'; //Estado STR_ESTADO_PAIS_NAO_INFORMADO = 'Campo PAÍS não informado'; STR_ESTADO_ESTADO_NAO_INFORMADO = 'Campo ESTADO não informado'; STR_ESTADO_UF_NAO_INFORMADO = 'Campo UF não informado'; //Pais STR_PAIS_NAO_INFORMADO = 'Campo PAÍS não informado'; STR_SIGLA_NAO_INFORMADO = 'Campo SIGLA não informado'; //Equipamento STR_EQUIPAMENTO_NOME_NAO_INFORMADO = 'Campo NOME não informado'; STR_EQUIPAMENTO_MARCA_NAO_INFORMADO = 'Campo MARCA não informado'; STR_EQUIPAMENTO_N_SERIE_NAO_INFORMADO = 'Campo Nº SÉRIE não informado'; //Tecnico STR_TECNICO_NOME_NAO_INFORMADO = 'Campo NOME não inforamado'; STR_TECNICO_VALOR_HORA_NAO_INFORMADO = 'Campo VALOR HORA não informado'; //Usuario STR_SENHA_NAO_SEGURA = 'Senha digitada não é segura, senha deve ter no mínimo %d caracteres'; STR_SENHAS_NAO_CONFEREM = 'Senhas não conferem'; STR_USUARIO_NOME_NAO_INFORMADO = 'Nome do usuário não foi informado'; STR_SENHA_ATUAL_NAO_CONFERE = 'Senha atual não confere'; STR_USUSARIO_DESCRICAO_SERVICO_NAO_INFORMADO = 'Campo DESCRIÇÃO SERVIÇO não informado'; //Login STR_USUARIO_OU_SENHA_SAO_INVALIDOS = 'Usuário ou senha são inválidos'; implementation end.
unit ScreenIO; var TextColor: Word = 0xF000; TextCursor: Word = 0x0; LineWidth: Word = 32; KeyOffset: Word = 0; procedure PrintLineBreak(); begin TextCursor := TextCursor + (LineWidth - TextCursor mod LineWidth); end; procedure Print(AText: string); var LChar: Word; LVid: Word; begin LVid := 0x8000 + TextCursor; while Pointer(AText)^ > 0 do begin if Pointer(AText)^ = 10 then begin PrintLineBreak(); LVid := 0x8000 + TextCursor; end else begin LChar := TextColor + Pointer(AText)^; LVid^ := LChar; LVid := LVid + 1; TextCursor := TextCursor + 1; end; Word(AText) := Word(AText) + 1; end; end; procedure PrintLn(AText: string); begin Print(AText); PrintLineBreak(); end; function GetKey(): Word; asm set b, [KeyOffset] add b, 0x9000 :wait ife [b], 0 set pc, wait set a, [b] set [b], 0 add [KeyOffset], 1 and [KeyOffset], 0xf end; procedure PrintChar(AChar: Word); var LVid: Word; begin LVid := 0x8000 + TextCursor; LVid^ := AChar + TextColor; TextCursor := TextCursor + 1; end; procedure PrintNumber(ANumber: Word); asm set x, 0 :IntToStrLoop set b, a mod b, 10 add b, 48 set push, b div a, 10 add x, 1 ifn a, 0 set pc, IntToStrLoop set y, 0 :PrintNumberLoop set a, pop set push, x set push, y jsr PrintChar set y, pop set x, pop add y, 1 ifg x, y set pc, PrintNumberLoop end; procedure PrintHex(ANumber: Word); asm set x, 0 :IntToStrLoop set b, a mod b, 16 ifg b, 9 set pc, HexChar add b, 48 set pc, DoPush :HexChar add b, 55 :DoPush set push, b div a, 16 add x, 1 ifn a, 0 set pc, IntToStrLoop set y, 0 :PrintNumberLoop set a, pop set push, x set push, y jsr PrintChar set y, pop set x, pop add y, 1 ifg x, y set pc, PrintNumberLoop end; procedure CLS(AColor: Word); asm set i, 0x8000 :loop set [i], a add i, 1 ifg 0x8180, i set pc, loop set [TextCursor], 0 end; end.
(* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Contributor(s): * Jody Dawkins <jdawkins@delphixtreme.com> *) unit Specifiers; interface uses SysUtils, Variants, Modifiers, BaseObjects, dSpecIntf; type TBaseSpecifier = class(TFailureReportingObject, ISpecifier, IShouldHelper, IBeHelper) private FValueName: string; protected FNegated: Boolean; function DoEvaluation(Failed : Boolean; const FailureMessage, SpecName : string; SpecValue : Variant) : IModifier; function CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string) : IModifier; virtual; function CreateNewShouldHelper(Negated : Boolean) : IShouldHelper; dynamic; procedure NegateMessage(var Msg : string); public constructor Create(ACallerAddress : Pointer; AContext : IContext; const AValueName : string; Negated : Boolean = False); reintroduce; destructor Destroy; override; { ISpecifier } function Should : IShouldHelper; function Not_ : IShouldHelper; function Be : IBeHelper; { IShouldHelper } function Equal(Expected : Variant) : IModifier; virtual; function DescendFrom(Expected : TClass) : IModifier; virtual; function Implement(Expected : TGUID) : IModifier; virtual; function Support(Expected : TGUID) : IModifier; virtual; function StartWith(Expected : Variant) : IModifier; virtual; function Contain(Expected : Variant) : IModifier; virtual; function EndWith(Expected : Variant) : IModifier; virtual; { IBeHelper } function OfType(Expected : TClass) : IModifier; virtual; function Nil_ : IModifier; virtual; function True : IModifier; virtual; function False : IModifier; virtual; function GreaterThan(Expected : Variant) : IModifier; virtual; function LessThan(Expected : Variant) : IModifier; virtual; function AtLeast(Expected : Variant) : IModifier; virtual; function AtMost(Expected : Variant) : IModifier; virtual; function Assigned : IModifier; virtual; function ImplementedBy(Expected : TClass) : IModifier; virtual; function Numeric : IModifier; virtual; function Alpha : IModifier; virtual; function AlphaNumeric : IModifier; virtual; function Odd : IModifier; virtual; function Even : IModifier; virtual; function Positive : IModifier; virtual; function Negative : IModifier; virtual; function Prime : IModifier; virtual; function Composite : IModifier; virtual; function Zero : IModifier; virtual; function Empty : IModifier; virtual; end; TIntegerSpecifier = class(TBaseSpecifier) private FActual: Integer; public constructor Create(Actual: Integer; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Equal(Expected : Variant) : IModifier; override; function GreaterThan(Expected : Variant) : IModifier; override; function LessThan(Expected : Variant) : IModifier; override; function AtLeast(Expected : Variant) : IModifier; override; function AtMost(Expected : Variant) : IModifier; override; function Odd : IModifier; override; function Even : IModifier; override; function Positive : IModifier; override; function Negative : IModifier; override; function Prime : IModifier; override; function Composite : IModifier; override; function Zero : IModifier; override; end; TBooleanSpecifier = class(TBaseSpecifier) private FActual: Boolean; public constructor Create(Actual: Boolean; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Equal(Expected : Variant) : IModifier; override; function True : IModifier; override; function False : IModifier; override; end; TFloatSpecifier = class(TBaseSpecifier) private FExpected: Extended; FActual: Extended; protected function CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string) : IModifier; override; public constructor Create(Actual: Extended; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Equal(Expected : Variant) : IModifier; override; function GreaterThan(Expected : Variant) : IModifier; override; function LessThan(Expected : Variant) : IModifier; override; function AtLeast(Expected : Variant) : IModifier; override; function AtMost(Expected : Variant) : IModifier; override; function Positive : IModifier; override; function Negative : IModifier; override; function Zero : IModifier; override; end; TStringSpecifier = class(TBaseSpecifier) private FActual: string; FExpected: string; protected function CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string) : IModifier; override; public constructor Create(Actual: string; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Equal(Expected : Variant) : IModifier; override; function Numeric : IModifier; override; function Alpha : IModifier; override; function AlphaNumeric : IModifier; override; function StartWith(Expected : Variant) : IModifier; override; function Contain(Expected : Variant) : IModifier; override; function EndWith(Expected : Variant) : IModifier; override; function Empty : IModifier; override; end; TObjectSpecifier = class(TBaseSpecifier) private FActual: TObject; public constructor Create(Actual: TObject; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function OfType(Expected : TClass) : IModifier; override; function Nil_ : IModifier; override; function DescendFrom(Expected : TClass) : IModifier; override; function Assigned : IModifier; override; function Implement(Expected : TGUID) : IModifier; override; function Support(Expected : TGUID) : IModifier; override; end; TPointerSpecifier = class(TBaseSpecifier) private FActual: Pointer; public constructor Create(Actual, ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Nil_ : IModifier; override; function Assigned : IModifier; override; end; TClassSpecifier = class(TBaseSpecifier) private FActual: TClass; public constructor Create(Actual: TClass; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function OfType(Value : TClass) : IModifier; override; function DescendFrom(Expected : TClass) : IModifier; override; end; TDateTimeSpecifier = class(TBaseSpecifier) private FActual: TDateTime; public constructor Create(Actual: TDateTime; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); reintroduce; function Equal(Expected : Variant) : IModifier; override; function LessThan(Expected : Variant) : IModifier; override; function GreaterThan(Expected : Variant) : IModifier; override; function AtLeast(Expected : Variant) : IModifier; override; function AtMost(Expected : Variant) : IModifier; override; end; TInterfaceSpecifier = class(TBaseSpecifier) private FActual: IInterface; public constructor Create(Actual : IInterface; ACallerAddress : Pointer; AContext : IContext; const AValueName : string); reintroduce; destructor Destroy; override; function Support(Expected : TGUID) : IModifier; override; function Assigned : IModifier; override; function Nil_ : IModifier; override; function ImplementedBy(Expected : TClass) : IModifier; override; end; implementation uses dSpecUtils, FailureMessages; { TBaseSpecifier } function TBaseSpecifier.Composite: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Composite', null); end; function TBaseSpecifier.Contain(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Containt', Expected); end; constructor TBaseSpecifier.Create(ACallerAddress: Pointer; AContext: IContext; const AValueName : string; Negated: Boolean); begin inherited Create(ACallerAddress, AContext); FNegated := Negated; FValueName := AValueName; end; function TBaseSpecifier.CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string): IModifier; begin Result := TModifier.Create(Self, RemoveLastFailure, FailureMessage, FCallerAddress, FContext); end; function TBaseSpecifier.CreateNewShouldHelper(Negated: Boolean): IShouldHelper; begin Result := Self.Create(FCallerAddress, FContext, FValueName, Negated); end; destructor TBaseSpecifier.Destroy; begin FCallerAddress := nil; try FContext.ReportFailures finally inherited Destroy; end; end; function TBaseSpecifier.DoEvaluation(Failed: Boolean; const FailureMessage, SpecName: string; SpecValue : Variant): IModifier; var Msg: string; begin Msg := FailureMessage; if FNegated then begin Failed := not Failed; NegateMessage(Msg); end; if FValueName <> '' then Msg := FValueName + ' ' + Msg; if Failed then Fail(Msg); Result := CreateModifier(Failed = System.True, Msg); FContext.DocumentSpec(SpecValue, SpecName); end; function TBaseSpecifier.Should: IShouldHelper; begin Result := Self; end; function TBaseSpecifier.StartWith(Expected : Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'StartWith', Expected); end; function TBaseSpecifier.Support(Expected: TGUID): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Support', GUIDToString(Expected)); end; function TBaseSpecifier.Alpha: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Alpha', null); end; function TBaseSpecifier.AlphaNumeric: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'AlphaNumeric', null); end; function TBaseSpecifier.Assigned: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Assigned', null); end; function TBaseSpecifier.AtLeast(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'AtLeast', Expected); end; function TBaseSpecifier.AtMost(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'AtMost', Expected); end; function TBaseSpecifier.Be: IBeHelper; begin Result := Self; FContext.DocumentSpec(null, 'Be'); end; function TBaseSpecifier.False : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'False', null); end; procedure TBaseSpecifier.NegateMessage(var Msg: string); var NegatedMsg: string; begin NegatedMsg := StringReplace(Msg, 'should ', 'should not ', [rfReplaceAll]); NegatedMsg := StringReplace(NegatedMsg, 'didn''t', 'did', [rfReplaceAll]); NegatedMsg := StringReplace(NegatedMsg, 'wasn''t', 'was', [rfReplaceAll]); Msg := NegatedMsg; end; function TBaseSpecifier.Negative: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Negative', null); end; function TBaseSpecifier.Nil_ : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Nil', null); end; function TBaseSpecifier.Odd: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Odd', null); end; function TBaseSpecifier.OfType(Expected: TClass) : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'OfType', Expected.ClassName); end; function TBaseSpecifier.Positive: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Positive', null); end; function TBaseSpecifier.Prime: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Prime', null); end; function TBaseSpecifier.True : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'True', null); end; function TBaseSpecifier.Zero: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Zero', null); end; function TBaseSpecifier.DescendFrom(Expected: TClass) : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'DecendFrom', Expected.ClassName); end; function TBaseSpecifier.Empty: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Empty', null); end; function TBaseSpecifier.EndWith(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'EndWith', Expected); end; function TBaseSpecifier.Equal(Expected: Variant) : IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Equal', Expected); end; function TBaseSpecifier.Even: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Even', null); end; function TBaseSpecifier.GreaterThan(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'GreaterThan', Expected); end; function TBaseSpecifier.Implement(Expected: TGUID): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Implement', GUIDToString(Expected)); end; function TBaseSpecifier.ImplementedBy(Expected: TClass): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'ImplementedBy', Expected.ClassName); end; function TBaseSpecifier.LessThan(Expected: Variant): IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'LessThan', Expected); end; function TBaseSpecifier.Not_: IShouldHelper; begin Result := CreateNewShouldHelper(System.True); FContext.DocumentSpec(null, 'Not'); end; function TBaseSpecifier.Numeric: IModifier; begin Result := DoEvaluation(System.True, SpecNotApplicable, 'Numeric', null); end; { TIntegerSpecifier } function TIntegerSpecifier.AtLeast(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecIntegerShouldBeAtLeast, [FActual, Integer(Expected)]); Result := DoEvaluation(FActual < Integer(Expected), Msg, 'AtLeast', Expected); end; function TIntegerSpecifier.AtMost(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecIntegerShouldBeAtMost, [FActual, Integer(Expected)]); Result := DoEvaluation(FActual > Integer(Expected), Msg, 'AtMost', Expected); end; function TIntegerSpecifier.Composite: IModifier; var Msg: string; IsComposite: Boolean; begin IsComposite := not IsPrime(FActual); Msg := Format(SpecIntegerShouldBeComposite, [FActual]); Result := DoEvaluation(not IsComposite, Msg, 'Composite', null); end; constructor TIntegerSpecifier.Create(Actual: Integer; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TIntegerSpecifier.Equal(Expected : Variant) : IModifier; var Msg : string; begin Msg := Format(SpecIntegerShouldEqual, [FActual, Integer(Expected)]); Result := DoEvaluation(Expected <> FActual, Msg, 'Equal', Expected); end; function TIntegerSpecifier.Even: IModifier; var IsEven: Boolean; Msg: string; begin IsEven := FActual mod 2 = 0; Msg := Format(SpecIntegerShouldBeEven, [FActual]); Result := DoEvaluation(not IsEven, Msg, 'Even', null); end; function TIntegerSpecifier.GreaterThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecIntegerShouldBeGreaterThan, [FActual, Integer(Expected)]); Result := DoEvaluation(FActual <= Expected, Msg, 'GreaterThan', Expected); end; function TIntegerSpecifier.LessThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecIntegerShouldBeLessThan, [FActual, Integer(Expected)]); Result := DoEvaluation(FActual >= Expected, Msg, 'LessThan', Expected); end; function TIntegerSpecifier.Negative: IModifier; var IsNegative: Boolean; Msg: string; begin IsNegative := FActual < 0; Msg := Format(SpecIntegerShouldBeNegative, [FActual]); Result := DoEvaluation(not IsNegative, Msg, 'Negative', null); end; function TIntegerSpecifier.Odd: IModifier; var Msg: string; IsOdd: Boolean; begin IsOdd := FActual mod 2 <> 0; Msg := Format(SpecIntegerShouldBeOdd, [FActual]); Result := DoEvaluation(not IsOdd, Msg, 'Odd', null); end; function TIntegerSpecifier.Positive: IModifier; var IsPositive: Boolean; Msg: string; begin IsPositive := FActual > 0; Msg := Format(SpecIntegerShouldBePositive, [FActual]); Result := DoEvaluation(not IsPositive, Msg, 'Positive', null); end; function TIntegerSpecifier.Prime: IModifier; var ValueIsPrime: Boolean; Msg: string; begin ValueIsPrime := IsPrime(FActual); Msg := Format(SpecIntegerShouldBePrime, [FActual]); Result := DoEvaluation(not ValueIsPrime, Msg, 'Prime', null); end; function TIntegerSpecifier.Zero: IModifier; var Msg: string; begin Msg := Format(SpecIntegerShouldBeZero, [FActual]); Result := DoEvaluation(FActual <> 0, Msg, 'Zero', null); end; { TBooleanSpecifier } constructor TBooleanSpecifier.Create(Actual: Boolean; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TBooleanSpecifier.False : IModifier; var Msg: string; begin Msg := Format(SpecStringShouldEqual, [BoolToStr(FActual, System.True), BoolToStr(System.False, System.True)]); Result := DoEvaluation(FActual <> System.False, Msg, 'False', null); end; function TBooleanSpecifier.True : IModifier; var Msg: string; begin Msg := Format(SpecStringShouldEqual, [BoolToStr(FActual, System.True), BoolToStr(System.True, System.True)]); Result := DoEvaluation(FActual <> System.True, Msg, 'True', null); end; function TBooleanSpecifier.Equal(Expected : Variant) : IModifier; var Msg: string; begin Msg := Format(SpecStringShouldEqual, [BoolToStr(FActual, System.True), BoolToStr(Boolean(Expected), System.True)]); Result := DoEvaluation(Expected <> FActual, Msg, 'Equal', Expected); end; { TFloatSpecifier } function TFloatSpecifier.AtLeast(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldBeAtLeast, [FActual, Extended(Expected)]); FExpected := Expected; Result := DoEvaluation(FActual < Extended(Expected), Msg, 'AtLeast', Expected) end; function TFloatSpecifier.AtMost(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldBeAtMost, [FActual, Extended(Expected)]); FExpected := Expected; Result := DoEvaluation(FActual > Extended(Expected), Msg, 'AtMost', Expected) end; constructor TFloatSpecifier.Create(Actual: Extended; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TFloatSpecifier.CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string): IModifier; begin Result := TFloatModifier.Create(FExpected, FActual, Self, RemoveLastFailure, FailureMessage, FCallerAddress, FContext); end; function TFloatSpecifier.Equal(Expected : Variant) : IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldEqual, [FActual, Extended(Expected)]); FExpected := Expected; Result := DoEvaluation(Expected <> FActual, Msg, 'Equal', Expected); end; function TFloatSpecifier.GreaterThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldBeGreaterThan, [FActual, Extended(Expected)]); FExpected := Expected; Result := DoEvaluation(FActual <= Extended(Expected), Msg, 'GreaterThan', Expected); end; function TFloatSpecifier.LessThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldBeLessThan, [FActual, Extended(Expected)]); FExpected := Expected; Result := DoEvaluation(FActual >= Extended(Expected), Msg, 'LessThan', Expected); end; function TFloatSpecifier.Negative: IModifier; var Msg: string; IsNegative: Boolean; begin IsNegative := FActual < 0; Msg := Format(SpecFloatShouldBeNegative, [FActual]); Result := DoEvaluation(not IsNegative, Msg, 'Negative', null); end; function TFloatSpecifier.Positive: IModifier; var Msg: string; IsPositive: Boolean; begin IsPositive := FActual > 0; Msg := Format(SpecFloatShouldBePositive, [FActual]); Result := DoEvaluation(not IsPositive, Msg, 'Positive', null); end; function TFloatSpecifier.Zero: IModifier; var Msg: string; begin Msg := Format(SpecFloatShouldBeZero, [FActual]); DoEvaluation(FActual <> 0, Msg, 'Zero', null); end; { TStringSpecifier } function TStringSpecifier.Alpha: IModifier; var Msg: string; begin Msg := Format(SpecStringShouldBeAlpha, [FActual]); Result := DoEvaluation(not IsAlpha(FActual), Msg, 'Alpha', null); end; function TStringSpecifier.AlphaNumeric: IModifier; var Msg: string; begin Msg := Format(SpecStringShouldBeAlphaNumeric, [FActual]); Result := DoEvaluation(not IsAlphaNumeric(FActual), Msg, 'AlphaNumeric', null); end; function TStringSpecifier.Contain(Expected: Variant): IModifier; var StringFound: Boolean; Msg: string; begin StringFound := Pos(string(Expected), FActual) <> 0; Msg := Format(SpecStringShouldContain, [FActual, string(Expected)]); FExpected := Expected; Result := DoEvaluation(not StringFound, Msg, 'Contain', Expected); end; constructor TStringSpecifier.Create(Actual: string; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TStringSpecifier.CreateModifier(RemoveLastFailure: Boolean; FailureMessage: string): IModifier; begin Result := TStringModifier.Create(FExpected, FActual, Self, RemoveLastFailure, FailureMessage, FCallerAddress, FContext); end; function TStringSpecifier.Empty: IModifier; var Msg: string; begin Msg := Format(SpecStringShouldBeEmpty, [FActual]); Result := DoEvaluation(FActual <> '', Msg, 'Empty', null) end; function TStringSpecifier.EndWith(Expected: Variant): IModifier; var EndOfString: string; Msg: string; begin EndOfString := Copy(FActual, (Length(FActual) - Length(string(Expected))) + 1, Length(string(Expected))); Msg := Format(SpecStringShouldEndWith, [FActual, string(Expected)]); FExpected := Expected; Result := DoEvaluation(EndOfString <> Expected, Msg, 'EndWith', Expected); end; function TStringSpecifier.Equal(Expected : Variant) : IModifier; var Msg: string; begin Msg := Format(SpecStringShouldEqual, [FActual, Expected]); FExpected := Expected; Result := DoEvaluation(Expected <> FActual, Msg, 'Equal', Expected) end; function TStringSpecifier.Numeric: IModifier; var Msg: string; begin Msg := Format(SpecStringShouldBeNumeric, [FActual]); Result := DoEvaluation(not IsNumeric(FActual), Msg, 'Numeric', null); end; function TStringSpecifier.StartWith(Expected : Variant): IModifier; var BeginningOfString: string; Msg: string; begin BeginningOfString := Copy(FActual, 1, Length(string(Expected))); Msg := Format(SpecStringShouldStartWith, [FActual, string(Expected)]); FExpected := Expected; Result := DoEvaluation(BeginningOfString <> string(Expected), Msg, 'StartWith', Expected); end; { TObjectSpecifier } function TObjectSpecifier.Assigned: IModifier; begin Result := DoEvaluation(not System.Assigned(FActual), SpecObjectShouldBeAssigned, 'Assigned', null); end; constructor TObjectSpecifier.Create(Actual: TObject; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TObjectSpecifier.Nil_ : IModifier; begin Result := DoEvaluation(System.Assigned(FActual), SpecPointerShouldBeNil, 'Nil', null); end; function TObjectSpecifier.OfType(Expected: TClass) : IModifier; var Msg: string; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'OfType', 'Unassigned') else begin Msg := Format(SpecObjectShouldBeOfType, [FActual.ClassName, Expected.ClassName]); Result := DoEvaluation(FActual.ClassType <> Expected, Msg, 'OfType', Expected.ClassName); end; end; function TObjectSpecifier.Support(Expected: TGUID): IModifier; var InterfaceFound: Boolean; obj: IInterface; Msg: string; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'Support', 'Unassigned') else begin InterfaceFound := FActual.GetInterface(Expected, obj); obj := nil; Msg := Format(SpecObjectShouldSupport, [FActual.ClassName, GUIDToString(Expected)]); Result := DoEvaluation(not InterfaceFound, Msg, 'Support', GUIDToString(Expected)); end; end; function TObjectSpecifier.DescendFrom(Expected: TClass) : IModifier; var Msg: string; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'DescendFrom', 'Unassigned') else begin Msg := Format(SpecObjectShouldDescendFrom, [FActual.ClassName, Expected.ClassName]); Result := DoEvaluation(not FActual.InheritsFrom(Expected), Msg, 'DecendFrom', Expected.ClassName); end; end; function TObjectSpecifier.Implement(Expected: TGUID): IModifier; var InterfaceFound: Boolean; obj: IInterface; Msg: string; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'Implement', 'Unassigned') else begin InterfaceFound := FActual.GetInterface(Expected, obj); obj := nil; Msg := Format(SpecObjectShouldImplement, [FActual.ClassName, GUIDToString(Expected)]); Result := DoEvaluation(not InterfaceFound, Msg, 'Implement', GUIDToString(Expected)); end; end; { TPointerSpecifier } function TPointerSpecifier.Assigned: IModifier; begin Result := DoEvaluation(not System.Assigned(FActual), SpecPointerShouldBeAssigned, 'Assigned', null); end; constructor TPointerSpecifier.Create(Actual, ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TPointerSpecifier.Nil_ : IModifier; begin Result := DoEvaluation(System.Assigned(FActual), SpecPointerShouldBeNil, 'Nil', null); end; { TClassSpecifier } constructor TClassSpecifier.Create(Actual: TClass; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TClassSpecifier.OfType(Value: TClass) : IModifier; var Msg: string; begin Msg := Format(SpecObjectShouldBeOfType, [FActual.ClassName, Value.ClassName]); Result := DoEvaluation(FActual <> Value, Msg, 'OfType', Value.ClassName); end; function TClassSpecifier.DescendFrom(Expected: TClass) : IModifier; var Msg: string; begin Msg := Format(SpecObjectShouldDescendFrom, [FActual.ClassName, Expected.ClassName]); Result := DoEvaluation(not FActual.InheritsFrom(Expected), Msg, 'DescendFrom', Expected.ClassName); end; { TDateTimeSpecifier } function TDateTimeSpecifier.AtLeast(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecDateTimeShouldBeAtLeast, [DateTimeToStr(FActual), DateTimeToStr(TDateTime(Expected))]); Result := DoEvaluation(FActual < TDateTime(Expected), Msg, 'AtLeast', Expected); end; function TDateTimeSpecifier.AtMost(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecDateTimeShouldBeAtMost, [DateTimeToStr(FActual), DateTimeToStr(TDateTime(Expected))]); Result := DoEvaluation(FActual > TDateTime(Expected), Msg, 'AtMost', Expected); end; constructor TDateTimeSpecifier.Create(Actual: TDateTime; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; function TDateTimeSpecifier.Equal(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecStringShouldEqual, [DateTimeToStr(FActual), DateTimeToStr(TDateTime(Expected))]); Result := DoEvaluation(FActual <> Expected, Msg, 'Equal', Expected) end; function TDateTimeSpecifier.GreaterThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecDateTimeShouldBeGreaterThan, [DateTimeToStr(FActual), DateTimeToStr(TDateTime(Expected))]); Result := DoEvaluation(FActual <= TDateTime(Expected), Msg, 'GreaterThan', Expected) end; function TDateTimeSpecifier.LessThan(Expected: Variant): IModifier; var Msg: string; begin Msg := Format(SpecDateTimeShouldBeLessThan, [DateTimeToStr(FActual), DateTimeToStr(TDateTime(Expected))]); Result := DoEvaluation(FActual >= TDateTime(Expected), Msg, 'LessThan', Expected) end; { TInterfaceSpecifier } function TInterfaceSpecifier.Assigned: IModifier; begin Result := DoEvaluation(not System.Assigned(FActual), SpecInterfaceShouldBeAssigned, 'Assigned', null); end; constructor TInterfaceSpecifier.Create(Actual: IInterface; ACallerAddress: Pointer; AContext: IContext; const AValueName : string); begin inherited Create(ACallerAddress, AContext, AValueName); FActual := Actual; end; destructor TInterfaceSpecifier.Destroy; begin FActual := nil; inherited Destroy; end; function TInterfaceSpecifier.ImplementedBy(Expected: TClass): IModifier; var Obj: TObject; Msg: string; MatchesExpectedClass: Boolean; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'ImplementedBy', 'Unassigned') else begin Obj := GetImplementingObjectFor(FActual); if System.Assigned(Obj) then begin MatchesExpectedClass := Obj.ClassType = Expected; Msg := Format(SpecInterfaceShouldBeImplementedBy, [Expected.ClassName]); Result := DoEvaluation(not MatchesExpectedClass, Msg, 'ImplementedBy', Expected.ClassName); end else Result := DoEvaluation(System.True, SpecInterfaceImplementingObjectNotFound, 'ImplementedBy', Expected.ClassName); end; end; function TInterfaceSpecifier.Nil_: IModifier; begin Result := DoEvaluation(System.Assigned(FActual), SpecInterfaceShouldBeNil, 'Nil', null); end; function TInterfaceSpecifier.Support(Expected: TGUID): IModifier; var obj: IInterface; InterfaceFound: Boolean; Msg: string; begin if not System.Assigned(FActual) then Result := DoEvaluation(System.True, 'Actual must be assigned for this specification', 'Support', 'Unassinged') else begin InterfaceFound := FActual.QueryInterface(Expected, obj) = 0; obj := nil; Msg := Format(SpecInterfaceShouldSupport, [GuidToString(Expected)]); Result := DoEvaluation(not InterfaceFound, Msg, 'Support', GUIDToString(Expected)); end; end; end.
unit class_taylor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs; type TTaylor = class ErrorAllowed: Real; Sequence, FunctionList: TstringList; FunctionType: Integer; AngleType: Integer; x: Real; function Execute(): Real; private Error, Angle: Real; function sen(): Real; function cos(): Real; function exponencial(): Real; function senh(): Real; function cosh(): Real; function ln(): Real; function arcsen(): Real; function arctan(): Real; function arcsenh(): Real; function arctanh(): Real; public constructor create; destructor Destroy; override; end; const IsSin = 0; IsCos = 1; IsExp = 2; IsSinh = 3; IsCosh = 4; IsLn = 5; IsArcSin = 6; IsArcTan = 7; IsArcSinh = 8; IsArcTanh = 9; AngleSexagedecimal = 0; AngleRadian = 1; implementation const Top = 100000; constructor TTaylor.create; begin Sequence:= TStringList.Create; FunctionList:= TStringList.Create; FunctionList.AddObject( 'sen', TObject( IsSin ) ); FunctionList.AddObject( 'cos', TObject( IsCos ) ); FunctionList.AddObject( 'exp', TObject( IsExp ) ); FunctionList.AddObject( 'sinh', TObject( IsSinh ) ); FunctionList.AddObject( 'cosh', TObject( IsCosh ) ); FunctionList.AddObject( 'ln(x+1)', TObject( IsLn ) ); FunctionList.AddObject( 'arcsin', TObject( IsArcSin ) ); FunctionList.AddObject( 'arctan', TObject( IsArcTan ) ); FunctionList.AddObject( 'arcsinh', TObject( IsArcSinh ) ); FunctionList.AddObject( 'arctanh', TObject( IsArcTanh ) ); Sequence.Add('0'); Error:= Top; x:= 0; end; destructor TTaylor.Destroy; begin Sequence.Destroy; FunctionList.Destroy; end; function Power( b: Double; n: Integer ): Double Double; var i: Integer; begin // ShowMessage(FloatToStr(b) + '^' + FloatToStr(n)); Result:= 1; for i:= 1 to n do Result:= Result * b; end; function Factorial( n: Integer ): Double; begin if n > 1 then Result:= n * Factorial( n -1 ) else if n >= 0 then Result:= 1 else Result:= 0; end; function Module(a: Real; b: Double): Real; var x: Real; i: Real; begin x:=a; i:=0; repeat x:=x-b; i:=i+1; until (x<0); i:=i-1; i:=i*b; Result := a-i; end; function TTaylor.Execute( ): Real; begin case AngleType of AngleRadian: Angle:= x; AngleSexagedecimal: Angle:=x * pi/180; end; Angle := Module(Angle ,(2*pi)); case FunctionType of IsSin: Result:= sen(); IsCos: Result:= cos(); IsExp: Result:= exponencial(); IsSinh: Result:= senh(); IsCosh: Result:= cosh(); IsLn: Result := ln(); IsArcSin: Result := ArcSen(); IsArcTan: Result := ArcTan(); IsArcSinh: Result := ArcSenh(); IsArcTanh: Result := ArcTanh(); end; end; function TTaylor.sen(): Real; var xn: Real; n: Integer; begin Result:= 0; n:= 0; repeat xn:= Result; Result:= Result + Power(-1, n)/Factorial( 2*n + 1 ) * Power(Angle, 2*n + 1); if n > 0 then Error:= abs( Result - xn ); Sequence.Add( FloatToStr( Result ) ); n:= n + 1; until ( Error <= ErrorAllowed ) or ( n >= Top ) ; end; function TTaylor.cos(): Real; var xn: real; n: Integer; begin Result:= 0; n:= 0; repeat xn:= Result; Result:= Result + Power( -1, n)/Factorial(2*n) * Power( Angle, 2*n ); Sequence.Add( FloatToStr( Result ) ); if n > 0 then Error:= abs( Result - xn ); n:= n + 1; until ( Error < ErrorAllowed ) or ( n >= Top ); end; function TTaylor.exponencial(): Real; var xn: Real; n: Integer; begin n:= 0; Result:= 0; repeat xn:= Result; Result:= Result + (Power( x,n ) / Factorial(n)); Sequence.Add( FloatToStr( Result ) ); if n > 0 then Error:= abs( Result - xn ); n:= n + 1; until (Error < ErrorAllowed ) or (n >= Top ); end; function Ttaylor.senh(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + 1 / Factorial( 2*n + 1 ) * Power( angle , 2*n + 1 ); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.cosh(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + 1 / Factorial( 2*n ) * Power( angle , 2*n ); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.ln(): Real; var xn: Real; n: Integer; begin n := 1; Result := 0; repeat xn := Result; Result := Result + (Power( -1, n + 1) / n )* Power( x , n ); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.arcsen(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + Factorial( 2*n )/ ( Power( 4 , n)*Power( Factorial( n ) , 2)*(2*n + 1))*Power( angle, 2*n + 1); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.arctan(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + Power( -1 , n ) / (2*n + 1) * Power (angle, 2*n + 1); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.arcsenh(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + ((Factorial(2*n)*Power(-1,n)) / (Power(4,n)*Power(Factorial(n),2)*(2*n+1)) )* Power(angle,2*n+1); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; function Ttaylor.arctanh(): Real; var xn: Real; n: Integer; begin n := 0; Result := 0; repeat xn := Result; Result := Result + 1 / (2*n+1) * Power( angle , 2*n + 1); Sequence.add( FloatToStr ( Result ) ); if n > 0 then Error := abs( Result - xn); n := n + 1; until (Error < ErrorAllowed) or (n >= Top); end; end.
Unit DevApp.Form.AccountInfo; Interface Uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, DevApp.Base.DetailForm, FMX.Controls.Presentation, FMX.Layouts, FMX.Edit, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, System.Rtti, FMX.Grid.Style, FMX.Grid, Aurelius.Mapping.Metadata; Type TAccountInfoForm = Class(TDevBaseForm) Layout1: TLayout; Label1: TLabel; Edit1: TEdit; Button1: TButton; Memo1: TMemo; Layout2: TLayout; Label2: TLabel; PublicKey: TLabel; Layout3: TLayout; AccountList: TStringGrid; StringColumn1: TStringColumn; Col2: TStringColumn; NumAccountsLabel: TLabel; NumAccounts: TLabel; LiveCol: TStringColumn; LinkedAccountsBtn: TSpeedButton; CopyPubKeyBtn: TSpeedButton; PastePubKeyBtn: TSpeedButton; Layout4: TLayout; Memo2: TMemo; OpsButton: TButton; OpDepth: TEdit; Label3: TLabel; Procedure AccountListCellClick(Const Column: TColumn; Const Row: Integer); Procedure Button1Click(Sender: TObject); Procedure CopyPubKeyBtnClick(Sender: TObject); Procedure Edit1KeyDown(Sender: TObject; Var Key: Word; Var KeyChar: Char; Shift: TShiftState); Procedure LinkedAccountsBtnClick(Sender: TObject); Procedure OpsButtonClick(Sender: TObject); Procedure PastePubKeyBtnClick(Sender: TObject); Private { Private declarations } FAccounts: Integer; FLastAccountIndex: Integer; FLatestBlock: Integer; Procedure FetchNextAccounts; Function DisplayAccountInfo(Const AnAccount: String): String; Function SanitiseRecovery(Const DaysToRecovery: Double): String; Public { Public declarations } End; Var AccountInfoForm: TAccountInfoForm; Implementation {$R *.fmx} Uses System.DateUtils, PascalCoin.Utils, PascalCoin.RPC.Interfaces, DevApp.Utils, FMX.PlatformUtils, PascalCoin.RPC.Consts; Procedure TAccountInfoForm.AccountListCellClick(Const Column: TColumn; Const Row: Integer); Begin Inherited; DisplayAccountInfo(AccountList.Cells[0, Row]); End; Procedure TAccountInfoForm.Button1Click(Sender: TObject); Var pk: String; Begin pk := DisplayAccountInfo(Edit1.Text); If pk <> PublicKey.Text Then Begin PublicKey.Text := pk; AccountList.RowCount := 0; End; End; Procedure TAccountInfoForm.CopyPubKeyBtnClick(Sender: TObject); Var S: String; Begin Inherited; S := PublicKey.Text; If S = '' Then Begin ShowMessage('Set a public key first'); Exit; End; If TFMXUtils.CopyToClipboard(S) Then ShowMessage('Copied to clipboard') Else ShowMessage('Can''t copy to clipboard on this platform'); End; Function TAccountInfoForm.DisplayAccountInfo(Const AnAccount: String): String; Var lAccount: IPascalCoinAccount; Begin If Not TPascalCoinUtils.ValidAccountNumber(AnAccount) Then Begin ShowMessage('Not a valid account number'); Exit; End; Edit1.Text := AnAccount; lAccount := ExplorerAPI.GetAccount(TPascalCoinUtils.AccountNumber(AnAccount)); Memo1.Lines.Clear; TDevAppUtils.AccountInfo(lAccount, Memo1.Lines); Result := lAccount.enc_pubkey; End; Procedure TAccountInfoForm.Edit1KeyDown(Sender: TObject; Var Key: Word; Var KeyChar: Char; Shift: TShiftState); Begin If Key = vkReturn Then Button1Click(self); End; Procedure TAccountInfoForm.FetchNextAccounts; Var lAccounts: IPascalCoinAccounts; I, lastRow: Integer; Begin FLatestBlock := ExplorerAPI.GetBlockCount; lAccounts := WalletExplorerAPI.getwalletaccounts(PublicKey.Text, TKeyStyle.ksEncKey, FLastAccountIndex); FLastAccountIndex := FLastAccountIndex + lAccounts.Count; lastRow := AccountList.RowCount - 1; AccountList.RowCount := AccountList.RowCount + lAccounts.Count; For I := 0 To lAccounts.Count - 1 Do Begin inc(lastRow); AccountList.Cells[0, lastRow] := TPascalCoinUtils.AccountNumberWithCheckSum(lAccounts[I].Account); AccountList.Cells[1, lastRow] := lAccounts[I].Name; AccountList.Cells[2, lastRow] := SanitiseRecovery(TPascalCoinUtils.DaysToRecovery(FLatestBlock, lAccounts[I].updated_b_active_mode)); End; End; Procedure TAccountInfoForm.LinkedAccountsBtnClick(Sender: TObject); Begin Inherited; AccountList.RowCount := 0; FLastAccountIndex := -1; Try FAccounts := WalletExplorerAPI.getwalletaccountscount(PublicKey.Text, TKeyStyle.ksEncKey); Except On e: Exception Do HandleAPIException(e); End; NumAccounts.Text := FormatFloat('#,##0', FAccounts); FetchNextAccounts; AccountList.Visible := True; End; Procedure TAccountInfoForm.OpsButtonClick(Sender: TObject); var lDepth: Integer; Begin Inherited; if SameText(OpDepth.Text, 'deep') then lDepth := DEEP_SEARCH else lDepth := StrToInt(OpDepth.Text.Trim); ExplorerAPI.getaccountoperations(TPascalCoinUtils.AccountNumber(Edit1.Text), lDepth); End; Procedure TAccountInfoForm.PastePubKeyBtnClick(Sender: TObject); Var S: String; Begin Inherited; If Not TFMXUtils.CopyFromClipboard(S) Then Begin ShowMessage('Sorry, can''t access the clipboard on this platform'); Exit; End; If S = '' Then Begin ShowMessage('Unable to retrieve the value from teh clipboard'); Exit; End; If TPascalCoinUtils.KeyStyle(S) <> TKeyStyle.ksEncKey Then Begin ShowMessage('Please paste Encoded Public Keys only'); Exit; End; Edit1.Text := ''; Memo1.Lines.Clear; PublicKey.Text := S; LinkedAccountsBtnClick(self); End; Function TAccountInfoForm.SanitiseRecovery(Const DaysToRecovery: Double): String; Var DTR: TDateTime; T: Double; Begin T := Frac(DaysToRecovery); DTR := IncDay(Now, Trunc(DaysToRecovery)) + T; Result := TDevAppUtils.FormatAsTimeToGo(DTR - Now); End; End.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_CONFIGURACAO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit EcfConfiguracaoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, EcfResolucaoVO, EcfImpressoraVO, EcfCaixaVO, EcfEmpresaVO, EcfConfiguracaoBalancaVO, EcfRelatorioGerencialVO, EcfConfiguracaoLeitorSerVO, Biblioteca; type [TEntity] [TTable('ECF_CONFIGURACAO')] TEcfConfiguracaoVO = class(TVO) private FID: Integer; FID_ECF_IMPRESSORA: Integer; FID_ECF_RESOLUCAO: Integer; FID_ECF_CAIXA: Integer; FID_ECF_EMPRESA: Integer; FMENSAGEM_CUPOM: String; FPORTA_ECF: String; FIP_SERVIDOR: String; FIP_SITEF: String; FTIPO_TEF: String; FTITULO_TELA_CAIXA: String; FCAMINHO_IMAGENS_PRODUTOS: String; FCAMINHO_IMAGENS_MARKETING: String; FCAMINHO_IMAGENS_LAYOUT: String; FCOR_JANELAS_INTERNAS: String; FMARKETING_ATIVO: String; FCFOP_ECF: Integer; FCFOP_NF2: Integer; FTIMEOUT_ECF: Integer; FINTERVALO_ECF: Integer; FDESCRICAO_SUPRIMENTO: String; FDESCRICAO_SANGRIA: String; FTEF_TIPO_GP: Integer; FTEF_TEMPO_ESPERA: Integer; FTEF_ESPERA_STS: Integer; FTEF_NUMERO_VIAS: Integer; FDECIMAIS_QUANTIDADE: Integer; FDECIMAIS_VALOR: Integer; FBITS_POR_SEGUNDO: Integer; FQUANTIDADE_MAXIMA_CARTOES: Integer; FPESQUISA_PARTE: String; FULTIMA_EXCLUSAO: Integer; FLAUDO: String; FINDICE_GERENCIAL: String; FDATA_ATUALIZACAO_ESTOQUE: TDateTime; FPEDE_CPF_CUPOM: String; FTIPO_INTEGRACAO: Integer; FTIMER_INTEGRACAO: Integer; FGAVETA_SINAL_INVERTIDO: String; FGAVETA_UTILIZACAO: Integer; FQUANTIDADE_MAXIMA_PARCELA: Integer; FIMPRIME_PARCELA: String; FUSA_TECLADO_REDUZIDO: String; FPERMITE_LANCAR_NF_MANUAL: String; FEcfResolucaoVO: TEcfResolucaoVO; FEcfImpressoraVO: TEcfImpressoraVO; FEcfCaixaVO: TEcfCaixaVO; FEcfEmpresaVO: TEcfEmpresaVO; FEcfConfiguracaoBalancaVO: TEcfConfiguracaoBalancaVO; FEcfRelatorioGerencialVO: TEcfRelatorioGerencialVO; FEcfConfiguracaoLeitorSerVO: TEcfConfiguracaoLeitorSerVO; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_ECF_IMPRESSORA', 'Id Ecf Impressora', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfImpressora: Integer read FID_ECF_IMPRESSORA write FID_ECF_IMPRESSORA; [TColumn('ID_ECF_RESOLUCAO', 'Id Ecf Resolucao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfResolucao: Integer read FID_ECF_RESOLUCAO write FID_ECF_RESOLUCAO; [TColumn('ID_ECF_CAIXA', 'Id Ecf Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA; [TColumn('ID_ECF_EMPRESA', 'Id Ecf Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfEmpresa: Integer read FID_ECF_EMPRESA write FID_ECF_EMPRESA; [TColumn('MENSAGEM_CUPOM', 'Mensagem Cupom', 450, [ldGrid, ldLookup, ldCombobox], False)] property MensagemCupom: String read FMENSAGEM_CUPOM write FMENSAGEM_CUPOM; [TColumn('PORTA_ECF', 'Porta Ecf', 80, [ldGrid, ldLookup, ldCombobox], False)] property PortaEcf: String read FPORTA_ECF write FPORTA_ECF; [TColumn('IP_SERVIDOR', 'Ip Servidor', 120, [ldGrid, ldLookup, ldCombobox], False)] property IpServidor: String read FIP_SERVIDOR write FIP_SERVIDOR; [TColumn('IP_SITEF', 'Ip Sitef', 120, [ldGrid, ldLookup, ldCombobox], False)] property IpSitef: String read FIP_SITEF write FIP_SITEF; [TColumn('TIPO_TEF', 'Tipo Tef', 16, [ldGrid, ldLookup, ldCombobox], False)] property TipoTef: String read FTIPO_TEF write FTIPO_TEF; [TColumn('TITULO_TELA_CAIXA', 'Titulo Tela Caixa', 450, [ldGrid, ldLookup, ldCombobox], False)] property TituloTelaCaixa: String read FTITULO_TELA_CAIXA write FTITULO_TELA_CAIXA; [TColumn('CAMINHO_IMAGENS_PRODUTOS', 'Caminho Imagens Produtos', 450, [ldGrid, ldLookup, ldCombobox], False)] property CaminhoImagensProdutos: String read FCAMINHO_IMAGENS_PRODUTOS write FCAMINHO_IMAGENS_PRODUTOS; [TColumn('CAMINHO_IMAGENS_MARKETING', 'Caminho Imagens Marketing', 450, [ldGrid, ldLookup, ldCombobox], False)] property CaminhoImagensMarketing: String read FCAMINHO_IMAGENS_MARKETING write FCAMINHO_IMAGENS_MARKETING; [TColumn('CAMINHO_IMAGENS_LAYOUT', 'Caminho Imagens Layout', 450, [ldGrid, ldLookup, ldCombobox], False)] property CaminhoImagensLayout: String read FCAMINHO_IMAGENS_LAYOUT write FCAMINHO_IMAGENS_LAYOUT; [TColumn('COR_JANELAS_INTERNAS', 'Cor Janelas Internas', 160, [ldGrid, ldLookup, ldCombobox], False)] property CorJanelasInternas: String read FCOR_JANELAS_INTERNAS write FCOR_JANELAS_INTERNAS; [TColumn('MARKETING_ATIVO', 'Marketing Ativo', 8, [ldGrid, ldLookup, ldCombobox], False)] property MarketingAtivo: String read FMARKETING_ATIVO write FMARKETING_ATIVO; [TColumn('CFOP_ECF', 'Cfop Ecf', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CfopEcf: Integer read FCFOP_ECF write FCFOP_ECF; [TColumn('CFOP_NF2', 'Cfop Nf2', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CfopNf2: Integer read FCFOP_NF2 write FCFOP_NF2; [TColumn('TIMEOUT_ECF', 'Timeout Ecf', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TimeoutEcf: Integer read FTIMEOUT_ECF write FTIMEOUT_ECF; [TColumn('INTERVALO_ECF', 'Intervalo Ecf', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IntervaloEcf: Integer read FINTERVALO_ECF write FINTERVALO_ECF; [TColumn('DESCRICAO_SUPRIMENTO', 'Descricao Suprimento', 160, [ldGrid, ldLookup, ldCombobox], False)] property DescricaoSuprimento: String read FDESCRICAO_SUPRIMENTO write FDESCRICAO_SUPRIMENTO; [TColumn('DESCRICAO_SANGRIA', 'Descricao Sangria', 160, [ldGrid, ldLookup, ldCombobox], False)] property DescricaoSangria: String read FDESCRICAO_SANGRIA write FDESCRICAO_SANGRIA; [TColumn('TEF_TIPO_GP', 'Tef Tipo Gp', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TefTipoGp: Integer read FTEF_TIPO_GP write FTEF_TIPO_GP; [TColumn('TEF_TEMPO_ESPERA', 'Tef Tempo Espera', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TefTempoEspera: Integer read FTEF_TEMPO_ESPERA write FTEF_TEMPO_ESPERA; [TColumn('TEF_ESPERA_STS', 'Tef Espera Sts', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TefEsperaSts: Integer read FTEF_ESPERA_STS write FTEF_ESPERA_STS; [TColumn('TEF_NUMERO_VIAS', 'Tef Numero Vias', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TefNumeroVias: Integer read FTEF_NUMERO_VIAS write FTEF_NUMERO_VIAS; [TColumn('DECIMAIS_QUANTIDADE', 'Decimais Quantidade', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property DecimaisQuantidade: Integer read FDECIMAIS_QUANTIDADE write FDECIMAIS_QUANTIDADE; [TColumn('DECIMAIS_VALOR', 'Decimais Valor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property DecimaisValor: Integer read FDECIMAIS_VALOR write FDECIMAIS_VALOR; [TColumn('BITS_POR_SEGUNDO', 'Bits Por Segundo', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property BitsPorSegundo: Integer read FBITS_POR_SEGUNDO write FBITS_POR_SEGUNDO; [TColumn('QUANTIDADE_MAXIMA_CARTOES', 'Qtde Maxima Cartoes', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property QuantidadeMaximaCartoes: Integer read FQUANTIDADE_MAXIMA_CARTOES write FQUANTIDADE_MAXIMA_CARTOES; [TColumn('PESQUISA_PARTE', 'Pesquisa Parte', 8, [ldGrid, ldLookup, ldCombobox], False)] property PesquisaParte: String read FPESQUISA_PARTE write FPESQUISA_PARTE; [TColumn('ULTIMA_EXCLUSAO', 'Ultima Exclusao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property UltimaExclusao: Integer read FULTIMA_EXCLUSAO write FULTIMA_EXCLUSAO; [TColumn('LAUDO', 'Laudo', 80, [ldGrid, ldLookup, ldCombobox], False)] property Laudo: String read FLAUDO write FLAUDO; [TColumn('INDICE_GERENCIAL', 'Indice Gerencial', 450, [ldGrid, ldLookup, ldCombobox], False)] property IndiceGerencial: String read FINDICE_GERENCIAL write FINDICE_GERENCIAL; [TColumn('DATA_ATUALIZACAO_ESTOQUE', 'Data Atualizacao Estoque', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataAtualizacaoEstoque: TDateTime read FDATA_ATUALIZACAO_ESTOQUE write FDATA_ATUALIZACAO_ESTOQUE; [TColumn('PEDE_CPF_CUPOM', 'Pede Cpf Cupom', 8, [ldGrid, ldLookup, ldCombobox], False)] property PedeCpfCupom: String read FPEDE_CPF_CUPOM write FPEDE_CPF_CUPOM; [TColumn('TIPO_INTEGRACAO', 'Tipo Integracao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TipoIntegracao: Integer read FTIPO_INTEGRACAO write FTIPO_INTEGRACAO; [TColumn('TIMER_INTEGRACAO', 'Timer Integracao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TimerIntegracao: Integer read FTIMER_INTEGRACAO write FTIMER_INTEGRACAO; [TColumn('GAVETA_SINAL_INVERTIDO', 'Gaveta Sinal Invertido', 8, [ldGrid, ldLookup, ldCombobox], False)] property GavetaSinalInvertido: String read FGAVETA_SINAL_INVERTIDO write FGAVETA_SINAL_INVERTIDO; [TColumn('GAVETA_UTILIZACAO', 'Gaveta Utilizacao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property GavetaUtilizacao: Integer read FGAVETA_UTILIZACAO write FGAVETA_UTILIZACAO; [TColumn('QUANTIDADE_MAXIMA_PARCELA', 'Quantidade Maxima Parcela', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property QuantidadeMaximaParcela: Integer read FQUANTIDADE_MAXIMA_PARCELA write FQUANTIDADE_MAXIMA_PARCELA; [TColumn('IMPRIME_PARCELA', 'Imprime Parcela', 8, [ldGrid, ldLookup, ldCombobox], False)] property ImprimeParcela: String read FIMPRIME_PARCELA write FIMPRIME_PARCELA; [TColumn('USA_TECLADO_REDUZIDO', 'Usa Teclado Reduzido', 8, [ldGrid, ldLookup, ldCombobox], False)] property UsaTecladoReduzido: String read FUSA_TECLADO_REDUZIDO write FUSA_TECLADO_REDUZIDO; [TColumn('PERMITE_LANCAR_NF_MANUAL', 'Permite Lancar Nf Manual', 8, [ldGrid, ldLookup, ldCombobox], False)] property PermiteLancarNfManual: String read FPERMITE_LANCAR_NF_MANUAL write FPERMITE_LANCAR_NF_MANUAL; [TAssociation('ID', 'ID_ECF_RESOLUCAO')] property EcfResolucaoVO: TEcfResolucaoVO read FEcfResolucaoVO write FEcfResolucaoVO; [TAssociation('ID', 'ID_ECF_IMPRESSORA')] property EcfImpressoraVO: TEcfImpressoraVO read FEcfImpressoraVO write FEcfImpressoraVO; [TAssociation('ID', 'ID_ECF_CAIXA')] property EcfCaixaVO: TEcfCaixaVO read FEcfCaixaVO write FEcfCaixaVO; [TAssociation('ID', 'ID_ECF_EMPRESA')] property EcfEmpresaVO: TEcfEmpresaVO read FEcfEmpresaVO write FEcfEmpresaVO; [TAssociation('ID_ECF_CONFIGURACAO', 'ID')] property EcfConfiguracaoBalancaVO: TEcfConfiguracaoBalancaVO read FEcfConfiguracaoBalancaVO write FEcfConfiguracaoBalancaVO; [TAssociation('ID_ECF_CONFIGURACAO', 'ID')] property EcfRelatorioGerencialVO: TEcfRelatorioGerencialVO read FEcfRelatorioGerencialVO write FEcfRelatorioGerencialVO; [TAssociation('ID_ECF_CONFIGURACAO', 'ID')] property EcfConfiguracaoLeitorSerVO: TEcfConfiguracaoLeitorSerVO read FEcfConfiguracaoLeitorSerVO write FEcfConfiguracaoLeitorSerVO; end; implementation constructor TEcfConfiguracaoVO.Create; begin inherited; FEcfResolucaoVO := TEcfResolucaoVO.Create; FEcfImpressoraVO := TEcfImpressoraVO.Create; FEcfCaixaVO := TEcfCaixaVO.Create; FEcfEmpresaVO := TEcfEmpresaVO.Create; FEcfConfiguracaoBalancaVO := TEcfConfiguracaoBalancaVO.Create; FEcfRelatorioGerencialVO := TEcfRelatorioGerencialVO.Create; FEcfConfiguracaoLeitorSerVO := TEcfConfiguracaoLeitorSerVO.Create; end; destructor TEcfConfiguracaoVO.Destroy; begin FreeAndNil(FEcfResolucaoVO); FreeAndNil(FEcfImpressoraVO); FreeAndNil(FEcfCaixaVO); FreeAndNil(FEcfEmpresaVO); FreeAndNil(FEcfConfiguracaoBalancaVO); FreeAndNil(FEcfRelatorioGerencialVO); FreeAndNil(FEcfConfiguracaoLeitorSerVO); inherited; end; initialization Classes.RegisterClass(TEcfConfiguracaoVO); finalization Classes.UnRegisterClass(TEcfConfiguracaoVO); end.
unit OptionsValidator; interface uses Classes, SysUtils, IniFiles; type TConsoleOutputEvent = procedure of object; TOptionsValidator = class (TObject) private FOnWriteProgramHeader: TConsoleOutputEvent; FOnWriteExplanations: TConsoleOutputEvent; FOnWriteProgramVersion: TConsoleOutputEvent; procedure UpdateSearchPathFromDOFFile; protected procedure DoWriteProgramHeader; procedure DoWriteExplanations; procedure DoWriteProgramVersion; public procedure Validate; property OnWriteProgramHeader: TConsoleOutputEvent read FOnWriteProgramHeader write FOnWriteProgramHeader; property OnWriteExplanations: TConsoleOutputEvent read FOnWriteExplanations write FOnWriteExplanations; property OnWriteProgramVersion: TConsoleOutputEvent read FOnWriteProgramVersion write FOnWriteProgramVersion; end; implementation uses Options; { TOptionsValidator } { Private declarations } procedure TOptionsValidator.UpdateSearchPathFromDOFFile; var DOFFileName, SearchPath: String; begin DOFFileName := ExpandFileName(ChangeFileExt(TOptions.Instance.InputFile, '.dof')); if not FileExists(DOFFileName) then Exit; with TIniFile.Create(DOFFileName) do try if ValueExists('Directories', 'SearchPath') then SearchPath := ReadString('Directories', 'SearchPath', '') else SearchPath := ''; finally Free; end; with TOptions.Instance.SearchPath do Text := StringReplace(SearchPath, PathSep, SLineBreak, [rfReplaceAll]) + Text; end; { Protected declarations } procedure TOptionsValidator.DoWriteProgramHeader; begin if Assigned(FOnWriteProgramHeader) then FOnWriteProgramHeader; end; procedure TOptionsValidator.DoWriteExplanations; begin if Assigned(FOnWriteExplanations) then FOnWriteExplanations; end; procedure TOptionsValidator.DoWriteProgramVersion; begin if Assigned(FOnWriteProgramVersion) then FOnWriteProgramVersion; end; { Public declarations } procedure TOptionsValidator.Validate; begin if not TOptions.Instance.Quiet then DoWriteProgramHeader; if TOptions.Instance.Help then begin DoWriteExplanations; Halt(0); end; if TOptions.Instance.PrintVersion then begin DoWriteProgramVersion; Halt(0); end; if TOptions.Instance.InputFile = '' then begin Writeln('Error: no input file specified'); Halt(1); end; if not FileExists(TOptions.Instance.InputFile) then begin Writeln('Error: specified input file does not exists'); Halt(1); end; if TOptions.Instance.LeftList.Count > 0 then begin Writeln('Error: unrecognized option ', TOptions.Instance.LeftList[0]); Halt(2); end; UpdateSearchPathFromDOFFile; end; end.
(* Category: SWAG Title: POINTERS, LINKING, LISTS, TREES Original name: 0025.PAS Description: Avl Tree Tally Author: MATT BOUSEK Date: 08-24-94 14:00 *) (* Here is TALLY.PAS, a program that Matt Bousek <MBOUSEK@intel9.intel.com> wrote to do a word frequency analysis on a text file. It uses an AVL tree. It should compile under TP 6.0 or BP 7.0 *) program word_freq(input,output); type short_str = string[32]; {************AVLtree routines*********} type balance_set = (left_tilt,neutral,right_tilt); memptr = ^memrec; memrec = record balance : balance_set; left,right : memptr; count : longint; key : short_str; end; {**************************************} procedure rotate_right(var root:memptr); var ptr2,ptr3 : memptr; begin ptr2:=root^.right; if ptr2^.balance=right_tilt then begin root^.right:=ptr2^.left; ptr2^.left:=root; root^.balance:=neutral; root:=ptr2; end else begin ptr3:=ptr2^.left; ptr2^.left:=ptr3^.right; ptr3^.right:=ptr2; root^.right:=ptr3^.left; ptr3^.left:=root; if ptr3^.balance=left_tilt then ptr2^.balance:=right_tilt else ptr2^.balance:=neutral; if ptr3^.balance=right_tilt then root^.balance:=left_tilt else root^.balance:=neutral; root:=ptr3; end; root^.balance:=neutral; end; {*************************************} procedure rotate_left(var root:memptr); var ptr2,ptr3 : memptr; begin ptr2:=root^.left; if ptr2^.balance=left_tilt then begin root^.left:=ptr2^.right; ptr2^.right:=root; root^.balance:=neutral; root:=ptr2; end else begin ptr3:=ptr2^.right; ptr2^.right:=ptr3^.left; ptr3^.left:=ptr2; root^.left:=ptr3^.right; ptr3^.right:=root; if ptr3^.balance=right_tilt then ptr2^.balance:=left_tilt else ptr2^.balance:=neutral; if ptr3^.balance=left_tilt then root^.balance:=right_tilt else root^.balance:=neutral; root:=ptr3; end; root^.balance:=neutral; end; {*****************************************************************} procedure insert_mem(var root:memptr; x:short_str; var ok:boolean); begin if root=nil then begin new(root); with root^ do begin key:=x; left:=nil; right:=nil; balance:=neutral; count:=1; end; ok:=true; end else begin if x=root^.key then begin ok:=false; inc(root^.count); end else begin if x<root^.key then begin insert_mem(root^.left,x,ok); if ok then case root^.balance of left_tilt : begin rotate_left(root); ok:=false; end; neutral : root^.balance:=left_tilt; right_tilt : begin root^.balance:=neutral; ok:=false; end; end; end else begin insert_mem(root^.right,x,ok); if ok then case root^.balance of left_tilt : begin root^.balance:=neutral; ok:=false; end; neutral : root^.balance:=right_tilt; right_tilt : begin rotate_right(root); ok:=false; end; end; end; end; end; end; {*****************************************************} procedure insert_memtree(var root:memptr; x:short_str); var ok:boolean; begin ok:=false; insert_mem(root,x,ok); end; {*********************************} procedure dump_mem(var root:memptr); begin if root<>nil then begin dump_mem(root^.left); writeln(root^.count:5,' ',root^.key); dump_mem(root^.right); end; end; {MAIN***************************************************************} {*** This program was written by Matt Bousek sometime in 1992. ***} {*** The act of this posting over Internet makes the code public ***} {*** domain, but it would be nice to keep this header. ***} {*** The basic AVL routines came from a book called "Turbo Algo- ***} {*** rythms", Sorry, I don't have the book here and I can't ***} {*** remember the authors or publisher. Enjoy. And remember, ***} {*** there is no free lunch... ***} const wchars:set of char=['''','a'..'z']; var i,j : word; aword : short_str; subject : text; wstart,wend : word; inword : boolean; linecount : longint; wordcount : longint; buffer : array[1..10240] of char; line : string; filename : string; tree : memptr; BEGIN tree:=nil; filename:=paramstr(1); if filename='' then filename:='tally.pas'; assign(subject,filename); settextbuf(subject,buffer); reset(subject); wordcount:=0; linecount:=0; while not eof(subject) do begin inc(linecount); readln(subject,line); wstart:=0; wend:=0; for i:=1 to byte(line[0]) do begin if line[i] in ['A'..'Z'] then line[i]:=chr(ord(line[i])+32); inword:=(line[i] in wchars); if inword and (wstart=0) then wstart:=i; if inword and (wstart>0) then wend:=i; if not(inword) or (i=byte(line[0])) then begin if wend>wstart then begin aword:=copy(line,wstart,wend+1-wstart); j:=byte(aword[0]); if (aword[j]='''') and (j>2) then begin {lose trailing '} aword:=copy(aword,1,j-1); dec(wend); dec(j); end; if (aword[1]='''') and (j>2) then begin {lose leading '} aword:=copy(aword,2,j-1); inc(wstart); dec(j); end; if (j>2) and (aword[j-1]='''') and (aword[j]='s') then begin {lose trailing 's} aword:=copy(aword,1,j-2); dec(wend,2); dec(j,2); end; if (j>2) then begin inc(wordcount); insert_memtree(tree,aword); end; end; { **if wend>wstart** } wstart:=0; wend:=0; end; { **if not(inword)** } end; { **for byte(line[0])** } end; { **while not eof** } dump_mem(tree); writeln(linecount,' lines, ',wordcount,' words.'); END.
unit IdSoapBase64; { why does this unit exist - to solve version and performance problems with the indy decoders } interface uses classes; {$IFDEF UNICODE} function IdSoapBase64Decode(AValue : String) : TMemoryStream; overload; {$ENDIF} function IdSoapBase64Decode(AValue : AnsiString) : TMemoryStream; overload; function IdSoapBase64Decode(ASource : TStream) : TMemoryStream; overload; function IdSoapBase64Encode(AStream : TStream; AWrap : Boolean) : String; overload; function IdSoapBase64EncodeAnsi(AStream : TStream; AWrap : Boolean) : AnsiString; overload; implementation uses IdSoapClasses, IdSoapConsts, IdSoapUtilities, SysUtils; const ASSERT_UNIT = 'IdSoapBase64'; Function Ceiling(rValue : Real) : Int64; Begin { Function Ceiling } Result := Integer(Trunc(rValue)); If Frac(rValue) > 0 Then Inc(Result); End; { Function Ceiling } (* this code kindly donated to Grahame by Steven Genusa long ago. *) {$R-} const Base64Table: array[0..63] of AnsiChar = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'); procedure BuildBase64(OutBuf: pAnsiChar; Index: Longint; Significant: Integer; Value: Longint); var i: Integer; begin for i := 3 downto Significant do begin OutBuf[Index +i] := '='; Value := Value shr 6; end; for i := Significant - 1 downto 0 do begin OutBuf[Index +i] := Base64Table[Value and 63]; Value := Value shr 6; end; end; function Base64ToBinary(InBuf, OutBuf: pAnsiChar; InLen, OutLen: Longint): Longint; const ASSERT_LOCATION = ASSERT_UNIT+'.Base64ToBinary'; { This routine converts a Base64 encoded stream back to the original binary stream. No real error checking is done except to ignore unexpected data. For example, only valid Base64 ascii characters are acted upon and Pad characters are ignored unless they are the last or next-to-last characters in the input buffer. Futhermore, any partially decoded data is ignored if the input stream is too short to contain 4 Base64 characters. } var Value, InNdx, OutNdx: Longint; Count, Pad: Integer; begin Value := 0; Count := 0; Pad := 0; OutNdx := 0; for InNdx := 0 to InLen - 1 do begin begin case InBuf[InNdx] of 'A'..'Z': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('A')); Inc(Count); end; 'a'..'z': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('a')) + Longint(26); Inc(Count); end; '0'..'9': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('0')) + Longint(52); Inc(Count); end; '+': begin Value := (Value shl 6) + 62; Inc(Count); end; '/': begin Value := (Value shl 6) + 63; Inc(Count); end; '=': begin if InNdx >= InLen - 2 then begin Value := (Value shl 6); Inc(Count); Inc(Pad); end; end; end; end; { If we have decoded 4 characters then we need to build the output buffer. If any pad characters were detected then we adjust the values first to ensure we only generate as many output bytes as there originally were. } if Count = 4 then begin Count := 3; if Pad = 1 then begin {Only 16 bits were originally encoded } Value := Value shr 8; Count := 2; end else if Pad = 2 then begin {Only 8 bits were originally encoded } Value := Value shr 16; Count := 1; end; for Pad := Count - 1 downto 0 do begin assert(OutNdx + Pad < OutLen, ASSERT_LOCATION+': out of buffer space base64 decoding. ('+inttostr(OutNdx + Pad)+'/'+inttostr(OutLen)+')'); OutBuf[OutNdx + Pad] := AnsiChar(Value and 255); Value := Value shr 8; end; Inc(OutNdx, Count); Count := 0; Pad := 0; Value := 0; end; end; Result := OutNdx; end; function BinaryToBase64(InBuf, OutBuf: pAnsiChar; InLen: Longint; AWrap : Boolean): Longint; var InNdx, OutNdx, Width: Longint; begin InNdx := 0; OutNdx := 0; Width := 0; while InNdx + 3 <= InLen do begin BuildBase64(OutBuf, OutNdx, 4, (Longint(Ord(InBuf[InNdx])) shl 16) + (Longint(Ord(InBuf[InNdx + 1])) shl 8) + Longint(Ord(InBuf[InNdx + 2]))); inc(OutNdx, 4); inc(Width, 4); if (Width = 76) and AWrap then begin OutBuf[OutNdx + 0] := #13; OutBuf[OutNdx + 1] := #10; Width := 0; inc(OutNdx, 2); end; InNdx := InNdx + 3; end; if InLen - InNdx = 2 then begin BuildBase64(OutBuf, OutNdx, 3, (Longint(Ord(InBuf[InNdx])) shl 16) + (Longint(Ord(InBuf[InNdx + 1])) shl 8)); OutNdx := OutNdx + 4; end else if InLen - InNdx = 1 then begin BuildBase64(OutBuf, OutNdx, 2, Longint(Ord(InBuf[InNdx])) shl 16); OutNdx := OutNdx + 4; end; Result := OutNdx; end; function IdSoapBase64Encode(AStream : TStream; AWrap : Boolean) : String; begin result := string(IdSoapBase64EncodeAnsi(AStream, AWrap)); end; function IdSoapBase64EncodeAnsi(AStream : TStream; AWrap : Boolean) : AnsiString; var LTemp : Pointer; LSize : Integer; LStr : TMemoryStream; begin if AStream is TMemoryStream then begin LStr := AStream as TMemoryStream; GetMem(LTemp, Ceiling( (Ceiling(LStr.Size / 3) * 4) * (78/76))); // for wrapping space if we need it try LSize := BinaryToBase64(PAnsiChar(LStr.memory), PAnsiChar(LTemp), LStr.Size, AWrap); if LSize > 0 then begin SetLength(Result, LSize); Move(LTemp^, Result[1], LSize); end else begin result := ''; end; finally FreeMem(LTemp); end; end else begin // load it all into RAM. First time reviewers are generally suspicious of this approach, // as an exorbitant RAM waster - but it will usually be cloned a couple of times later, so we // might as well go for speed LStr := TIdMemoryStream.create; try LStr.CopyFrom(AStream, 0); LStr.position := 0; result := IdSoapBase64EncodeAnsi(LStr, AWrap); finally FreeAndNil(LStr); end; end; end; {$IFDEF UNICODE} function IdSoapBase64Decode(AValue : String) : TMemoryStream; begin result := IdSoapBase64Decode(AnsiString(AValue)); end; {$ENDIF} function IdSoapBase64Decode(AValue : AnsiString) : TMemoryStream; var LLen : integer; LTemp : Pointer; LSize : Integer; begin LLen := length(AValue); while (LLen >= 2) and (copy(AValue, LLen-1, 2) = EOL_WINDOWS) do begin dec(LLen, 2); end; result := TIdMemoryStream.create; if LLen > 0 then begin GetMem(LTemp, LLen); try LSize := Base64ToBinary(pAnsiChar(AValue), pAnsiChar(LTemp), LLen, LLen); result.Size := LSize; move(LTemp^, result.Memory^, LSize); finally FreeMem(LTemp); end; end; end; function IdSoapBase64Decode(ASource : TStream) : TMemoryStream; var LLen : integer; LTemp : AnsiString; begin LLen := (ASource.Size - ASource.Position); // well, we need everything in RAM anyway. // just make it happen SetLength(LTemp, Llen); if LLen > 0 then begin ASource.Read(LTemp[1], LLen); end; result := IdSoapBase64Decode(String(LTemp)); end; end.
unit typex; {$I DelphiDefs.inc} interface uses {$IFDEF NEED_FAKE_ANSISTRING} ios.stringx.iosansi, {$ENDIF} sysutils, variants, types; const {$IFDEF WINDOWS} NEWLINE = #13#10; {$ELSE} NEWLINE = #10; {$ENDIF} CR = #13; LF = #10; THOUSAND:int64 = 1000; MILLION:int64 = 1000000; BILLION:int64 = 1000000000; TRILLION:int64 = 1000000000000; QUADRILLION:int64 = 1000000000000000; PENTILLION:int64 = 1000000000000000000; BIT_THOUSAND:int64 = 1024; BIT_MILLION:int64 = 1024*1024; BIT_BILLION:int64 = 1024*1024*1024; BIT_TRILLION:int64 = 1099511627776; KILO:int64 = 1024; MEGA:int64 = 1024*1024; GIGA:int64 = 1024*1024*1024; TERA:int64 = 1099511627776; {$IF sizeof(pointer)=8} POINTER_SHIFT = 3; {$ELSE} POINTER_SHIFT_ = 2; {$ENDIF} type void = record end; {$IFDEF CPUx64} TSize = uint64; {$ELSE} TSize = cardinal; {$ENDIF} TriBool = (tbNull, tbFalse, tbTrue); EClassException = class(Exception); EBetterException = class(Exception); ENotImplemented = class(Exception); ECritical = class(Exception); ENetworkError = class(Exception); EUserError = class(Exception); EScriptVarError = class(Exception); {$IFDEF IS_64BIT} nativeQfloat = double; {$ELSE} nativefloat = single; {$ENDIF} DWORD = cardinal; PDWORD = ^DWORD; BOOL = wordbool; ni = nativeint; fi = integer; TDynByteArray = array of byte; TDynInt64Array = array of Int64; PInt16 = ^smallint; PInt32 = ^integer; tinyint = shortint; signedchar = shortint; signedbyte = shortint; {$IFDEF ZEROBASEDSTRINGS} const STRZERO = 0; {$ELSE} const STRZERO = 1; {$ENDIF} {$IFDEF GT_XE3} type TVolatileProgression = record StepsCompleted: nativeint; TotalSteps: nativeint; Complete: boolean; procedure Reset; end; PVolatileProgression = ^TVolatileProgression; TStringHelperEx = record {$IFDEF SUPPORTS_RECORD_HELPERS}helper for string{$ENDIF} function ZeroBased: boolean; function FirstIndex: nativeint; end; {$ELSE} {$Message Error 'we don''t support this compiler anymore'} {$ENDIF} {$IFDEF NEED_FAKE_ANSISTRING} type ansistring = ios.stringx.iosansi.ansistring; {$ENDIF} nf = nativefloat; ASingleArray = array[0..0] of system.Single; PSingleArray = ^ASingleArray; ADoubleArray = array[0..0] of system.Double; PDoubleArray = ^ADoubleArray; ASmallintArray = array[0..0] of smallint; PSmallintArray = ^ASmallintArray; ByteArray = array[0..0] of byte; PByteArray = ^ByteArray; complex = packed record r: double; i: double; end; complexSingle = packed record r: single; i: single; end; TNativeFloatRect = record x1,y1,x2,y2: nativefloat; end; PComplex = ^complex; TProgress = record step, stepcount: int64; function PercentComplete: single; end; PProgress = ^TProgress; TPixelRect = record //this rect behaves more like you'd expect TRect to behave in the Pixel context //if you make a rect from (0,0)-(1,1) the width is 2 and height is 2 private function GetRight: nativeint; procedure SetRight(const value: nativeint); function GetBottom: nativeint; procedure SetBottom(const value: nativeint); public Left, Top, Width, Height: nativeint; property Right: nativeint read GetRight write SetRight; property Bottom: nativeint read GetBottom write SetBottom; function ToRect: TRect; end; AComplexArray = array[0..0] of complex; PComplexArray = ^AComplexArray; AComplexSingleArray = array[0..0] of complexSingle; PComplexSingleArray = ^AComplexSingleArray; fftw_complex = complex; Pfftw_complex = PComplex; PAfftw_complex = PComplexArray; fftw_float = system.double; Pfftw_float = system.Pdouble; PAfftw_float = PDoubleArray; function PointToStr(pt:TPoint): string; function STRZ(): nativeint; function BoolToTriBool(b: boolean): TriBool;inline; function TriBoolToBool(tb: TriBool): boolean;inline; function BoolToint(b: boolean): integer; function InttoBool(i: integer): boolean; function DynByteArrayToInt64Array(a: TDynByteArray): TDynInt64Array; function DynInt64ArrayToByteArray(a: TDynInt64Array): TDynByteArray; function StringToTypedVariant(s: string): variant; function JavaScriptStringToTypedVariant(s: string): variant; function VartoStrEx(v: variant): string; function IsVarString(v: variant): boolean; function rect_notdumb(x1,y1,x2,y2: int64): TRect; function PixelRect(x1,y1,x2,y2: int64): TPixelRect; implementation uses systemx, numbers; function STRZ(): nativeint; //Returns the index of the first element of a string based on current configuration begin {$IFDEF MSWINDOWS} exit(1); {$ELSE} exit(0); {$ENDIF} end; { TStringHelperEx } {$IFDEF GT_XE3} function TStringHelperEx.FirstIndex: nativeint; begin result := STRZ; end; {$ENDIF} {$IFDEF GT_XE3} function TStringHelperEx.ZeroBased: boolean; begin result := STRZ=0; end; {$ENDIF} function BoolToTriBool(b: boolean): TriBool;inline; begin if b then result := tbTrue else result := tbFalse; end; function TriBoolToBool(tb: TriBool): boolean;inline; begin result := tb = tbTrue; end; function BoolToint(b: boolean): integer; begin if b then result := 1 else result := 0; end; function InttoBool(i: integer): boolean; begin result := i <> 0; end; function DynInt64ArrayToByteArray(a: TDynInt64Array): TDynByteArray; begin SetLength(result, length(a) * 8); movemem32(@result[0], @a[0], length(result)); end; function DynByteArrayToInt64Array(a: TDynByteArray): TDynInt64Array; begin SEtLength(result, length(a) shr 3); movemem32(@result[0], @a[0], length(a)); end; function JavaScriptStringToTypedVariant(s: string): variant; begin result := StringToTypedVariant(s); if varType(s) = varString then result := StringReplace(result, '\\','\', [rfReplaceall]); end; function StringToTypedVariant(s: string): variant; var c: char; bCanInt: boolean; bCanFloat: boolean; begin s := lowercase(s); if s = '' then exit(''); if s = 'null' then exit(null); if s = 'true' then exit(true); if s = 'false' then exit(false); bcanInt := true; bCanFloat := true; for c in s do begin if not charinset(c, ['-','0','1','2','3','4','5','6','7','8','9']) then bCanInt := false; if not charinset(c, ['-','.','E','0','1','2','3','4','5','6','7','8','9']) then bCanFloat := false; if not (bCanInt or bCanFloat) then break; end; if bCanInt then begin try if IsNumber(s) then exit(strtoint64(s)) else exit(s); except exit(s); end; end; if bCanFloat then begin try exit(strtofloat(s)); except exit(s); end; end; exit(s); end; function IsVarString(v: variant): boolean; begin result := (vartype(v) = varString) or (vartype(v) = varUString) or (vartype(v) = varOleStr) or (varType(v) = 0 (*null string*));// or (varType(v) = v); end; function VartoStrEx(v: variant): string; begin if vartype(v) = varNull then exit('null'); exit(vartostr(v)); end; function TProgress.PercentComplete: single; begin if StepCount = 0 then result := 0 else result := Step/StepCount; end; procedure TVolatileProgression.Reset; begin StepsCompleted := 0; Complete := false; end; function PointToStr(pt:TPoint): string; begin result := pt.x.tostring+','+pt.y.tostring; end; function rect_notdumb(x1,y1,x2,y2: int64): TRect; begin result.Left := x1; result.top := y1; result.Right := x2+1; result.Bottom := y2+1; end; function TPixelRect.GetRight: nativeint; begin result := (left+width)-1; end; procedure TPixelRect.SetRight(const value: nativeint); begin width := (value-left)+1; end; function TPixelRect.GetBottom: nativeint; begin result := (height+top)-1; end; procedure TPixelRect.SetBottom(const value: nativeint); begin height := (value-top)+1; end; function TPixelRect.ToRect: TRect; begin result.LEft := self.left; result.Top := self.top; result.width := self.width+1; result.Height := self.height+1; end; function PixelRect(x1,y1,x2,y2: int64): TPixelRect; begin result.Left := x1; result.Top := y1; result.Width := (x2-x1)+1; result.Height := (y2-y1)+1; end; end.
//--------------------------------------------------------------------------------------------- // // Archivo: HiloDescarga.pas // // Propósito: // Se trata de un descendiente de la clase THilo, que permite realizar la descarga de un // segmento de un recurso a través del API WinInet y el uso de la cabecera RANGE de HTTP. // Si se quieren recibir los eventos que la descarga de archivos genera, se debe implementar // un descendiente de esta clase, y sobrescribir los métodos virtuales "OnXXXXX". Esto se // hace en la clase THiloDescargaEventos. // // Autor: José Manuel Navarro - http://www.lawebdejm.com // Fecha: 01/05/2004 // Observaciones: Unidad creada en Delphi 5. // Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre que // SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos comentarios // o de cualquier otro modo. // //--------------------------------------------------------------------------------------------- unit HiloDescarga; interface uses Hilo, Windows, WinInet; type THiloDescarga = class(THilo) private FURL: string; FDestino: string; data: PByte; hFile: THandle; hMap: THandle; function parseURLData(URL: string; var host: string; var recurso: string): boolean; function getSize(conexion: HINTERNET; recurso: string): DWORD; function getHeader(byteIni, byteFin: DWORD): string; function openInternet(var hInet: HINTERNET): boolean; function connectInternet(hInet: HINTERNET; var hConn: HINTERNET; var recurso: string): boolean; function sendRequest(hConn: HINTERNET; var hRecurso: HINTERNET; recurso: string; var size: DWORD; var byteIni: DWORD; var byteFin: DWORD): boolean; procedure downloadFile(hRecurso: HINTERNET; data: PByte; byteIni: DWORD; var sizeDescargado: DWORD); function openFile(filename: string; size: DWORD): PByte; procedure saveFile(var data: PByte); protected function funcionHilo: DWORD; override; // // eventos // function onBeginDownload(var byteIni: DWORD; var byteFin: DWORD; size: DWORD): boolean; virtual; procedure onEndDownload(totalBytes: DWORD); virtual; function onProcessDownload(currentBytes: DWORD): boolean; virtual; procedure onCancelDownload(currentByte: DWORD); virtual; property URL: string read FURL; property Destino: string read FDestino; public function descargar(url, destino: string): boolean; virtual; end; implementation uses SysUtils; function THiloDescarga.parseURLData(URL: string; var host: string; var recurso: string): boolean; const SIZE_HOST = 128; SIZE_RECURSO = 256; var components: URL_COMPONENTS; buffHost: array[0..SIZE_HOST-1] of char; buffRecurso: array[0..SIZE_RECURSO-1] of char; begin ZeroMemory(@buffHost, SIZE_HOST); ZeroMemory(@buffRecurso, SIZE_RECURSO); // Preparo la estructura URL_COMPONENTS para descomponer la URL ZeroMemory(@components, sizeof(URL_COMPONENTS)); components.dwStructSize := sizeof(URL_COMPONENTS); components.dwHostNameLength := SIZE_HOST; components.lpszHostName := buffHost; components.dwUrlPathLength := SIZE_RECURSO; components.lpszUrlPath := buffRecurso; result := InternetCrackUrl(PChar(URL), 0, 0, components); if result then begin host := buffHost; recurso := buffRecurso; end; end; function THiloDescarga.getSize(conexion: HINTERNET; recurso: string): DWORD; var len, dummy: DWORD; hRecurso: HINTERNET; begin result := 0; hRecurso := HttpOpenRequest(conexion, 'HEAD', PChar(recurso), nil, nil, nil, INTERNET_FLAG_RELOAD, 0); if hRecurso <> nil then if HttpSendRequest(hRecurso, nil, 0, nil, 0) then begin len := sizeof(result); dummy := 0; if not HttpQueryInfo(hRecurso, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, Pointer(@result), len, dummy) then result := 0; end; InternetCloseHandle(hRecurso); end; function THiloDescarga.getHeader(byteIni, byteFin: DWORD): string; begin if (byteIni > 0) and (byteFin > 0) then result := Format('Range: bytes=%d-%d', [byteIni, byteFin]) else if byteIni > 0 then result := Format('Range: bytes=%d-', [byteIni, byteFin]) else result := ''; end; function THiloDescarga.openFile(filename: string; size: DWORD): PByte; begin result := nil; hFile := CreateFile(PChar(filename), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if hFile <> INVALID_HANDLE_VALUE then begin hMap := CreateFileMapping(hFile, nil, PAGE_READWRITE, 0, size, nil); if hMap = 0 then CloseHandle(hFile) else result := MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0); end; end; procedure THiloDescarga.saveFile(var data: PByte); begin FlushViewOfFile(data, 0); UnmapViewOfFile(data); data := nil; CloseHandle(hMap); CloseHandle(hFile); hMap := 0; hFile := 0; end; function THiloDescarga.funcionHilo: DWORD; var hInet, hConn, hRecurso: HINTERNET; recurso: string; size, sizeDescargado, byteIni, byteFin: DWORD; procedure CloseHandles(error: boolean); begin if hRecurso <> nil then InternetCloseHandle(hRecurso); if hConn <> nil then InternetCloseHandle(hConn); if hInet <> nil then InternetCloseHandle(hInet); if error then onCancelDownload(0) else if Cancelado then onCancelDownload(byteIni + sizeDescargado) else onEndDownload(byteIni + sizeDescargado); end; begin result := 0; hInet := nil; hConn := nil; hRecurso := nil; Cancelado := false; if not openInternet(hInet) then begin CloseHandles(true); exit; end; if not connectInternet(hInet, hConn, recurso) then begin CloseHandles(true); exit; end; if not sendRequest(hConn, hRecurso, recurso, size, byteIni, byteFin) then begin CloseHandles(true); exit; end; if FDestino[Length(FDestino)] <> '\' then FDestino := FDestino + '\'; FDestino := FDestino + (StrRScan(PChar(recurso), '/')+1); data := openFile(FDestino, size); if data = nil then begin CloseHandles(true); exit; end; downloadFile(hRecurso, data, byteIni, sizeDescargado); saveFile(data); CloseHandles(false); result := 1; end; function THiloDescarga.openInternet(var hInet: HINTERNET): boolean; begin hInet := InternetOpen('Multi-Descarga', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); result := (hInet <> nil); end; function THiloDescarga.connectInternet(hInet: HINTERNET; var hConn: HINTERNET; var recurso: string): boolean; var host: string; begin parseURLData(FURL, host, recurso); hConn := InternetConnect(hInet, PChar(host), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 0); result := (hConn <> nil); end; function THiloDescarga.sendRequest(hConn: HINTERNET; var hRecurso: HINTERNET; recurso: string; var size: DWORD; var byteIni: DWORD; var byteFin: DWORD): boolean; var header: string; begin result := false; hRecurso := HttpOpenRequest(hConn, 'GET', PChar(recurso), nil, nil, nil, INTERNET_FLAG_RELOAD, 0); size := getSize(hConn, recurso); if size = 0 then exit; byteIni := 0; byteFin := size; if not onBeginDownload(byteIni, byteFin, size) then exit; if (byteIni > 0) or (byteFin > size) then begin header := getHeader(byteIni, byteFin); if header <> '' then HttpAddRequestHeaders(hRecurso, PChar(header), Length(header), HTTP_ADDREQ_FLAG_ADD_IF_NEW); end; result := HttpSendRequest(hRecurso, nil, 0, nil, 0); end; procedure THiloDescarga.downloadFile(hRecurso: HINTERNET; data: PByte; byteIni: DWORD; var sizeDescargado: DWORD); const CHUNK_SIZE = 4 * 1024; var leido: DWORD; dataPtr: PByte; buffer: array[0..CHUNK_SIZE-1] of Byte; begin dataPtr := data; Inc(dataPtr, byteIni); sizeDescargado := 0; repeat ZeroMemory(@buffer, sizeof(buffer)); InternetReadFile(hRecurso, @buffer, sizeof(buffer), leido); if leido > 0 then begin CopyMemory(dataPtr, @buffer, leido); Inc(sizeDescargado, leido); Inc(dataPtr, leido); if not onProcessDownload(sizeDescargado + byteIni) then exit; end; until Cancelado or (leido = 0); if not Cancelado then begin dataPtr := data; Inc(dataPtr, sizeDescargado + byteIni); dataPtr^ := 0; end; end; // // eventos // function THiloDescarga.onBeginDownload(var byteIni: DWORD; var byteFin: DWORD; size: DWORD): boolean; begin result := false; end; procedure THiloDescarga.onEndDownload(totalBytes: DWORD); begin end; function THiloDescarga.onProcessDownload(currentBytes: DWORD): boolean; begin result := false; end; procedure THiloDescarga.onCancelDownload(currentByte: DWORD); begin end; function THiloDescarga.descargar(url, destino: string): boolean; begin FURL := url; FDestino := destino; iniciar(true); arrancar(); result := true; end; end.
unit DiffieHellman; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CryptoUtils; type TDiffieHellmanRequest = record Generator : DWORD; Modulus : DWORD; Interim : DWORD; end; TDiffieHellmanResponse = record Interim : DWORD; end; { TDiffieHellman } TDiffieHellman = class(TObject) private FModulus : DWORD; FGenerator : DWORD; FPrivateA : DWORD; FPrivateB : DWORD; FInterimA : DWORD; FInterimB : DWORD; FKey : DWORD; // procedure Clean; procedure CreateKeys(out Generator, Modulus: DWORD); function CreateSenderInterKey: DWORD; function CreateRecipientInterKey(Generator, Modulus: DWORD): DWORD; procedure CreateSenderEncryptionKey(RecipientInterKey: DWORD); procedure CreateRecipientEncryptionKey(SenderInterKey: DWORD); public constructor Create; destructor Destroy; override; // procedure Clear; function GenerateRequest: TDiffieHellmanRequest; function ProcessRequest(Request: TDiffieHellmanRequest): TDiffieHellmanResponse; procedure ReceiveResponse(Response: TDiffieHellmanResponse); // property Key: DWORD read FKey; end; TDiffieHellman128Request = array[0..3] of TDiffieHellmanRequest; PDiffieHellman128Request = ^TDiffieHellman128Request; TDiffieHellman128Response = array[0..3] of TDiffieHellmanResponse; PDiffieHellman128Response = ^TDiffieHellman128Response; { TDiffieHellman128 } TDiffieHellman128 = class(TObject) private A: array[0..3] of TDiffieHellman; function GetKey: TKey128; public constructor Create; destructor Destroy; override; procedure Clear; function GenerateRequest: TDiffieHellman128Request; function ProcessRequest(Request: TDiffieHellman128Request): TDiffieHellman128Response; procedure ReceiveResponse(Response: TDiffieHellman128Response); function KeysMatch(DH: TDiffieHellman128): Boolean; property Key: TKey128 read GetKey; end; TDiffieHellman256Request = array[0..7] of TDiffieHellmanRequest; PDiffieHellman256Request = ^TDiffieHellman256Request; TDiffieHellman256Response = array[0..7] of TDiffieHellmanResponse; PDiffieHellman256Response = ^TDiffieHellman256Response; { TDiffieHellman256 } TDiffieHellman256 = class(TObject) private A: array[0..7] of TDiffieHellman; function GetKey: TKey256; public constructor Create; destructor Destroy; override; procedure Clear; function GenerateRequest: TDiffieHellman256Request; function ProcessRequest(Request: TDiffieHellman256Request): TDiffieHellman256Response; procedure ReceiveResponse(Response: TDiffieHellman256Response); function KeysMatch(DH: TDiffieHellman256): Boolean; property Key: TKey256 read GetKey; end; function DHRequestToStr(Request: TDiffieHellmanRequest): String; function DHResponseToStr(Response: TDiffieHellmanResponse): String; function DH128RequestToStr(Request: TDiffieHellman128Request): String; function DH128ResponseToStr(Response: TDiffieHellman128Response): String; function DH256RequestToStr(Request: TDiffieHellman256Request): String; function DH256ResponseToStr(Response: TDiffieHellman256Response): String; implementation uses Rand; function DHRequestToStr(Request: TDiffieHellmanRequest): String; begin Result := Format('Generator=%s Interim=%s Modulus=%s',[ BufferToHex(@Request.Generator,SizeOf(Request.Generator)), BufferToHex(@Request.Interim,SizeOf(Request.Interim)), BufferToHex(@Request.Modulus,SizeOf(Request.Modulus)) ]); end; function DHResponseToStr(Response: TDiffieHellmanResponse): String; begin Result := Format('Interim=%s',[BufferToHex(@Response.Interim,SizeOf(Response.Interim))]); end; function DH128RequestToStr(Request: TDiffieHellman128Request): String; begin Result := '[0] '+DHRequestToStr(Request[0])+#13#10+ '[1] '+DHRequestToStr(Request[1])+#13#10+ '[2] '+DHRequestToStr(Request[2])+#13#10+ '[3] '+DHRequestToStr(Request[3])+#13#10; end; function DH128ResponseToStr(Response: TDiffieHellman128Response): String; begin Result := '[0] '+DHResponseToStr(Response[0])+#13#10+ '[1] '+DHResponseToStr(Response[1])+#13#10+ '[2] '+DHResponseToStr(Response[2])+#13#10+ '[3] '+DHResponseToStr(Response[3])+#13#10; end; function DH256RequestToStr(Request: TDiffieHellman256Request): String; begin Result := '[0] '+DHRequestToStr(Request[0])+#13#10+ '[1] '+DHRequestToStr(Request[1])+#13#10+ '[2] '+DHRequestToStr(Request[2])+#13#10+ '[3] '+DHRequestToStr(Request[3])+#13#10+ '[4] '+DHRequestToStr(Request[4])+#13#10+ '[5] '+DHRequestToStr(Request[5])+#13#10+ '[6] '+DHRequestToStr(Request[6])+#13#10+ '[7] '+DHRequestToStr(Request[7])+#13#10; end; function DH256ResponseToStr(Response: TDiffieHellman256Response): String; begin Result := '[0] '+DHResponseToStr(Response[0])+#13#10+ '[1] '+DHResponseToStr(Response[1])+#13#10+ '[2] '+DHResponseToStr(Response[2])+#13#10+ '[3] '+DHResponseToStr(Response[3])+#13#10+ '[4] '+DHResponseToStr(Response[4])+#13#10+ '[5] '+DHResponseToStr(Response[5])+#13#10+ '[6] '+DHResponseToStr(Response[6])+#13#10+ '[7] '+DHResponseToStr(Response[7])+#13#10; end; { TDiffieHellman } constructor TDiffieHellman.Create; begin Clear; end; destructor TDiffieHellman.Destroy; begin Clear; inherited Destroy; end; // Zeros everything except key procedure TDiffieHellman.Clean; begin FGenerator := 0; FModulus := 0; FPrivateA := 0; FPrivateB := 0; FInterimA := 0; FInterimB := 0; end; // Zeros everything procedure TDiffieHellman.Clear; begin Clean; FKey := 0; end; function TDiffieHellman.GenerateRequest: TDiffieHellmanRequest; begin CreateKeys(Result.Generator,Result.Modulus); Result.Interim := CreateSenderInterKey; end; function TDiffieHellman.ProcessRequest(Request: TDiffieHellmanRequest): TDiffieHellmanResponse; begin Result.Interim := CreateRecipientInterKey(Request.Generator,Request.Modulus); CreateRecipientEncryptionKey(Request.Interim); Clean; end; procedure TDiffieHellman.ReceiveResponse(Response: TDiffieHellmanResponse); begin CreateSenderEncryptionKey(Response.Interim); Clean; end; procedure TDiffieHellman.CreateKeys(out Generator, Modulus: DWORD); var Swap: DWORD; begin FGenerator := GeneratePrime; FModulus := GeneratePrime; if FGenerator > FModulus then begin Swap := FGenerator; FGenerator := FModulus; FModulus := Swap; end; Generator := FGenerator; Modulus := FModulus; end; function TDiffieHellman.CreateSenderInterKey: DWORD; begin FPrivateA := RNG.Generate; FInterimA := XpowYmodN(FGenerator,FPrivateA,FModulus); Result := FInterimA; end; function TDiffieHellman.CreateRecipientInterKey(Generator, Modulus: DWORD): DWORD; begin FPrivateB := RNG.Generate; FGenerator := Generator; FModulus := Modulus; FInterimB := XpowYmodN(FGenerator,FPrivateB,FModulus); Result := FInterimB; end; procedure TDiffieHellman.CreateSenderEncryptionKey(RecipientInterKey: DWORD); begin FInterimB := RecipientInterKey; FKey := XpowYmodN(FInterimB,FPrivateA,FModulus); end; procedure TDiffieHellman.CreateRecipientEncryptionKey(SenderInterKey: DWORD); begin FInterimA := SenderInterKey; FKey := XpowYmodN(FInterimA,FPrivateB,FModulus); end; { TDiffieHellman128 } constructor TDiffieHellman128.Create; var I: Byte; begin for I := 0 to 3 do A[I] := TDiffieHellman.Create; end; destructor TDiffieHellman128.Destroy; var I: Byte; begin for I := 0 to 3 do A[I].Destroy; inherited Destroy; end; procedure TDiffieHellman128.Clear; var I: Byte; begin for I := 0 to 3 do A[I].Clear; end; function TDiffieHellman128.GetKey: TKey128; var X: Byte; D: DWORD; begin for X := 0 to 3 do begin D := A[X].Key; Result[X*4+0] := (D and $FF000000) shr 24; Result[X*4+1] := (D and $FF0000 ) shr 16; Result[X*4+2] := (D and $FF00 ) shr 8; Result[X*4+3] := (D and $FF ); end; end; function TDiffieHellman128.GenerateRequest: TDiffieHellman128Request; var I: Byte; begin for I := 0 to 3 do Result[I] := A[I].GenerateRequest; end; function TDiffieHellman128.ProcessRequest(Request: TDiffieHellman128Request): TDiffieHellman128Response; var I: Byte; begin for I := 0 to 3 do Result[I] := A[I].ProcessRequest(Request[I]); end; procedure TDiffieHellman128.ReceiveResponse(Response: TDiffieHellman128Response); var I: Byte; begin for I := 0 to 3 do A[I].ReceiveResponse(Response[I]); end; function TDiffieHellman128.KeysMatch(DH: TDiffieHellman128): Boolean; var I: Integer; Key1, Key2: TKey128; begin Key1 := Key; Key2 := DH.Key; for I := 0 to 15 do if Key1[I] <> Key2[I] then begin Result := False; Exit; end; Result := True; end; { TDiffieHellman256 } constructor TDiffieHellman256.Create; var I: Byte; begin for I := 0 to 7 do A[I] := TDiffieHellman.Create; end; destructor TDiffieHellman256.Destroy; var I: Byte; begin for I := 0 to 7 do A[I].Destroy; inherited Destroy; end; procedure TDiffieHellman256.Clear; var I: Byte; begin for I := 0 to 7 do A[I].Clear; end; function TDiffieHellman256.GetKey: TKey256; var X: Byte; D: DWORD; begin for X := 0 to 7 do begin D := A[X].Key; Result[X] := D; { Result[X*4+0] := (D and $FF000000) shr 24; Result[X*4+1] := (D and $FF0000 ) shr 16; Result[X*4+2] := (D and $FF00 ) shr 8; Result[X*4+3] := (D and $FF ); } end; end; function TDiffieHellman256.GenerateRequest: TDiffieHellman256Request; var I: Byte; begin for I := 0 to 7 do Result[I] := A[I].GenerateRequest; end; function TDiffieHellman256.ProcessRequest(Request: TDiffieHellman256Request): TDiffieHellman256Response; var I: Byte; begin for I := 0 to 7 do Result[I] := A[I].ProcessRequest(Request[I]); end; procedure TDiffieHellman256.ReceiveResponse(Response: TDiffieHellman256Response); var I: Byte; begin for I := 0 to 7 do A[I].ReceiveResponse(Response[I]); end; function TDiffieHellman256.KeysMatch(DH: TDiffieHellman256): Boolean; var I: Integer; Key1, Key2: TKey256; begin Key1 := Key; Key2 := DH.Key; for I := 0 to 31 do if Key1[I] <> Key2[I] then begin Result := False; Exit; end; Result := True; end; end.
unit UDataModuleNFe; interface uses SysUtils, Classes, DB, DBClient, WideStrings, DBXMySql, FMTBcd, Provider, SqlExpr, Biblioteca; type TFDataModuleNFe = class(TDataModule) CDSVolumes: TClientDataSet; DSVolumes: TDataSource; CDSNfReferenciada: TClientDataSet; DSNfReferenciada: TDataSource; CDSCteReferenciado: TClientDataSet; DSCteReferenciado: TDataSource; CDSNfRuralReferenciada: TClientDataSet; DSNfRuralReferenciada: TDataSource; CDSCupomReferenciado: TClientDataSet; DSCupomReferenciado: TDataSource; CDSDuplicata: TClientDataSet; DSDuplicata: TDataSource; CDSNfeReferenciada: TClientDataSet; DSNfeReferenciada: TDataSource; CDSNfeDetalhe: TClientDataSet; DSNfeDetalhe: TDataSource; CDSReboque: TClientDataSet; DSReboque: TDataSource; CDSNfeImpostoCofins: TClientDataSet; DSNfeImpostoCofins: TDataSource; CDSNfeImpostoIcms: TClientDataSet; DSNfeImpostoIcms: TDataSource; CDSNfeImpostoImportacao: TClientDataSet; DSNfeImpostoImportacao: TDataSource; CDSNfeImpostoIpi: TClientDataSet; DSNfeImpostoIpi: TDataSource; CDSNfeImpostoIssqn: TClientDataSet; DSNfeImpostoIssqn: TDataSource; CDSNfeImpostoPis: TClientDataSet; DSNfeImpostoPis: TDataSource; CDSNfeDeclaracaoImportacao: TClientDataSet; DSNfeDeclaracaoImportacao: TDataSource; CDSNfeImportacaoDetalhe: TClientDataSet; DSNfeImportacaoDetalhe: TDataSource; CDSNfeDetalheVeiculo: TClientDataSet; DSNfeDetalheVeiculo: TDataSource; CDSNfeDetalheArmamento: TClientDataSet; DSNfeDetalheArmamento: TDataSource; CDSNfeDetalheCombustivel: TClientDataSet; DSNfeDetalheCombustivel: TDataSource; CDSNfeDetalheMedicamento: TClientDataSet; DSNfeDetalheMedicamento: TDataSource; CDSVolumesLacres: TClientDataSet; DSVolumesLacres: TDataSource; CDSNfeNumero: TClientDataSet; DSNfeNumero: TDataSource; procedure ControlaPersistencia(pDataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FDataModuleNFe: TFDataModuleNFe; implementation uses NfeDetalheImpostoCofinsVO, NfeDetalheImpostoIcmsVO, NfeNumeroVO, NfeDetalheImpostoPisVO, NfeDetalheImpostoIiVO, NfeDetalheImpostoIssqnVO, NfeDetalheImpostoIpiVO, NfeDeclaracaoImportacaoVO, NfeImportacaoDetalheVO, NfeDetEspecificoVeiculoVO, NfeDetEspecificoCombustivelVO; {$R *.dfm} { TFDataModuleNFe } procedure TFDataModuleNFe.ControlaPersistencia(pDataSet: TDataSet); begin pDataSet.FieldByName('PERSISTE').AsString := 'S'; end; procedure TFDataModuleNFe.DataModuleCreate(Sender: TObject); begin ConfiguraCDSFromVO(CDSNfeImpostoIcms, TNfeDetalheImpostoIcmsVO); CDSNfeImpostoIcms.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoIcms.MasterSource := DSNfeDetalhe; CDSNfeImpostoIcms.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeImpostoPis, TNfeDetalheImpostoPisVO); CDSNfeImpostoPis.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoPis.MasterSource := DSNfeDetalhe; CDSNfeImpostoPis.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeImpostoCofins, TNfeDetalheImpostoCofinsVO); CDSNfeImpostoCofins.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoCofins.MasterSource := DSNfeDetalhe; CDSNfeImpostoCofins.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeImpostoIpi, TNfeDetalheImpostoIpiVO); CDSNfeImpostoIpi.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoIpi.MasterSource := DSNfeDetalhe; CDSNfeImpostoIpi.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeImpostoImportacao, TNfeDetalheImpostoIiVO); CDSNfeImpostoImportacao.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoImportacao.MasterSource := DSNfeDetalhe; CDSNfeImpostoImportacao.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeImpostoIssqn, TNfeDetalheImpostoIssqnVO); CDSNfeImpostoIssqn.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeImpostoIssqn.MasterSource := DSNfeDetalhe; CDSNfeImpostoIssqn.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeDetalheCombustivel, TNfeDetEspecificoCombustivelVO); CDSNfeDetalheCombustivel.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeDetalheCombustivel.MasterSource := DSNfeDetalhe; CDSNfeDetalheCombustivel.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeDetalheVeiculo, TNfeDetEspecificoVeiculoVO); CDSNfeDetalheVeiculo.IndexFieldNames := 'ID_NFE_DETALHE'; CDSNfeDetalheVeiculo.MasterSource := DSNfeDetalhe; CDSNfeDetalheVeiculo.MasterFields := 'ID'; ConfiguraCDSFromVO(CDSNfeNumero, TNfeNumeroVO); end; end.
unit SubscriptionsForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, StdCtrls, ExtCtrls, FolderList, SubUtils, CommCtrl; type TformSubscriptions = class(TForm) Panel2: TPanel; Panel3: TPanel; butnOk: TButton; butnCancel: TButton; Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; Label1: TLabel; Panel1: TPanel; lstvAccounts: TListView; Bevel4: TBevel; Bevel5: TBevel; Panel4: TPanel; butnSubscribe: TButton; butnUnsubscribe: TButton; butnResetList: TButton; Panel5: TPanel; Bevel6: TBevel; editSearch: TEdit; pctlMain: TPageControl; tshtAll: TTabSheet; tshtSub: TTabSheet; Panel6: TPanel; Label2: TLabel; Panel7: TPanel; ilstAll: TImageList; ilstAccounts: TImageList; timrSearch: TTimer; cboxSearchDescriptions: TCheckBox; procedure DetermineProtection(Sender: TObject); procedure butnSubscribeClick(Sender: TObject); procedure butnUnsubscribeClick(Sender: TObject); procedure butnResetListClick(Sender: TObject); procedure butnOkClick(Sender: TObject); procedure lstvAccountsDeletion(Sender: TObject; Item: TListItem); procedure lstvAccountsChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormShow(Sender: TObject); procedure timrSearchTimer(Sender: TObject); procedure editSearchChange(Sender: TObject); procedure cboxSearchDescriptionsClick(Sender: TObject); private FHostItem: TListItem; protected function ActiveListView : TListView; public constructor Create(AOwner: TComponent); override; end; implementation uses MainForm, ListingForm, Datamodule, DbTables, DemoUtils; {$R *.DFM} constructor TformSubscriptions.Create(AOwner: TComponent); var Node: TTreeNode; Item: TListItem; begin inherited Create(AOwner); Node := formMain.lstvFolders.Items.GetFirstNode.GetFirstChild; while Assigned(Node) do begin Item := lstvAccounts.Items.Add; Item.Caption := Node.Text; Item.ImageIndex := 0; Item.Data := TSubscriptionData.Create(Panel6, Panel7, ilstAll); TSubscriptionData(Item.Data).HostData := Node.Data; if Item.Caption = formMain.lstvFolders.Selected.Text then FHostItem := Item; Node := Node.GetNextChild(Node); end; lstvAccounts.OnChange := lstvAccountsChange; end; function TformSubscriptions.ActiveListView : TListView; begin if pctlMain.ActivePage = tshtAll then Result := TSubscriptionData(lstvAccounts.Selected.Data).ViewAll else Result := TSubscriptionData(lstvAccounts.Selected.Data).ViewSub; end; procedure TformSubscriptions.DetermineProtection(Sender: TObject); var SubData: TSubscriptionData; IndexAll, IndexSub: Integer; begin if Assigned(lstvAccounts.Selected) then SubData := TSubscriptionData(lstvAccounts.Selected.Data) else SubData := nil; if Assigned(SubData) then begin IndexAll := SubData.ViewAll.GetNextItem(-1, LVNI_ALL or LVNI_SELECTED); IndexSub := SubData.ViewSub.GetNextItem(-1, LVNI_ALL or LVNI_SELECTED); end else begin IndexAll := -1; IndexSub := -1; end; {-The protection of sub/unsub buttons needs to be extended} butnResetList.Enabled := Assigned(SubData) and (pctlMain.ActivePage = tshtAll); butnSubscribe.Enabled := butnResetList.Enabled and (IndexAll <> -1); if pctlMain.ActivePage = tshtAll then butnUnsubscribe.Enabled := butnSubscribe.Enabled else if pctlMain.ActivePage = tshtSub then butnUnsubscribe.Enabled := Assigned(SubData) and (IndexSub <> -1); end; procedure TformSubscriptions.butnSubscribeClick(Sender: TObject); var Index: Integer; SubData: TSubscriptionData; NewsRec: PNewsRec; begin SubData := TSubscriptionData(lstvAccounts.Selected.Data); SubData.Modified := True; SubData.BeginUpdate; try Index := SubData.ViewAll.GetNextItem(-1, LVNI_ALL or LVNI_SELECTED); while Index <> -1 do begin NewsRec := SubData.GetAllNewsRec(Index); NewsRec^.Subscribed := True; NewsRec^.Modified := True; Index := SubData.ViewAll.GetNextItem(Index, LVNI_ALL or LVNI_SELECTED); end; finally SubData.RefreshSubList; SubData.EndUpdate; end; DetermineProtection(Sender); end; procedure TformSubscriptions.butnUnsubscribeClick(Sender: TObject); var Index: Integer; SubData: TSubscriptionData; NewsRec: PNewsRec; begin SubData := TSubscriptionData(lstvAccounts.Selected.Data); SubData.Modified := True; SubData.BeginUpdate; try if pctlMain.ActivePage = tshtSub then begin Index := SubData.ViewSub.GetNextItem(-1, LVNI_ALL or LVNI_SELECTED); while Index <> -1 do begin NewsRec := SubData.GetSubNewsRec(Index); NewsRec^.Subscribed := False; NewsRec^.Modified := True; Index := SubData.ViewSub.GetNextItem(Index, LVNI_ALL or LVNI_SELECTED); end; end else begin Index := SubData.ViewAll.GetNextItem(-1, LVNI_ALL or LVNI_SELECTED); while Index <> -1 do begin NewsRec := SubData.GetAllNewsRec(Index); NewsRec^.Subscribed := False; NewsRec^.Modified := True; Index := SubData.ViewAll.GetNextItem(Index, LVNI_ALL or LVNI_SELECTED); end; end; finally SubData.EndUpdate; SubData.RefreshSubList; end; DetermineProtection(Sender); end; procedure TformSubscriptions.butnResetListClick(Sender: TObject); var SubData: TSubscriptionData; begin SubData := TSubscriptionData(lstvAccounts.Selected.Data); SubData.BeginUpdate; try with TformListing.Create(Self) do begin try HostData := SubData.HostData; Show; SubData.Load; finally Free; end; end; finally SubData.EndUpdate; ActiveListView.SetFocus; end; DetermineProtection(Sender); end; procedure TformSubscriptions.lstvAccountsDeletion(Sender: TObject; Item: TListItem); begin if Assigned(Item.Data) then TObject(Item.Data).Free; end; procedure TformSubscriptions.lstvAccountsChange(Sender: TObject; Item: TListItem; Change: TItemChange); var SubData: TSubscriptionData; X: Integer; begin if Visible and Assigned(Item) and Item.Selected and (Change = ctState) then begin SubData := TSubscriptionData(Item.Data); SubData.ViewAll.Visible := True; SubData.ViewSub.Visible := True; for X := 0 to Pred(lstvAccounts.Items.Count) do begin if lstvAccounts.Items[X].Data <> SubData then begin TSubscriptionData(lstvAccounts.Items[X].Data).ViewAll.Visible := False; TSubscriptionData(lstvAccounts.Items[X].Data).ViewSub.Visible := False; end; end; if not SubData.Loaded then begin ActiveListView.Refresh; SubData.Load; end; end; end; procedure TformSubscriptions.butnOkClick(Sender: TObject); var AcctItem: TListItem; SubData: TSubscriptionData; begin AcctItem := lstvAccounts.GetNextItem(nil, sdAll, [isNone]); while Assigned(AcctItem) do begin SubData := TSubscriptionData(AcctItem.Data); if SubData.Modified then begin SubData.Save; SubData.HostData.Modified := True; end; AcctItem := lstvAccounts.GetNextItem(AcctItem, sdAll, [isNone]); end; end; procedure TformSubscriptions.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var Item: TListItem; begin if ModalResult = mrCancel then begin Item := lstvAccounts.GetNextItem(nil, sdAll, [isNone]); while Assigned(Item) do begin if TSubscriptionData(lstvAccounts.Selected.Data).Modified then begin CanClose := MessageDlg('Changes have been made, do you wish to abandon them?', mtWarning, [mbYes, mbNo], 0) = mrYes; Exit; end; Item := lstvAccounts.GetNextItem(Item, sdAll, [isNone]); end; end; end; procedure TformSubscriptions.FormShow(Sender: TObject); begin DetermineProtection(Sender); Refresh; lstvAccounts.Selected := FHostItem; lstvAccounts.ItemFocused := FHostItem; if Assigned(lstvAccounts.Selected) then begin if ActiveListView.Items.Count = 0 then begin if MessageDlg('Would you like to download the list of available newsgroups?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then butnResetListClick(Sender); end; end; end; procedure TformSubscriptions.timrSearchTimer(Sender: TObject); var SubData: TSubscriptionData; begin SubData := TSubscriptionData(lstvAccounts.Selected.Data); SubData.Filter := editSearch.Text; timrSearch.Enabled := False; ActiveListView.SetFocus; end; procedure TformSubscriptions.editSearchChange(Sender: TObject); begin timrSearch.Enabled := False; {-Resets the timer} timrSearch.Enabled := True; end; procedure TformSubscriptions.cboxSearchDescriptionsClick(Sender: TObject); var SubData: TSubscriptionData; begin SubData := TSubscriptionData(lstvAccounts.Selected.Data); SubData.SearchDesc := cboxSearchDescriptions.Checked; end; end.
unit ssl_ecdh; interface uses ssl_types; var ECDH_OpenSSL: function: PECDH_METHOD; cdecl = nil; ECDH_set_default_method: procedure(const _p: PECDH_METHOD); cdecl = nil; ECDH_get_default_method: function: PECDH_METHOD; cdecl = nil; ECDH_set_method: function(_key: PEC_KEY; const _p: PECDH_METHOD): TC_INT; cdecl = nil; ECDH_compute_key: function(_out: Pointer; outlen: TC_SIZE_T; const _pub_key: PEC_POINT; _ecdh: PEC_KEY; KDF: ecdh_kdf): TC_INT; cdecl = nil; ECDH_get_ex_new_index: function(_argl: TC_LONG; _argp: Pointer; _new_func: CRYPTO_EX_new; _dup_func: CRYPTO_EX_dup; _free_func: CRYPTO_EX_free): TC_INT; cdecl = nil; ECDH_set_ex_data: function(_d: PEC_KEY; _idx: TC_INT; _arg: Pointer): TC_INT; cdecl = nil; ECDH_get_ex_data: function(_d: Pointer; _idx: TC_INT): Pointer; cdecl = nil; ERR_load_ECDH_strings: procedure; cdecl = nil; procedure SSL_InitSSLDH; implementation uses ssl_lib; procedure SSL_InitSSLDH; begin if @ECDH_OpenSSL = nil then begin @ECDH_OpenSSL:= LoadFunctionCLib('ECDH_OpenSSL'); @ECDH_set_default_method:= LoadFunctionCLib('ECDH_set_default_method'); @ECDH_get_default_method:= LoadFunctionCLib('ECDH_get_default_method'); @ECDH_set_method:= LoadFunctionCLib('ECDH_set_method'); @ECDH_compute_key:= LoadFunctionCLib('ECDH_compute_key'); @ECDH_get_ex_new_index:= LoadFunctionCLib('ECDH_get_ex_new_index'); @ECDH_set_ex_data:= LoadFunctionCLib('ECDH_set_ex_data'); @ECDH_get_ex_data:= LoadFunctionCLib('ECDH_get_ex_data'); @ERR_load_ECDH_strings:= LoadFunctionCLib('ERR_load_ECDH_strings'); end; end; end.
unit BalanceColor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ExtCtrls, ComCtrls, StdCtrls, LibGfl, RzTrkBar, cxLookAndFeelPainters, ActnList, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit; type TfrmBalanceColor = class(TForm) Image: TImage; Panel1: TPanel; tbRed: TRzTrackBar; tbGreen: TRzTrackBar; tbBlue: TRzTrackBar; Panel3: TPanel; OK: TcxButton; Cancel: TcxButton; ActionList1: TActionList; Label1: TLabel; Label2: TLabel; Label3: TLabel; cxSpinEdit1: TcxSpinEdit; cxSpinEdit2: TcxSpinEdit; cxSpinEdit3: TcxSpinEdit; Label4: TLabel; ActionOK: TAction; Panel4: TPanel; ImageOrig: TImage; Label5: TLabel; Label6: TLabel; Label7: TLabel; procedure Button1Click(Sender: TObject); procedure tbRedChange(Sender: TObject); procedure ActionOKExecute(Sender: TObject); procedure cxSpinEdit1PropertiesChange(Sender: TObject); procedure cxSpinEdit2PropertiesChange(Sender: TObject); procedure cxSpinEdit3PropertiesChange(Sender: TObject); procedure tbGreenChange(Sender: TObject); procedure tbBlueChange(Sender: TObject); procedure CreatingBMP; procedure FormDestroy(Sender: TObject); private FClonBitmap: PGFL_BITMAP; FColor3: Integer; FColor1: Integer; FColor2: Integer; FOriginalBMP: PGFL_BITMAP; Fhbmp: HBitmap; FtmBlue: Integer; FtmRed: Integer; FtmGreen: Integer; FColorGreen: Integer; FColorRed: Integer; FColorBlue: Integer; procedure SetColor1(const Value: Integer); procedure SetColor2(const Value: Integer); procedure SetColor3(const Value: Integer); procedure ApplyUpdates; function CalSize(var X, Y: Integer; ASize: Integer): Boolean; procedure SetOriginalBMP(const Value: PGFL_BITMAP); procedure SettmBlue(const Value: Integer); procedure SettmGreen(const Value: Integer); procedure SettmRed(const Value: Integer); procedure SetColorBlue(const Value: Integer); procedure SetColorGreen(const Value: Integer); procedure SetColorRed(const Value: Integer); public property ColorRed: Integer read FColorRed write SetColorRed; property ColorGreen: Integer read FColorGreen write SetColorGreen; property ColorBlue: Integer read FColorBlue write SetColorBlue; property OriginalBMP: PGFL_BITMAP read FOriginalBMP write SetOriginalBMP; property hbmp: HBitmap read Fhbmp write Fhbmp; property tmRed: Integer read FtmRed write SettmRed; property tmGreen: Integer read FtmGreen write SettmGreen; property tmBlue: Integer read FtmBlue write SettmBlue; end; function GetBalanceColorForm(var red, blue, green: Integer; gfl_bmp: PGFL_BITMAP): Integer; implementation {$R *.dfm} function GetBalanceColorForm; var form: TfrmBalanceColor; begin form := TfrmBalanceColor.Create(Application); try form.OriginalBMP := gfl_bmp; form.CreatingBMP; Result := form.ShowModal; if Result = mrOk then begin red := form.tmRed; green := form.tmGreen; blue := form.tmBlue; end; finally form.Free; end; end; procedure TfrmBalanceColor.Button1Click(Sender: TObject); begin Close; end; procedure TfrmBalanceColor.tbRedChange(Sender: TObject); begin ColorRed := tbRed.Position; end; procedure TfrmBalanceColor.ActionOKExecute(Sender: TObject); begin OK.SetFocus; ModalResult := mrOK; end; procedure TfrmBalanceColor.SetColor1(const Value: Integer); begin FColor1 := Value; ApplyUpdates; end; procedure TfrmBalanceColor.SetColor2(const Value: Integer); begin FColor2 := Value; ApplyUpdates; end; procedure TfrmBalanceColor.SetColor3(const Value: Integer); begin FColor3 := Value; ApplyUpdates; end; procedure TfrmBalanceColor.cxSpinEdit1PropertiesChange(Sender: TObject); begin ColorRed := TcxSpinEdit(Sender).Value; end; procedure TfrmBalanceColor.cxSpinEdit2PropertiesChange(Sender: TObject); begin ColorGreen := TcxSpinEdit(Sender).Value; end; procedure TfrmBalanceColor.cxSpinEdit3PropertiesChange(Sender: TObject); begin ColorBlue := TcxSpinEdit(Sender).Value; end; procedure TfrmBalanceColor.ApplyUpdates; var color: TGFL_COLOR; y, ImagePixelFormat: Integer; LineSrc: Pointer; LineDest: Pointer; pvbBitmap: PGFL_BITMAP; Bitmap: TBitmap; b, s,min, i,IMin,{tmRed, tmGreen, tmBlue,} Red, Green, Blue: Integer; Cells: array [1..3] of Integer; begin cxSpinEdit1.Value := ColorRed; tbRed.Position := ColorRed; cxSpinEdit2.Value := ColorGreen; tbGreen.Position := ColorGreen; cxSpinEdit3.Value := ColorBlue; tbBlue.Position := ColorBlue; Red := ColorRed; Green := ColorGreen; Blue := ColorBlue; Cells[1] := Red; Cells[2] := Green; Cells[3] := Blue; for s := 1 to 3-1 do begin min := Cells[s]; IMin := s; for i := s+1 to 3 do if Cells[i] < Min then begin Min := Cells[i]; IMin := i; end; Cells[IMin] := Cells[s]; Cells[S] := Min; end; {Самое минимальное число совпадает со значением красного} if Cells[1] = Red then begin tmRed := 0; for i := 2 to 3 do begin if Cells[i] = Green then begin if Cells[i] >= 0 then tmGreen := Green - Red else tmGreen := Green + Abs(Red); end; if Cells[i] = Blue then begin if Cells[i] >= 0 then tmBlue := Blue - Red else tmBlue := Blue + Abs(Red); end; end; end; if Cells[1] = Green then begin tmGreen := 0; for i := 2 to 3 do begin if Cells[i] = Red then begin if Cells[i] >= 0 then tmRed := Red - Green else tmRed := Red + Abs(Green); end; if Cells[i] = Blue then begin if Cells[i] >= 0 then tmBlue := Blue - Green else tmBlue := Blue + Abs(Green); end; end; end; if Cells[1] = Blue then begin tmBlue := 0; for i := 2 to 3 do begin if Cells[i] = Red then begin if Cells[i] >= 0 then tmRed := Red - Blue else tmRed := Red + Abs(Blue); end; if Cells[i] = Green then begin if Cells[i] >= 0 then tmGreen := Green - Blue else tmGreen := Green + Abs(Blue); end; end; end; color.Red := tmRed; color.Green := tmGreen; color.Blue := tmBlue; pvbBitmap := gflCloneBitmap(FClonBitmap); gflBalance(pvbBitmap, nil, color); DeleteObject(hbmp); hbmp := CreateBitmap(pvbBitmap.Width, pvbBitmap.Height, pvbBitmap.ColorUsed, pvbBitmap.BitsPerComponent, nil); gflConvertBitmapIntoDDB(pvbBitmap, Fhbmp); Image.Picture.Bitmap.Handle := hbmp; gflFreeBitmap(pvbBitmap); end; // procedure TfrmBalanceColor.ApplyUpdates procedure TfrmBalanceColor.tbGreenChange(Sender: TObject); begin ColorGreen := TRzTrackBar(Sender).Position; end; procedure TfrmBalanceColor.tbBlueChange(Sender: TObject); begin ColorBlue := TRzTrackBar(Sender).Position; end; function TfrmBalanceColor.CalSize(var X, Y: Integer; ASize: Integer): Boolean; var k: Extended; begin k := OriginalBMP.Width / OriginalBMP.Height; if k >= 1 then begin X := ASize; Y := Trunc(ASize / k); end else begin X := Trunc(ASize * k); Y := ASize; end; Result := ((OriginalBMP.Width > X) and (OriginalBMP.Height > Y)); end; procedure TfrmBalanceColor.CreatingBMP; var W, H: Integer; hbmp: HBITMAP; pvbBitmap: PGFL_BITMAP; begin FClonBitmap := gflCloneBitmap(OriginalBMP); pvbBitmap := gflCloneBitmap(FClonBitmap); CalSize(W, H, Image.Width); Panel1.DoubleBuffered := True; gflResize(pvbBitmap, nil, W, H, GFL_RESIZE_BILINEAR, 0); hbmp := CreateBitmap(pvbBitmap.Width, pvbBitmap.Height, pvbBitmap.ColorUsed, pvbBitmap.BitsPerComponent, nil); gflConvertBitmapIntoDDB(pvbBitmap, hbmp); ImageOrig.Picture.Bitmap.Handle := hbmp; gflFreeBitmap(pvbBitmap); gflResize(FClonBitmap, nil, W, H, GFL_RESIZE_BILINEAR, 0); ApplyUpdates; end; procedure TfrmBalanceColor.FormDestroy(Sender: TObject); begin DeleteObject(hbmp); gflFreeBitmap(FClonBitmap); end; procedure TfrmBalanceColor.SetOriginalBMP(const Value: PGFL_BITMAP); begin FOriginalBMP := Value; end; procedure TfrmBalanceColor.SettmBlue(const Value: Integer); begin FtmBlue := Value; end; procedure TfrmBalanceColor.SettmGreen(const Value: Integer); begin FtmGreen := Value; end; procedure TfrmBalanceColor.SettmRed(const Value: Integer); begin FtmRed := Value; end; procedure TfrmBalanceColor.SetColorBlue(const Value: Integer); begin FColorBlue := Value; ApplyUpdates; end; procedure TfrmBalanceColor.SetColorGreen(const Value: Integer); begin FColorGreen := Value; ApplyUpdates; end; procedure TfrmBalanceColor.SetColorRed(const Value: Integer); begin FColorRed := Value; ApplyUpdates; end; end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uPhotoSort, Vcl.ComCtrls, Vcl.Menus, System.UITypes, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, Vcl.ExtCtrls, Vcl.PlatformDefaultStyleActnCtrls, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList; const INI_FILENAME = 'settings.ini'; APPDATA_DIR = 'StoiPhotoSort'; TAG_SETTINGS = 'settings'; type TfrmMainForm = class(TForm) lblPrefix: TLabel; actmgrActions: TActionManager; actAddDestination: TAction; actDeleteDestination: TAction; actClearDestination: TAction; actEditDestination: TAction; statStatus: TStatusBar; ilImages: TImageList; pnlBottom: TPanel; pnlDestionation: TPanel; acttbDestionation: TActionToolBar; lvDestinations: TListView; btnCopyFiles: TButton; edtPrefix: TEdit; pbCopyProgress: TProgressBar; btn1: TButton; btn2: TButton; pnlBody: TPanel; lvPhotos: TListView; pnlTop: TPanel; btnSelectSrcFolder: TButton; edtSrcPath: TEdit; imgSource: TImage; procedure btnSelectSrcFolderClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCopyFilesClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actAddDestinationExecute(Sender: TObject); procedure actClearDestinationExecute(Sender: TObject); procedure actDeleteDestinationExecute(Sender: TObject); procedure lvDestinationsClick(Sender: TObject); procedure lvDestinationsDblClick(Sender: TObject); procedure btn1Click(Sender: TObject); procedure btn2Click(Sender: TObject); procedure edtSrcPathChange(Sender: TObject); private FDefFolder: string; FPhotoSort: TPhotoSort; FDestination: string; private procedure SelectSrcFile(APhoto: TPhoto); procedure DoCopyFile(Sender: TObject); procedure LoadPhotos; // procedure DoAddFile(Sender: TObject); procedure CopyFiles(const ADestinfation: string); procedure UpdateData; procedure SaveSettings; procedure ReadSettings; function SelectFolder(const ACaption, ADefDestination: string): string; private procedure OnMsgAddFile(var Msg: TMessage); message WM_ADDFILE; procedure OnMsgClear(var Msg: TMessage); message WM_CLEAR; procedure OnMsgLoaded(var Msg: TMessage); message WM_LOADED; public { Public declarations } end; var frmMainForm: TfrmMainForm; implementation uses Winapi.ShlObj, System.IniFiles; function BrowseCallbackProc(HWND: HWND; uMsg: UINT; lParam: lParam; lpData: lParam): Integer; stdcall; begin if (uMsg = BFFM_INITIALIZED) then begin if frmMainForm.FDefFolder = '' then SendMessage(HWND, BFFM_SETSELECTION, 1, lpData) else SendMessage(HWND, BFFM_SETSELECTION, Integer(True), Integer(PChar(frmMainForm.FDefFolder))); end; Result := 0; end; function GetFolderDialog(Handle: Integer; Caption: string; var strFolder: string): Boolean; const BIF_STATUSTEXT = $0004; BIF_NEWDIALOGSTYLE = $0040; BIF_RETURNONLYFSDIRS = $0080; BIF_SHAREABLE = $0100; BIF_USENEWUI = BIF_EDITBOX or BIF_NEWDIALOGSTYLE; var BrowseInfo: TBrowseInfo; ItemIDList: PItemIDList; JtemIDList: PItemIDList; Path: PChar; begin Result := False; Path := StrAlloc(MAX_PATH); SHGetSpecialFolderLocation(Handle, CSIDL_DRIVES, JtemIDList); with BrowseInfo do begin hwndOwner := GetActiveWindow; pidlRoot := JtemIDList; SHGetSpecialFolderLocation(hwndOwner, CSIDL_DRIVES, JtemIDList); ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE or BIF_NONEWFOLDERBUTTON; pszDisplayName := StrAlloc(MAX_PATH); { Возврат названия выбранного элемента } lpszTitle := PChar(Caption); { Установка названия диалога выбора папки } lpfn := @BrowseCallbackProc; { Флаги, контролирующие возврат } lParam := LongInt(PChar(strFolder)); { Дополнительная информация, которая отдаётся обратно в обратный вызов (callback) } end; ItemIDList := SHBrowseForFolder(BrowseInfo); if (ItemIDList <> nil) then if SHGetPathFromIDList(ItemIDList, Path) then begin strFolder := Path; GlobalFreePtr(ItemIDList); Result := True; end; GlobalFreePtr(JtemIDList); StrDispose(Path); StrDispose(BrowseInfo.pszDisplayName); end; function GetSpecialPath(CSIDL: Word): string; var S: string; begin SetLength(S, MAX_PATH); if not SHGetSpecialFolderPath(0, PChar(S), CSIDL, True) then S := GetSpecialPath(CSIDL_APPDATA); Result := IncludeTrailingPathDelimiter(PChar(S)); end; function GetIniFilePath: string; begin Result := IncludeTrailingPathDelimiter(GetSpecialPath(CSIDL_COMMON_APPDATA) + APPDATA_DIR); ForceDirectories(Result); Result := Result + INI_FILENAME; end; {$R *.dfm} procedure TfrmMainForm.actAddDestinationExecute(Sender: TObject); var LItem: TListItem; LFolder: string; begin LFolder := SelectFolder('Select destionation', ''); if LFolder.IsEmpty then Exit; LItem := lvDestinations.Items.Add; LItem.Checked := True; LItem.Caption := LFolder; LItem.ImageIndex := 1; end; procedure TfrmMainForm.actClearDestinationExecute(Sender: TObject); begin lvDestinations.Clear; end; procedure TfrmMainForm.actDeleteDestinationExecute(Sender: TObject); var LItem: TListItem; begin LItem := lvDestinations.Selected; if not Assigned(LItem) then Exit; lvDestinations.DeleteSelected; end; procedure TfrmMainForm.btn1Click(Sender: TObject); begin LoadPhotos; end; procedure TfrmMainForm.btn2Click(Sender: TObject); begin FPhotoSort.TerminateThreads; end; procedure TfrmMainForm.btnCopyFilesClick(Sender: TObject); var I: Integer; begin UpdateData; // FPhotoSort.LoadPhotos(edtSrcPath.Text); FPhotoSort.AddPrefix := Trim(edtPrefix.Text); for I := 0 to lvDestinations.Items.Count - 1 do begin lvDestinations.ItemIndex := I; if lvDestinations.Items[I].Checked then CopyFiles(lvDestinations.Items[I].Caption); end; end; procedure TfrmMainForm.btnSelectSrcFolderClick(Sender: TObject); var LFolder: string; begin LFolder := SelectFolder('Select source directory', edtSrcPath.Text); if LFolder.IsEmpty then Exit; edtSrcPath.Text := LFolder; end; procedure TfrmMainForm.CopyFiles(const ADestinfation: string); begin FDestination := ADestinfation; // statStatus.Panels[0].Text := 'Copyng to: ' + ADestinfation; pbCopyProgress.Max := FPhotoSort.Count - 1; pbCopyProgress.Position := 0; if not FPhotoSort.SavePhotos(ADestinfation) then MessageDlg('Error copyng files to "' + ADestinfation + '"', mtError, [mbOK], 0); pbCopyProgress.Position := 0; statStatus.Panels[0].Text := ''; end; procedure TfrmMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; procedure TfrmMainForm.FormCreate(Sender: TObject); begin FPhotoSort := TPhotoSort.Create(Self.Handle); FPhotoSort.OnCopyFile := DoCopyFile; ReadSettings; end; procedure TfrmMainForm.FormDestroy(Sender: TObject); begin FPhotoSort.Free; end; procedure TfrmMainForm.LoadPhotos; begin // lvPhotos.Clear; FPhotoSort.ExecLoadPhotos(edtSrcPath.Text); end; procedure TfrmMainForm.lvDestinationsClick(Sender: TObject); var LItem: TListItem; begin LItem := lvDestinations.Selected; if not Assigned(LItem) then Exit; end; procedure TfrmMainForm.lvDestinationsDblClick(Sender: TObject); var LItem: TListItem; LFolder: string; begin LItem := lvDestinations.Selected; if not Assigned(LItem) then Exit; LFolder := SelectFolder('Select destination', LItem.Caption); if not LFolder.IsEmpty then LItem.Caption := LFolder; end; procedure TfrmMainForm.OnMsgAddFile(var Msg: TMessage); var LPhoto: TPhoto; LItem: TListItem; begin LPhoto := TPhoto(Msg.WParam); LItem := lvPhotos.Items.Add; LItem.Caption := LPhoto.FName; LItem.Data := LPhoto; LItem.ImageIndex := 0; LItem.Checked := True; end; procedure TfrmMainForm.OnMsgClear(var Msg: TMessage); begin lvPhotos.Clear; btnCopyFiles.Enabled := False; end; procedure TfrmMainForm.OnMsgLoaded(var Msg: TMessage); begin btnCopyFiles.Enabled := Boolean(Msg.WParam); end; procedure TfrmMainForm.DoCopyFile(Sender: TObject); begin pbCopyProgress.Position := pbCopyProgress.Position + 1; statStatus.Panels[0].Text := 'Copyng to "' + FDestination + '": ' + IntToStr(pbCopyProgress.Position) + ' - ' + TPhoto(Sender).FName; SelectSrcFile(TPhoto(Sender)); pbCopyProgress.Invalidate; Application.ProcessMessages; end; procedure TfrmMainForm.edtSrcPathChange(Sender: TObject); begin LoadPhotos; end; procedure TfrmMainForm.SaveSettings; var Ini: TIniFile; I: Integer; begin Ini := TIniFile.Create(GetIniFilePath); try Ini.WriteString(TAG_SETTINGS, 'source', edtSrcPath.Text); Ini.WriteString(TAG_SETTINGS, 'prefix', edtPrefix.Text); Ini.EraseSection('destinations'); for I := 0 to lvDestinations.Items.Count - 1 do begin Ini.WriteString('destinations', lvDestinations.Items[I].Caption, BoolToStr(lvDestinations.Items[I].Checked, True)); end; finally FreeAndNil(Ini); end; end; function TfrmMainForm.SelectFolder(const ACaption, ADefDestination : string): string; var LFolder: string; begin FDefFolder := ADefDestination; if not GetFolderDialog(Handle, ACaption, LFolder) then Exit(''); Result := LFolder; end; procedure TfrmMainForm.SelectSrcFile(APhoto: TPhoto); var I: Integer; begin for I := 0 to lvPhotos.Items.Count - 1 do begin if APhoto = TPhoto(lvPhotos.Items[I].Data) then begin lvPhotos.ItemIndex := I; Exit; end; end; end; procedure TfrmMainForm.UpdateData; var I: Integer; begin for I := 0 to lvPhotos.Items.Count - 1 do TPhoto(lvPhotos.Items[I].Data).FChecked := lvPhotos.Items[I].Checked; end; procedure TfrmMainForm.ReadSettings; var Ini: TIniFile; LFolders: TStrings; I: Integer; LItem: TListItem; begin Ini := TIniFile.Create(GetIniFilePath); try edtSrcPath.Text := Ini.ReadString(TAG_SETTINGS, 'source', ''); edtPrefix.Text := Ini.ReadString(TAG_SETTINGS, 'prefix', ''); lvDestinations.Clear; LFolders := TStringList.Create; try Ini.ReadSectionValues('destinations', LFolders); for I := 0 to LFolders.Count - 1 do begin LItem := lvDestinations.Items.Add; LItem.Caption := LFolders.KeyNames[I]; LItem.Checked := StrToBoolDef(LFolders.ValueFromIndex[I], False); LItem.ImageIndex := 1; end; finally FreeAndNil(LFolders); end; finally FreeAndNil(Ini); end; end; end.
unit untCalcularImpostoExercicio2; interface uses untFuncionario, untDependente, Generics.Collections; type TCalcularImpostoExercicio2 = class private function fcTestarExisteDependenteCalculaIR(const pListaDependentes: TObjectList<TDependente>): Boolean; function fcRetornarNumeroDependentesCalculaIR(const pListaDependentes: TObjectList<TDependente>): Integer; function fcTestarExisteDependenteCalculaINSS(const pListaDependentes: TObjectList<TDependente>): Boolean; public function fcRetornarValorIR(const pFuncionario: TFuncionario): Double; function fcRetornarValorINSS(const pFuncionario: TFuncionario): Double; end; implementation { TCalcularImpostoExercicio2 } function TCalcularImpostoExercicio2.fcRetornarNumeroDependentesCalculaIR(const pListaDependentes: TObjectList<TDependente>): Integer; var vContador: Integer; begin Result := 0; if not Assigned(pListaDependentes) then Exit; if pListaDependentes.Count = 0 then Exit; for vContador := 0 to pListaDependentes.Count - 1 do begin if pListaDependentes[vContador].IsCalcularIR > 0 then Inc(Result); end; end; function TCalcularImpostoExercicio2.fcRetornarValorIR(const pFuncionario: TFuncionario): Double; const cFATORIR = 0.15; cVALORDEDUCAOPORDEPENDENTE = 100; var vListaDependentes: TObjectList<TDependente>; vValorDeducao: Double; begin Result := 0; if not Assigned(pFuncionario) then Exit; if pFuncionario.Salario <= 0 then Exit; vValorDeducao := 0; vListaDependentes := pFuncionario.ListaDependentes; if fcTestarExisteDependenteCalculaIR(vListaDependentes) then vValorDeducao := fcRetornarNumeroDependentesCalculaIR(vListaDependentes) * cVALORDEDUCAOPORDEPENDENTE; Result := (pFuncionario.Salario - vValorDeducao) * cFATORIR; end; function TCalcularImpostoExercicio2.fcTestarExisteDependenteCalculaIR(const pListaDependentes: TObjectList<TDependente>): Boolean; var vContador: Integer; begin Result := False; if not Assigned(pListaDependentes) then Exit; if pListaDependentes.Count = 0 then Exit; for vContador := 0 to pListaDependentes.Count - 1 do begin if pListaDependentes[vContador].IsCalcularIR > 0 then begin Result := True; Break; end; end; end; function TCalcularImpostoExercicio2.fcRetornarValorINSS(const pFuncionario: TFuncionario): Double; const cFATORINSS = 0.08; var vListaDependentes: TObjectList<TDependente>; begin Result := 0; if not Assigned(pFuncionario) then Exit; if pFuncionario.Salario <= 0 then Exit; vListaDependentes := pFuncionario.ListaDependentes; if fcTestarExisteDependenteCalculaINSS(vListaDependentes) then Result := pFuncionario.Salario * cFatorINSS; end; function TCalcularImpostoExercicio2.fcTestarExisteDependenteCalculaINSS(const pListaDependentes: TObjectList<TDependente>): Boolean; var vContador: Integer; begin Result := False; if not Assigned(pListaDependentes) then Exit; if pListaDependentes.Count = 0 then Exit; for vContador := 0 to pListaDependentes.Count - 1 do begin if pListaDependentes[vContador].IsCalcularINSS > 0 then begin Result := True; Break; end; end; end; end.
unit TestUFuncionarioPersist; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, UIPersist, System.Generics.Collections, UFuncionario, UFuncionarioPersist, UDependente; type // Test methods for class TFuncionarioPersist TestTFuncionarioPersist = class(TTestCase) strict private FFuncionarioPersist: TFuncionarioPersist; public procedure SetUp; override; procedure TearDown; override; published private // colocado para não aparecer nos testes procedure TestGet; procedure TestGetById; procedure TestSave; procedure TestDelete; end; implementation procedure TestTFuncionarioPersist.SetUp; begin FFuncionarioPersist := TFuncionarioPersist.Create; end; procedure TestTFuncionarioPersist.TearDown; begin FFuncionarioPersist.Free; FFuncionarioPersist := nil; end; procedure TestTFuncionarioPersist.TestGet; var ReturnValue: TList<TFuncionario>; func: TFuncionario; begin ReturnValue := FFuncionarioPersist.Get; assert(ReturnValue.Count <> 0, 'ta errado'); assert(ReturnValue[0].Nome = 'Maria'); if assigned(ReturnValue) then begin for func in returnvalue do begin func.free; end; ReturnValue.Free; end; end; procedure TestTFuncionarioPersist.TestGetById; var ReturnValue: TFuncionario; Id: Integer; begin try Id := 2; ReturnValue := FFuncionarioPersist.GetById(Id); assert(ReturnValue.Nome = 'Maria'); finally if assigned(ReturnValue) then ReturnValue.Free; end; end; procedure TestTFuncionarioPersist.TestSave; var ReturnValue: Boolean; Entidade: TFuncionario; begin try Entidade := TFuncionario.Create(0, 'Maria', '321', 10100); entidade.AddDependente(TDependente.Create(0,0,'fulano',true,true)); entidade.AddDependente(TDependente.Create(0,0,'Beltrano',true,false)); entidade.AddDependente(TDependente.Create(0,0,'ciclano',true,True)); entidade.AddDependente(TDependente.Create(0,0,'João',true,False)); entidade.AddDependente(TDependente.Create(0,0,'Jose',false,False)); ReturnValue := FFuncionarioPersist.Save(Entidade); finally if assigned(Entidade) then Entidade.Free end; end; procedure TestTFuncionarioPersist.TestDelete; var ReturnValue: Boolean; Entidade: TFuncionario; begin // TODO: Setup method call parameters entidade := TFuncionario.Create(1,'','',0); try ReturnValue := FFuncionarioPersist.Delete(Entidade); finally entidade.Free; end; // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTFuncionarioPersist.Suite); end.
{: GLMovement<p> Movement path behaviour by Roger Cao<p> <b>Historique : </b><font size=-1><ul> <li>14/01/01 - Egg - Minor changes, integrated to v0.8RC2, still needed: use of standard classes and documentation <li>22/09/00 - RoC - Added StartAllPathTravel and StopAllPathTravel methods <li>24/08/00 - RoC - TGLMovement and relative class added </ul></font> } unit GLMovement; interface uses Classes, GLScene, Geometry, GLMisc, XCollection, OpenGL12, Spline, GLObjects; type // TGLPathNode // TGLPathNode = class (TCollectionItem) private FPosition: TVector; FScale: TVector; FRotation: TVector; FSpeed: single; procedure SetPositionAsVector(const Value: TVector); procedure SetRotationAsVector(const Value: TVector); procedure SetScaleAsVector(const Value: TVector); procedure SetPositionCoordinate(Index: integer; AValue: TGLFloat); procedure SetRotationCoordinate(Index: integer; AValue: TGLFloat); procedure SetScaleCoordinate(Index: integer; AValue: TGLFloat); procedure SetSpeed(Value: single); protected function GetDisplayName: string; override; procedure WriteToFiler(writer : TWriter); procedure ReadFromFiler(reader : TReader); public constructor Create(Collection: TCollection); override; destructor Destroy; override; function PositionAsAddress: PGLFloat; function RotationAsAddress: PGLFloat; function ScaleAsAddress: PGLFloat; procedure Assign(Source: TPersistent); override; procedure InitializeByObject(Obj: TGLBaseSceneObject); function EqualNode(aNode: TGLPathNode): boolean; property PositionAsVector: TVector Read FPosition Write SetPositionAsVector; property RotationAsVector: TVector Read FRotation Write SetRotationAsVector; property ScaleAsVector: TVector Read FScale Write SetScaleAsVector; published property X: TGLFloat index 0 Read FPosition[0] Write SetPositionCoordinate; property Y: TGLFloat index 1 Read FPosition[1] Write SetPositionCoordinate; property Z: TGLFloat index 2 Read FPosition[2] Write SetPositionCoordinate; //Rotation.X means PitchAngle; //Rotation.Y means TurnAngle; //Rotation.Z means RollAngle; property PitchAngle: TGLFloat index 0 Read FRotation[0] Write SetRotationCoordinate; property TurnAngle: TGLFloat index 1 Read FRotation[1] Write SetRotationCoordinate; property RollAngle: TGLFloat index 2 Read FRotation[2] Write SetRotationCoordinate; property ScaleX: TGLFloat index 0 Read FScale[0] Write SetScaleCoordinate; property ScaleY: TGLFloat index 1 Read FScale[1] Write SetScaleCoordinate; property ScaleZ: TGLFloat index 2 Read FScale[2] Write SetScaleCoordinate; property Speed: single Read FSpeed Write SetSpeed; end; TGLMovementPath = class; // TGLPathNodes // TGLPathNodes = class (TCollection) private Owner: TGLMovementPath; protected function GetOwner: TPersistent; override; procedure SetItems(index: integer; const val: TGLPathNode); function GetItems(index: integer): TGLPathNode; public constructor Create(aOwner: TGLMovementPath); function Add: TGLPathNode; function FindItemID(ID: integer): TGLPathNode; property Items[index: integer]: TGLPathNode Read GetItems Write SetItems; default; procedure Delete(index: integer); procedure NotifyChange; virtual; end; TGLMovementPath = class(TCollectionItem) private FPathLine: TLines; FShowPath: Boolean; FPathSplineMode: TLineSplineMode; FNodes: TGLPathNodes; //All the time saved in ms FStartTime: double; FEstimateTime: double; FCurrentNode: TGLPathNode; FInTravel: boolean; FLooped: boolean; FName: string; MotionSplineControl: TCubicSpline; RotationSplineControl: TCubicSpline; ScaleSplineControl: TCubicSpline; FOnTravelStart: TNotifyEvent; FOnTravelStop: TNotifyEvent; FCurrentNodeIndex: integer; //function GetPathNode(Index: integer): TGLPathNode; //procedure SetPathNode(Index: integer; AValue: TGLPathNode); function GetNodeCount: integer; procedure SetStartTime(Value: double); procedure SetCurrentNodeIndex(Value: integer); procedure SetShowPath(Value: Boolean); procedure SetPathSplineMode(Value: TLineSplineMode); protected procedure WriteToFiler(writer : TWriter); procedure ReadFromFiler(reader : TReader); function CanTravel: boolean; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function AddNode: TGLPathNode; overload; function AddNode(Node: TGLPathNode): TGLPathNode; overload; function AddNodeFromObject(Obj: TGLBaseSceneObject): TGLPathNode; function InsertNodeFromObject(Obj: TGLBaseSceneObject; Index: integer): TGLPathNode; function InsertNode(Node: TGLPathNode; Index: integer): TGLPathNode; overload; function InsertNode(Index: integer): TGLPathNode; overload; function DeleteNode(Index: integer): TGLPathNode; overload; function DeleteNode(Node: TGLPathNode): TGLPathNode; overload; procedure ClearNodes; procedure UpdatePathLine; function NodeDistance(Node1, Node2: TGLPathNode): double; procedure CalculateState(CurrentTime: double); procedure TravelPath(Start: boolean); overload; procedure TravelPath(Start: boolean; aStartTime: double); overload; //property Nodes[index: Integer]: TGLPathNode read GetPathNode write SetPathNode; property NodeCount: integer Read GetNodeCount; property CurrentNode: TGLPathNode Read FCurrentNode; property InTravel: boolean Read FInTravel; function PrevNode: integer; function NextNode: integer; property CurrentNodeIndex: integer Read FCurrentNodeIndex Write SetCurrentNodeIndex; property OnTravelStart: TNotifyEvent Read FOnTravelStart Write FOnTravelStart; property OnTravelStop: TNotifyEvent Read FOnTravelStop Write FOnTravelStop; published property Name: string Read FName Write FName; property PathSplineMode: TLineSplineMode read FPathSplineMode write SetPathSplineMode; property StartTime: double Read FStartTime Write SetStartTime; property EstimateTime: double Read FEstimateTime; property Looped: boolean Read FLooped Write FLooped; property Nodes: TGLPathNodes Read FNodes; property ShowPath: Boolean read FShowPath write SetShowPath; end; TGLMovement = class; TGLMovementPaths = class(TCollection) protected Owner: TGLMovement; function GetOwner: TPersistent; override; procedure SetItems(index: integer; const val: TGLMovementPath); function GetItems(index: integer): TGLMovementPath; public constructor Create(aOwner: TGLMovement); function Add: TGLMovementPath; function FindItemID(ID: integer): TGLMovementPath; property Items[index: integer]: TGLMovementPath Read GetItems Write SetItems; default; procedure Delete(index: integer); procedure NotifyChange; virtual; end; //Event for path related event TPathTravelStartEvent = procedure (Sender: TObject; Path: TGLMovementPath) of object; TPathTravelStopEvent = procedure (Sender: TObject; Path: TGLMovementPath; var Looped: boolean) of object; TGLMovement = class(TGLBehaviour) private FPaths: TGLMovementPaths; FAutoStartNextPath: boolean; FActivePathIndex: integer; FOnAllPathTravelledOver: TNotifyEvent; FOnPathTravelStart: TPathTravelStartEvent; FOnPathTravelStop: TPathTravelStopEvent; { function GetMovementPath(Index: integer): TGLMovementPath; procedure SetMovementPath(Index: integer; AValue: TGLMovementPath); } function GetPathCount: integer; procedure SetActivePathIndex(Value: integer); function GetActivePath: TGLMovementPath; procedure SetActivePath(Value: TGLMovementPath); protected procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; procedure PathTravelStart(Sender: TObject); procedure PathTravelStop(Sender: TObject); public constructor Create(aOwner: TXCollection); override; destructor Destroy; override; //add an empty path; function AddPath: TGLMovementPath; overload; //add an path with one node, and the node is based on aObject function AddPath(aObject: TGLBaseSceneObject): TGLMovementPath; overload; //add one path to the new one function AddPath(Path: TGLMovementPath): TGLMovementPath; overload; procedure ClearPaths; //Result is current path function DeletePath(Path: TGLMovementPath): TGLMovementPath; overload; function DeletePath(Index: integer): TGLMovementPath; overload; function DeletePath: TGLMovementPath; overload; procedure Assign(Source: TPersistent); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: boolean; override; procedure StartPathTravel; procedure StopPathTravel; procedure DoProgress(const deltaTime, newTime: double); override; function NextPath: integer; function PrevPath: integer; function FirstPath: integer; function LastPath: integer; //property Paths[index: Integer]: TGLMovementPath read GetMovementPath write SetMovementPath; property PathCount: integer Read GetPathCount; //why do these property can't be saved in IDE ? property OnAllPathTravelledOver: TNotifyEvent Read FOnAllPathTravelledOver Write FOnAllPathTravelledOver; property OnPathTravelStart: TPathTravelStartEvent Read FOnPathTravelStart Write FOnPathTravelStart; property OnPathTravelStop: TPathTravelStopEvent Read FOnPathTravelStop Write FOnPathTravelStop; published property Paths: TGLMovementPaths Read FPaths; property AutoStartNextPath: boolean Read FAutoStartNextPath Write FAutoStartNextPath; property ActivePathIndex: integer Read FActivePathIndex Write SetActivePathIndex; property ActivePath: TGLMovementPath Read GetActivePath Write SetActivePath; end; function GetMovement(behaviours: TGLBehaviours): TGLMovement; overload; function GetMovement(obj: TGLBaseSceneObject): TGLMovement; overload; function GetOrCreateMovement(behaviours: TGLBehaviours): TGLMovement; overload; function GetOrCreateMovement(obj: TGLBaseSceneObject): TGLMovement; overload; procedure StartAllMovements(Scene: TGLScene; StartCamerasMove, StartObjectsMove: Boolean); procedure StopAllMovements(Scene: TGLScene; StopCamerasMove, StopObjectsMove: Boolean); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils, Dialogs; //----------------------------------- Added by Roger --------------------------- //----------------------------- TGLPathNode ------------------------------------ constructor TGLPathNode.Create(Collection: TCollection); begin inherited Create(Collection); FPosition := VectorMake(0, 0, 0, 1); FRotation := VectorMake(0, 0, 0, 1); FScale := VectorMake(1, 1, 1, 1); FSpeed := 0; end; destructor TGLPathNode.Destroy; begin inherited Destroy; end; procedure TGLPathNode.SetPositionAsVector(const Value: TVector); begin FPosition := Value; (Collection as TGLPathNodes).NotifyChange; end; procedure TGLPathNode.SetRotationAsVector(const Value: TVector); begin FRotation := Value; (Collection as TGLPathNodes).NotifyChange; end; procedure TGLPathNode.SetScaleAsVector(const Value: TVector); begin FScale := Value; (Collection as TGLPathNodes).NotifyChange; end; function TGLPathNode.PositionAsAddress: PGLFloat; begin Result := @FPosition; end; function TGLPathNode.RotationAsAddress: PGLFloat; begin Result := @FRotation; end; function TGLPathNode.ScaleAsAddress: PGLFloat; begin Result := @FScale; end; procedure TGLPathNode.WriteToFiler(writer : TWriter); var WriteStuff: boolean; begin with Writer do begin WriteInteger(0); // Archive Version 0 WriteStuff := not (VectorEquals(FPosition, NullHmgPoint) and VectorEquals(FRotation, NullHmgPoint) and VectorEquals(FScale, VectorMake(1, 1, 1)) and (Speed=0)); WriteBoolean(writeStuff); if WriteStuff then begin Write(FPosition, sizeof(FPosition)); Write(FRotation, sizeof(FRotation)); Write(FScale, sizeof(FScale)); WriteFloat(FSpeed); end; end; end; procedure TGLPathNode.ReadFromFiler(reader : TReader); begin with Reader do begin ReadInteger; //Achive Version 0 if ReadBoolean then begin Read(FPosition, sizeof(FPosition)); Read(FRotation, sizeof(FRotation)); Read(FScale, sizeof(FScale)); FSpeed := ReadFloat; end else begin FPosition := NullHmgPoint; FRotation := NullHmgPoint; FScale := VectorMake(1, 1, 1, 1); FSpeed := 0; end; end; end; procedure TGLPathNode.InitializeByObject(Obj: TGLBaseSceneObject); begin if Assigned(Obj) then begin FPosition := Obj.Position.AsVector; FScale := Obj.Scale.AsVector; FRotation := Obj.Rotation.AsVector; //Speed := Obj.Speed; end; end; procedure TGLPathNode.Assign(Source: TPersistent); begin if Source is TGLPathNode then begin FPosition := TGLPathNode(Source).FPosition; FRotation := TGLPathNode(Source).FRotation; FScale := TGLPathNode(Source).FScale; FSpeed := TGLPathNode(Source).FSpeed; end else inherited Assign(Source); end; function TGLPathNode.EqualNode(aNode: TGLPathNode): boolean; begin //the speed diffrent will not be ... Result := (VectorEquals(FPosition, aNode.FPosition)) and (VectorEquals(FRotation, aNode.FRotation)) and (VectorEquals(FScale, aNode.FScale)); end; procedure TGLPathNode.SetPositionCoordinate(Index: integer; AValue: TGLFloat); begin FPosition[Index] := AValue; (Collection as TGLPathNodes).NotifyChange; end; procedure TGLPathNode.SetRotationCoordinate(Index: integer; AValue: TGLFloat); begin FRotation[Index] := AValue; (Collection as TGLPathNodes).NotifyChange; end; procedure TGLPathNode.SetScaleCoordinate(Index: integer; AValue: TGLFloat); begin FScale[Index] := AValue; (Collection as TGLPathNodes).NotifyChange; end; procedure TGLPathNode.SetSpeed(Value: single); begin FSpeed := Value; end; function TGLPathNode.GetDisplayName: string; begin Result := 'PathNode'; end; //--------------------------- TGLPathNodes ------------------------------------- constructor TGLPathNodes.Create(aOwner: TGLMovementPath); begin Owner := aOwner; inherited Create(TGLPathNode); end; function TGLPathNodes.GetOwner: TPersistent; begin Result := Owner; end; procedure TGLPathNodes.SetItems(index: integer; const val: TGLPathNode); begin inherited Items[index] := val; end; function TGLPathNodes.GetItems(index: integer): TGLPathNode; begin Result := TGLPathNode(inherited Items[index]); end; function TGLPathNodes.Add: TGLPathNode; begin Result := (inherited Add) as TGLPathNode; end; function TGLPathNodes.FindItemID(ID: integer): TGLPathNode; begin Result := (inherited FindItemID(ID)) as TGLPathNode; end; procedure TGLPathNodes.Delete(index: integer); var item: TCollectionItem; begin item := inherited Items[index]; item.Collection := nil; item.Free; end; procedure TGLPathNodes.NotifyChange; begin //Update the path-line if avlible in TGLMovementPath (Owner as TGLMovementPath).UpdatePathLine; end; //--------------------------- TGLMovementPath ---------------------------------- constructor TGLMovementPath.Create(Collection: TCollection); begin //This object can only be added to a TGLMovement class inherited Create(Collection); FNodes := TGLPathNodes.Create(Self); FStartTime := 0; FEstimateTime := 0; FCurrentNode := nil; FInTravel := False; FOnTravelStart := nil; FOnTravelStop := nil; FLooped := False; FCurrentNodeIndex := -1; FCurrentNode := nil; MotionSplineControl := nil; RotationSplineControl := nil; ScaleSplineControl := nil; FShowPath := False; FPathLine := nil; FPathSplineMode := lsmCubicSpline; end; destructor TGLMovementPath.Destroy; begin ClearNodes; FNodes.Free; inherited Destroy; end; procedure TGLMovementPath.WriteToFiler(writer : TWriter); var WriteStuff: boolean; I: Integer; begin with Writer do begin WriteInteger(0); // Archive Version 0 WriteStuff := (FNodes.Count>0) or (FLooped) or (FCurrentNodeIndex<>-1) or (FShowPath) or (FPathSplineMode<>lsmCubicSpline); WriteBoolean(writeStuff); if WriteStuff then begin WriteBoolean(FLooped); WriteInteger(FCurrentNodeIndex); WriteBoolean(FShowPath); Write(FPathSplineMode, sizeof(FPathSplineMode)); WriteInteger(FNodes.Count); for I:=0 to FNodes.Count-1 do FNodes.Items[I].WriteToFiler(Writer); end; end; end; procedure TGLMovementPath.ReadFromFiler(reader : TReader); var I: Integer; Count: Integer; Node: TGLPathNode; begin ClearNodes; with Reader do begin ReadInteger; // Archive Version 0 if ReadBoolean then begin FLooped := ReadBoolean; FCurrentNodeIndex := ReadInteger; ShowPath := ReadBoolean; Read(FPathSplineMode, sizeof(FPathSplineMode)); Count := ReadInteger; for I:=0 to Count-1 do begin Node := AddNode; Node.ReadFromFiler(Reader); end; end else begin FLooped := False; FCurrentNodeIndex := -1; FShowPath := False; FPathSplineMode := lsmCubicSpline; end; end; UpdatePathLine; end; procedure TGLMovementPath.SetPathSplineMode(Value: TLineSplineMode); begin if Value<>FPathSplineMode then begin FPathSplineMode := Value; if FShowPath then FPathLine.SplineMode := FPathSplineMode; end; end; procedure TGLMovementPath.UpdatePathLine; var I: Integer; Node: TGLPathNode; begin if FShowPath then begin FPathLine.Nodes.Clear; for I:=0 to Nodes.Count-1 do begin Node := Nodes.Items[I]; FPathLine.AddNode(Node.PositionAsVector); end; end; end; procedure TGLMovementPath.SetShowPath(Value: Boolean); var OwnerObj: TGLBaseSceneObject; LineObj: TLines; begin if FShowPath<>Value then begin FShowPath := Value; //what a mass relationship :-( OwnerObj := (Collection as TGLMovementPaths).Owner{TGLMovement}.Owner{TGLBehavours}.Owner as TGLBaseSceneObject; if FShowPath then begin //allways add the line object to the root LineObj := OwnerObj.Scene.Objects.AddNewChild(TLines) as TLines; //set the link FPathLine := LineObj; FPathLine.SplineMode := FPathSplineMode; UpdatePathLine; end else begin OwnerObj.Scene.Objects.Remove(FPathLine, False); FPathLine.free; FPathLine := nil; end; end; end; procedure TGLMovementPath.ClearNodes; begin TravelPath(False); FNodes.Clear; if Assigned(FCurrentNode) then begin FCurrentNode.Free; FCurrentNode := nil; end; FCurrentNodeIndex := -1; UpdatePathLine; end; procedure TGLMovementPath.SetCurrentNodeIndex(Value: integer); begin if FNodes.Count = 0 then begin FCurrentNodeIndex := -1; exit; end; if (FInTravel) or (Value > FNodes.Count - 1) or (Value < 0) then exit else begin FCurrentNodeIndex := Value; if not Assigned(FCurrentNode) then FCurrentNode := TGLPathNode.Create(nil); FCurrentNode.Assign(Nodes[FCurrentNodeIndex]); end; end; function TGLMovementPath.InsertNode(Node: TGLPathNode; Index: integer): TGLPathNode; var N: TGLPathNode; begin Result := nil; //Intravel, can't insert if FInTravel then exit; //Insert into the position if (Assigned(Node)) and (Assigned(Nodes[Index])) then begin N := TGLPathNode(FNodes.Insert(Index)); if Index >0 then N.Assign(Nodes[Index -1]); end else //add to the tail of list N := FNodes.Add; Result := N; UpdatePathLine; end; function TGLMovementPath.InsertNode(Index: integer): TGLPathNode; var N: TGLPathNode; begin Result := nil; //Intravel, can't insert if FInTravel then exit; //Insert into the position if (Assigned(Nodes[Index])) then begin N := TGLPathNode(FNodes.Insert(Index)); if Index >0 then N.Assign(Nodes[Index -1]); Result := N; end else //add to the tail of list Result := AddNode; UpdatePathLine; end; function TGLMovementPath.AddNodeFromObject(Obj: TGLBaseSceneObject): TGLPathNode; begin Result := nil; if (FInTravel) or (not Assigned(Obj)) then exit; Result := AddNode; Result.FPosition := Obj.Position.AsVector; Result.FScale := Obj.Scale.AsVector; Result.FRotation := Obj.Rotation.AsVector; //Result.FSpeed := Obj.Speed; UpdatePathLine; end; function TGLMovementPath.InsertNodeFromObject(Obj: TGLBaseSceneObject; Index: integer): TGLPathNode; var N: TGLPathNode; begin Result := nil; if (FInTravel) or (not Assigned(Obj)) then exit; N := InsertNode(Index); N.FPosition := Obj.Position.AsVector; N.FScale := Obj.Scale.AsVector; N.FRotation := Obj.Rotation.AsVector; //N.Speed := Obj.Speed; Result := N; UpdatePathLine; end; function TGLMovementPath.DeleteNode(Index: integer): TGLPathNode; var Node: TGLPathNode; begin Result := nil; //Ontravel, can't delete if FInTravel then exit; Node := Nodes[Index]; if Assigned(Node) then begin Node.Free; FNodes.Delete(Index); if FCurrentNodeIndex < 0 then exit; if (Index =0) then begin if FNodes.Count > 0 then FCurrentNodeIndex := 0 else FCurrentNodeIndex := -1; end else begin //one has been deleted, so the index should be equal to FNodeList.Count if Index =FNodes.Count then FCurrentNodeIndex := Index -1 else FCurrentNodeIndex := Index; end; Result := Nodes[FCurrentNodeIndex]; end; UpdatePathLine; end; function TGLMovementPath.DeleteNode(Node: TGLPathNode): TGLPathNode; var I: integer; begin Result := nil; for I := 0 to FNodes.Count - 1 do begin if Node = Nodes[I] then begin Result := DeleteNode(I); break; end; end; UpdatePathLine; end; function TGLMovementPath.PrevNode: integer; begin Result := FCurrentNodeIndex; if FNodes.Count = 0 then exit; Dec(FCurrentNodeIndex); if (FCurrentNodeIndex < 0) then FCurrentNodeIndex := 0 else //this line can cause the CurrentNode generated CurrentNodeIndex := FCurrentNodeIndex; Result := FCurrentNodeIndex; end; function TGLMovementPath.NextNode: integer; begin Result := FCurrentNodeIndex; if FNodes.Count = 0 then exit; Inc(FCurrentNodeIndex); if (FCurrentNodeIndex = FNodes.Count) then Dec(FCurrentNodeIndex) else //this line can cause the CurrentNode generated CurrentNodeIndex := FCurrentNodeIndex; Result := FCurrentNodeIndex; end; function TGLMovementPath.NodeDistance(Node1, Node2: TGLPathNode): double; var Vector: TVector; begin Vector := VectorSubtract(Node1.FPosition, Node2.FPosition); Result := VectorLength(Vector); end; //need to do //1 No acceleration implemented //2 The travel-time of a segment is based a simple linear movement, at the start and the end // of the segment, the speed will be more high than in the middle //3 Rotation Interpolation has not been tested procedure TGLMovementPath.CalculateState(CurrentTime: double); var I: integer; SumTime: double; L: single; Interpolated: boolean; T: double; procedure Interpolation(ReturnNode: TGLPathNode; Time1, Time2: double; Index: integer); var Ratio: double; x, y, z, p, t, r, sx, sy, sz: single; begin Ratio := Time2 / Time1 + Index; MotionSplineControl.SplineXYZ(Ratio, x, y, z); RotationSplineControl.SplineXYZ(Ratio, p, t, r); ScaleSplineControl.SplineXYZ(Ratio, sx, sy, sz); ReturnNode.FPosition := VectorMake(x, y, z, 1); ReturnNode.FRotation := VectorMake(p, t, r, 1); ReturnNode.FScale := VectorMake(sx, sy, sz, 1); end; begin I := 1; if (FStartTime=0) or (FStartTime>CurrentTime) then FStartTime := CurrentTime; SumTime := FStartTime; Interpolated := False; while I < FNodes.Count do begin L := NodeDistance(Nodes[I], Nodes[I - 1]); T := L / Nodes[I - 1].Speed; if (SumTime + T) >= CurrentTime then begin Interpolation(FCurrentNode, T, CurrentTime - SumTime, I - 1); Interpolated := True; break; end else begin Inc(I); SumTime := SumTime + T; end; end; if (not Interpolated) then begin Interpolation(FCurrentNode, 1.0, 0.0, FNodes.Count - 1); TravelPath(False); end; end; function TGLMovementPath.CanTravel: boolean; var I: integer; begin Result := True; if FNodes.Count < 2 then begin Result := False; exit; end; for I := 0 to FNodes.Count - 1 do if Abs(Nodes[I].Speed) < 0.01 then begin Result := False; break; end; end; procedure TGLMovementPath.TravelPath(Start: boolean); var x, y, z: PFloatArray; p, t, r: PFloatArray; sx, sy, sz: PFloatArray; I: integer; begin if (FInTravel = Start) or (FNodes.Count = 0) then exit; //One of the node speed < 0.01; if (Start) and (not CanTravel) then exit; FInTravel := Start; if FInTravel then begin GetMem(x, sizeof(single) * FNodes.Count); GetMem(y, sizeof(single) * FNodes.Count); GetMem(z, sizeof(single) * FNodes.Count); GetMem(p, sizeof(single) * FNodes.Count); GetMem(t, sizeof(single) * FNodes.Count); GetMem(r, sizeof(single) * FNodes.Count); GetMem(sx, sizeof(single) * FNodes.Count); GetMem(sy, sizeof(single) * FNodes.Count); GetMem(sz, sizeof(single) * FNodes.Count); for I := 0 to FNodes.Count - 1 do begin PFloatArray(x)[I] := Nodes[I].FPosition[0]; PFloatArray(y)[I] := Nodes[I].FPosition[1]; PFloatArray(z)[I] := Nodes[I].FPosition[2]; PFloatArray(p)[I] := Nodes[I].FRotation[0]; PFloatArray(t)[I] := Nodes[I].FRotation[1]; PFloatArray(r)[I] := Nodes[I].FRotation[2]; PFloatArray(sx)[I] := Nodes[I].FScale[0]; PFloatArray(sy)[I] := Nodes[I].FScale[1]; PFloatArray(sz)[I] := Nodes[I].FScale[2]; end; MotionSplineControl := TCubicSpline.Create(x, y, z, nil, FNodes.Count); RotationSplineControl := TCubicSpline.Create(p, t, r, nil, FNodes.Count); ScaleSplineControl := TCubicSpline.Create(sx, sy, sz, nil, FNodes.Count); FreeMem(x); FreeMem(y); FreeMem(z); FreeMem(p); FreeMem(t); FreeMem(r); FreeMem(sx); FreeMem(sy); FreeMem(sz); FCurrentNode := TGLPathNode.Create(nil); FCurrentNode.Assign(Nodes[0]); FCurrentNodeIndex := -1; FEstimateTime := 0; for I := 1 to FNodes.Count - 1 do FEstimateTime := FEstimateTime + NodeDistance(Nodes[I], Nodes[I - 1]) / Nodes[I - 1].Speed; if Assigned(FOnTravelStart) then FOnTravelStart(self); end else begin MotionSplineControl.Free; RotationSplineControl.Free; ScaleSplineControl.Free; if Assigned(FOnTravelStop) then FOnTravelStop(self); end; end; procedure TGLMovementPath.TravelPath(Start: boolean; aStartTime: double); begin if FInTravel = Start then exit; FStartTime := aStartTime; TravelPath(Start); end; { function TGLMovementPath.GetPathNode(Index: integer): TGLPathNode; begin if (Index >=0) and (Index <FNodes.Count) then Result := FNodes[Index] else Result := nil; end; procedure TGLMovementPath.SetPathNode(Index: integer; AValue: TGLPathNode); begin if (Index >=0) and (Index <FNodes.Count) and (Assigned(AValue)) then Nodes[Index].Assign(AValue); end; } function TGLMovementPath.GetNodeCount: integer; begin Result := FNodes.Count; end; //-------------------------- This function need modified ----------------------- procedure TGLMovementPath.SetStartTime(Value: double); begin FStartTime := Value; end; (* procedure TGLMovementPath.WriteToFiler(writer : TWriter); var WriteStuff : Boolean; I: Integer; begin with Writer do begin WriteInteger(0); // Archive Version 0 WriteStuff := (FStartTime<>0) or (FNodes.Count>0) {or (Assigned(FOnTravelStart)) or (Assigned(FOnTravelStop))} or (FLooped) or (FName<>''); WriteBoolean(WriteStuff); if WriteStuff then begin WriteString(FName); Writer.WriteFloat(FStartTime); WriteInteger(FNodeList.Count); for I:=0 to FNodeList.Count-1 do Nodes[I].WriteToFiler(Writer); WriteBoolean(FLooped); //Writer.WriteString(MethodName(@FOnTravelStart)); //Writer.WriteString(MethodName(@FOnTravelStop)); end; end; end; procedure TGLMovementPath.ReadFromFiler(reader : TReader); var I: Integer; Count: Integer; //S: string; begin ClearNodes; FEstimateTime := 0; with Reader do begin ReadInteger; // ignore Archive Version if ReadBoolean then begin FName := ReadString; FStartTime := ReadFloat; //List count read here Count := ReadInteger; for I:=0 to Count-1 do begin AddNode; Nodes[I].ReadFromFiler(Reader); end; FLooped := ReadBoolean; { S := ReadString; @FOnTravelStart := MethodAddress(S); S := ReadString; @FOnTravelStop := MethodAddress(S); } end else begin FStartTime := 0; FLooped := False; FOnTravelStart := nil; FOnTravelStop := nil; end; end; FInTravel := False; if Assigned(FCurrentNode) then begin FCurrentNode.free; FCurrentNode := nil; end; FCurrentNodeIndex := -1; end; *) procedure TGLMovementPath.Assign(Source: TPersistent); var I: integer; begin if Source is TGLMovementPath then begin ClearNodes; for I := 0 to TGLMovementPath(Source).NodeCount - 1 do begin AddNode; Nodes[I].Assign(TGLMovementPath(Source).Nodes[I]); FStartTime := TGLMovementPath(Source).FStartTime; //FEstimateTime := TGLMovementPath(Source).FEstimateTime; FLooped := TGLMovementPath(Source).FLooped; end; end; end; function TGLMovementPath.AddNode: TGLPathNode; var Node: TGLPathNode; I: integer; begin //Add a empty node, if it's not the first one, try locate the node to the previous one Node := FNodes.Add; I := FNodes.Count; if I > 1 then Node.Assign(Nodes[I - 2]); Result := Node; end; function TGLMovementPath.AddNode(Node: TGLPathNode): TGLPathNode; begin Result := AddNode; if Assigned(Node) then Result.Assign(Node); end; //------------------------- TGLMovementPaths ---------------------------------- constructor TGLMovementPaths.Create(aOwner: TGLMovement); begin Owner := aOwner; inherited Create(TGLMovementPath); end; procedure TGLMovementPaths.SetItems(index: integer; const val: TGLMovementPath); begin inherited Items[index] := val; end; function TGLMovementPaths.GetOwner: TPersistent; begin Result := Owner; end; function TGLMovementPaths.GetItems(index: integer): TGLMovementPath; begin Result := TGLMovementPath(inherited Items[index]); end; function TGLMovementPaths.Add: TGLMovementPath; begin Result := (inherited Add) as TGLMovementPath; end; function TGLMovementPaths.FindItemID(ID: integer): TGLMovementPath; begin Result := (inherited FindItemID(ID)) as TGLMovementPath; end; procedure TGLMovementPaths.Delete(index: integer); var item: TCollectionItem; begin item := inherited Items[index]; item.Collection := nil; item.Free; end; procedure TGLMovementPaths.NotifyChange; begin //Do nothing here end; //--------------------------- TGLMovement -------------------------------------- constructor TGLMovement.Create(aOwner: TXCollection); begin inherited Create(aOwner); FPaths := TGLMovementPaths.Create(Self); FAutoStartNextPath := True; FActivePathIndex := -1; FOnAllPathTravelledOver := nil; FOnPathTravelStart := nil; FOnPathTravelStop := nil; end; destructor TGLMovement.Destroy; begin ClearPaths; FPaths.Free; inherited Destroy; end; procedure TGLMovement.WriteToFiler(writer : TWriter); var WriteStuff: boolean; I: Integer; begin with Writer do begin WriteInteger(0); // Archive Version 0 WriteStuff := (FPaths.Count>0) or (not FAutoStartNextPath) or (FActivePathIndex<>-1); WriteBoolean(WriteStuff); if WriteStuff then begin WriteBoolean(FAutoStartNextPath); WriteInteger(FActivePathIndex); WriteInteger(FPaths.Count); for I:=0 to FPaths.Count-1 do FPaths.Items[I].WriteToFiler(Writer); end; end; end; procedure TGLMovement.ReadFromFiler(reader : TReader); var I: Integer; Count: Integer; Path: TGLMovementPath; begin ClearPaths; with Reader do begin ReadInteger; // Archive Version 0 if ReadBoolean then begin FAutoStartNextPath := ReadBoolean; FActivePathIndex := ReadInteger; Count := ReadInteger; for I:=0 to Count-1 do begin Path := AddPath; Path.ReadFromFiler(Reader); end; end else begin FAutoStartNextPath := True; FActivePathIndex := -1; end; end; end; procedure TGLMovement.ClearPaths; begin FPaths.Clear; FActivePathIndex := -1; end; procedure TGLMovement.PathTravelStart(Sender: TObject); begin if Assigned(FOnPathTravelStart) then FOnPathTravelStart(Self, TGLMovementPath(Sender)); end; procedure TGLMovement.PathTravelStop(Sender: TObject); begin if Assigned(FOnPathTravelStop) then FOnPathTravelStop(Self, TGLMovementPath(Sender), TGLMovementPath(Sender).FLooped); if TGLMovementPath(Sender).FLooped then begin //if looped, then re-start the path StartPathTravel; end else if (FActivePathIndex = FPaths.Count - 1) then begin if (Assigned(FOnAllPathTravelledOver)) then FOnAllPathTravelledOver(Self); end else //auto-start next path if FAutoStartNextPath then begin Inc(FActivePathIndex); StartPathTravel; end; end; function TGLMovement.AddPath: TGLMovementPath; var Path: TGLMovementPath; begin Path := FPaths.Add; Path.OnTravelStart := PathTravelStart; Path.OnTravelStop := PathTravelStop; Result := Path; end; function TGLMovement.AddPath(aObject: TGLBaseSceneObject): TGLMovementPath; begin Result := AddPath; Result.AddNodeFromObject(aObject); end; function TGLMovement.AddPath(Path: TGLMovementPath): TGLMovementPath; begin Result := AddPath; if Assigned(Path) then Result.Assign(Path); end; function TGLMovement.DeletePath: TGLMovementPath; begin Result := DeletePath(FActivePathIndex); end; function TGLMovement.DeletePath(Path: TGLMovementPath): TGLMovementPath; var I: integer; begin Result := nil; for I := 0 to FPaths.Count - 1 do begin if Path = Paths[I] then begin Result := DeletePath(I); break; end; end; end; function TGLMovement.DeletePath(Index: integer): TGLMovementPath; begin Result := nil; if (Index <0) or (Index >=FPaths.Count) then exit; if Index >=0 then begin TGLMovementPath(FPaths[Index]).Free; FPaths.Delete(Index); if FActivePathIndex < 0 then exit; if (Index =0) then begin if FPaths.Count > 0 then FActivePathIndex := 0 else FActivePathIndex := -1; end else begin //one has been deleted, so the index should be equal to FPathList.Count if Index =FPaths.Count then FActivePathIndex := Index -1 else FActivePathIndex := Index; end; Result := ActivePath; end; end; procedure TGLMovement.SetActivePathIndex(Value: integer); begin if FActivePathIndex = Value then exit; //if current has a Active path in travelling, then exit the method if (Assigned(ActivePath)) and (ActivePath.InTravel) then exit; if (Value >= 0) and (Value < FPaths.Count) then begin FActivePathIndex := Value; //Start the new path or wait for the start-command end else if Value < 0 then begin FActivePathIndex := -1; //Stop all the running path end; end; function TGLMovement.NextPath: integer; begin ActivePathIndex := FActivePathIndex + 1; Result := FActivePathIndex; end; function TGLMovement.PrevPath: integer; begin ActivePathIndex := FActivePathIndex - 1; if (FActivePathIndex < 0) and (FPaths.Count > 0) then Result := 0 else Result := FActivePathIndex; end; function TGLMovement.FirstPath: integer; begin if FPaths.Count > 0 then FActivePathIndex := 0; Result := FActivePathIndex; end; function TGLMovement.LastPath: integer; begin if FPaths.Count > 0 then FActivePathIndex := FPaths.Count - 1; Result := FActivePathIndex; end; function TGLMovement.GetActivePath: TGLMovementPath; begin if FActivePathIndex >= 0 then Result := Paths[FActivePathIndex] else Result := nil; end; procedure TGLMovement.SetActivePath(Value: TGLMovementPath); var I: integer; begin ActivePathIndex := -1; for I := 0 to FPaths.Count - 1 do begin if Value = Paths[I] then begin ActivePathIndex := I; break; end; end; end; function TGLMovement.GetPathCount: integer; begin Result := FPaths.Count; end; (* procedure TGLMovement.WriteToFiler(writer : TWriter); var WriteStuff : Boolean; I: Integer; //S: string; begin inherited; with Writer do begin WriteInteger(0); // Archive Version 0 WriteStuff := (FPathList.Count>0) or (FAutoStartNextPath) or (FActivePathIndex<>-1) {or (Assigned(OnAllPathTravelledOver))}; WriteBoolean(WriteStuff); if WriteStuff then begin WriteBoolean(FAutoStartNextPath); WriteInteger(FPathList.Count); for I:=0 to FPathList.Count-1 do Paths[I].WriteToFiler(Writer); //the Activepathindex must be write after the path list had been saved WriteInteger(FActivePathIndex); end; end; end; procedure TGLMovement.ReadFromFiler(reader : TReader); var I: Integer; Count: Integer; //S: string; begin inherited; ClearPaths; with Reader do begin ReadInteger; // ignore Archive Version if ReadBoolean then begin FAutoStartNextPath := ReadBoolean; //List count read here Count := ReadInteger; for I:=0 to Count-1 do begin AddPath; Paths[I].ReadFromFiler(Reader); end; //the Activepathindex must be write after the path list had been saved FActivePathIndex := ReadInteger; end else begin FAutoStartNextPath := False; FOnAllPathTravelledOver := nil; end; end; end; *) procedure TGLMovement.Assign(Source: TPersistent); var I: integer; begin if Source is TGLMovement then begin ClearPaths; for I := 0 to TGLMovement(Source).PathCount - 1 do begin AddPath; Paths[I].Assign(TGLMovement(Source).Paths[I]); end; FAutoStartNextPath := TGLMovement(Source).FAutoStartNextPath; end; end; class function TGLMovement.FriendlyName: string; begin Result := 'Movement controls' end; class function TGLMovement.FriendlyDescription: string; begin Result := 'Object movement path controls' end; class function TGLMovement.UniqueItem: boolean; begin Result := True; end; var OldTime: double = 0.0; procedure TGLMovement.StartPathTravel; var newTime: double; begin if FActivePathIndex < 0 then exit; //convert the time to second newTime := 0; OldTime := newTime; Paths[FActivePathIndex].TravelPath(True, newTime); end; procedure TGLMovement.StopPathTravel; begin if FActivePathIndex < 0 then exit; Paths[FActivePathIndex].TravelPath(False); end; //Calculate functions add into this method procedure TGLMovement.DoProgress(const deltaTime, newTime: double); var Path: TGLMovementPath; begin if (FActivePathIndex >= 0) and (Paths[FActivePathIndex].InTravel) then //if deltaTime >= 0.033 then begin Path := Paths[FActivePathIndex]; Path.CalculateState(newTime); if Assigned(Path.CurrentNode) then begin if Owner.Owner is TGLBaseSceneObject then with TGLBaseSceneObject(Owner.Owner) do begin Position.AsVector := Path.CurrentNode.FPosition; Scale.AsVector := Path.CurrentNode.FScale; Rotation.AsVector := Path.CurrentNode.FRotation; end; end; end; end; function GetMovement(behaviours: TGLBehaviours): TGLMovement; overload; var i: integer; begin i := behaviours.IndexOfClass(TGLMovement); if i >= 0 then Result := TGLMovement(behaviours[i]) else Result := nil; end; function GetMovement(obj: TGLBaseSceneObject): TGLMovement; overload; begin Result := GetMovement(obj.behaviours); end; function GetOrCreateMovement(behaviours: TGLBehaviours): TGLMovement; overload; var i: integer; begin i := behaviours.IndexOfClass(TGLMovement); if i >= 0 then Result := TGLMovement(behaviours[i]) else Result := TGLMovement.Create(behaviours); end; function GetOrCreateMovement(obj: TGLBaseSceneObject): TGLMovement; overload; begin Result := GetOrCreateMovement(obj.behaviours); end; procedure StartStopTravel(Obj: TGLBaseSceneObject; Start: Boolean); var NewObj: TGLBaseSceneObject; I: Integer; Movement: TGLMovement; begin Movement := GetMovement(Obj); if Assigned(Movement) then if Start then begin if (Movement.PathCount>0) and (Movement.ActivePathIndex=-1) then Movement.ActivePathIndex := 0; Movement.StartPathTravel; end else Movement.StopPathTravel; for I:=0 to Obj.Count-1 do begin NewObj := Obj.Children[I]; StartStopTravel(NewObj, Start); end; end; procedure StartAllMovements(Scene: TGLScene; StartCamerasMove, StartObjectsMove: Boolean); begin if Assigned(Scene) then begin if StartCamerasMove then StartStopTravel(Scene.Cameras, StartCamerasMove); if StartObjectsMove then StartStopTravel(Scene.Objects, StartObjectsMove); end; end; procedure StopAllMovements(Scene: TGLScene; StopCamerasMove, StopObjectsMove: Boolean); begin if Assigned(Scene) then begin if StopCamerasMove then StartStopTravel(Scene.Cameras, False); if StopObjectsMove then StartStopTravel(Scene.Objects, False); end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // class registrations RegisterXCollectionItemClass(TGLMovement); end.
unit nxAttributes; interface type TDisplayTextAttribute = class(TCustomAttribute) private FDisplayText: string; public constructor Create(aDisplayText: string); property DisplayText: string read FDisplayText write FDisplayText; end; implementation constructor TDisplayTextAttribute.Create(aDisplayText: string); begin FDisplayText := aDisplayText; end; end.
unit classes.ScriptDDL; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants; type TScriptDDL = class(TObject) private class var aInstance : TScriptDDL; const TABLE_VERSAO = 'tbl_versao'; TABLE_INFO = 'tbl_info'; TABLE_USUARIO = 'tbl_usuario'; TABLE_ESPECIALIDADE = 'tbl_especialidade'; TABLE_NOTIFICACAO = 'app_notificacao'; TABLE_MENSAGEM = 'app_mensagem'; public class function GetInstance : TScriptDDL; function getCreateTableVersao : TStringList; function getCreateTableEspecialidade : TStringList; function getCreateTableUsuario : TStringList; function getCreateTableNotificacao : TStringList; virtual; abstract; function getCreateTableMensagem : TStringList; virtual; abstract; function getAlterTableUsuario : TStringList; function getTableNameEspecialidade : String; function getTableNameUsuario : String; function getTableNameNotificacao : String; function getTableNameMensagem : String; end; implementation { TScriptDDL } function TScriptDDL.getAlterTableUsuario: TStringList; var aSQL : TStringList; begin aSQL := TStringList.Create; try aSQL.Clear; aSQL.BeginUpdate; aSQL.Add('ALTER TABLE ' + TABLE_USUARIO + ' '); aSQL.Add(' ADD nr_celular STRING (50)'); aSQL.Add(' , ADD id_dispositivo STRING (250)'); aSQL.Add(' , ADD dk_dispositivo STRING (250)'); aSQL.EndUpdate; finally Result := aSQL; end; end; function TScriptDDL.getCreateTableEspecialidade: TStringList; var aSQL : TStringList; begin aSQL := TStringList.Create; try aSQL.Clear; aSQL.BeginUpdate; aSQL.Add('CREATE TABLE IF NOT EXISTS ' + TABLE_ESPECIALIDADE + ' ('); aSQL.Add(' cd_especialidade INTEGER NOT NULL PRIMARY KEY'); aSQL.Add(' , ds_especialidade STRING (50)'); aSQL.Add(')'); aSQL.EndUpdate; finally Result := aSQL; end; end; function TScriptDDL.getCreateTableUsuario: TStringList; var aSQL : TStringList; begin aSQL := TStringList.Create; try aSQL := TStringList.Create; aSQL.Clear; aSQL.BeginUpdate; aSQL.Add('CREATE TABLE IF NOT EXISTS ' + TABLE_USUARIO + ' ('); aSQL.Add(' id_usuario STRING (38) NOT NULL PRIMARY KEY'); aSQL.Add(' , cd_usuario STRING (30) NOT NULL'); aSQL.Add(' , nm_usuario STRING (50)'); aSQL.Add(' , ds_email STRING (50)'); aSQL.Add(' , ds_senha STRING (100)'); aSQL.Add(' , cd_prestador NUMERIC'); aSQL.Add(' , ds_observacao STRING (50)'); aSQL.Add(' , nr_celular STRING (50)'); aSQL.Add(' , id_dispositivo STRING (250)'); aSQL.Add(' , tk_dispositivo STRING (250)'); aSQL.Add(' , sn_ativo STRING (1) NOT NULL'); aSQL.Add(')'); aSQL.EndUpdate; finally Result := aSQL; end; end; function TScriptDDL.getCreateTableVersao: TStringList; var aSQL : TStringList; begin aSQL := TStringList.Create; try aSQL.Clear; aSQL.BeginUpdate; aSQL.Add('CREATE TABLE IF NOT EXISTS ' + TABLE_VERSAO + ' ('); aSQL.Add(' cd_versao INTEGER NOT NULL PRIMARY KEY'); aSQL.Add(' , ds_versao STRING (30)'); aSQL.Add(' , dt_versao DATE'); aSQL.Add(')'); aSQL.EndUpdate; finally Result := aSQL; end; end; class function TScriptDDL.GetInstance: TScriptDDL; begin if not Assigned(aInstance) then aInstance := TScriptDDL.Create; Result := aInstance; end; function TScriptDDL.getTableNameEspecialidade: String; begin Result := TABLE_ESPECIALIDADE; end; function TScriptDDL.getTableNameMensagem: String; begin Result := TABLE_MENSAGEM; end; function TScriptDDL.getTableNameNotificacao: String; begin Result := TABLE_NOTIFICACAO; end; function TScriptDDL.getTableNameUsuario: String; begin Result := TABLE_USUARIO; end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Model relacionado à tabela [PESSOA] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit Pessoa; interface uses Generics.Collections, System.SysUtils, PessoaContato, PessoaEndereco, PessoaFisica, PessoaJuridica, PessoaTelefone, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TPessoa = class(TModelBase) private FId: Integer; FNome: string; FTipo: string; FSite: string; FEmail: string; FCliente: string; FFornecedor: string; FTransportadora: string; FColaborador: string; FContador: string; FPessoaFisica: TPessoaFisica; FPessoaJuridica: TPessoaJuridica; FListaPessoaContato: TObjectList<TPessoaContato>; FListaPessoaEndereco: TObjectList<TPessoaEndereco>; FListaPessoaTelefone: TObjectList<TPessoaTelefone>; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('NOME')] [MVCNameAsAttribute('nome')] property Nome: string read FNome write FNome; [MVCColumnAttribute('TIPO')] [MVCNameAsAttribute('tipo')] property Tipo: string read FTipo write FTipo; [MVCColumnAttribute('SITE')] [MVCNameAsAttribute('site')] property Site: string read FSite write FSite; [MVCColumnAttribute('EMAIL')] [MVCNameAsAttribute('email')] property Email: string read FEmail write FEmail; [MVCColumnAttribute('CLIENTE')] [MVCNameAsAttribute('cliente')] property Cliente: string read FCliente write FCliente; [MVCColumnAttribute('FORNECEDOR')] [MVCNameAsAttribute('fornecedor')] property Fornecedor: string read FFornecedor write FFornecedor; [MVCColumnAttribute('TRANSPORTADORA')] [MVCNameAsAttribute('transportadora')] property Transportadora: string read FTransportadora write FTransportadora; [MVCColumnAttribute('COLABORADOR')] [MVCNameAsAttribute('colaborador')] property Colaborador: string read FColaborador write FColaborador; [MVCColumnAttribute('CONTADOR')] [MVCNameAsAttribute('contador')] property Contador: string read FContador write FContador; [MVCNameAsAttribute('pessoaFisica')] property PessoaFisica: TPessoaFisica read FPessoaFisica write FPessoaFisica; [MVCNameAsAttribute('pessoaJuridica')] property PessoaJuridica: TPessoaJuridica read FPessoaJuridica write FPessoaJuridica; [MapperListOf(TPessoaContato)] [MVCNameAsAttribute('listaPessoaContato')] property ListaPessoaContato: TObjectList<TPessoaContato> read FListaPessoaContato write FListaPessoaContato; [MapperListOf(TPessoaEndereco)] [MVCNameAsAttribute('listaPessoaEndereco')] property ListaPessoaEndereco: TObjectList<TPessoaEndereco> read FListaPessoaEndereco write FListaPessoaEndereco; [MapperListOf(TPessoaTelefone)] [MVCNameAsAttribute('listaPessoaTelefone')] property ListaPessoaTelefone: TObjectList<TPessoaTelefone> read FListaPessoaTelefone write FListaPessoaTelefone; end; implementation { TPessoa } constructor TPessoa.Create; begin FListaPessoaContato := TObjectList<TPessoaContato>.Create; FListaPessoaEndereco := TObjectList<TPessoaEndereco>.Create; FPessoaFisica := TPessoaFisica.Create; FPessoaJuridica := TPessoaJuridica.Create; FListaPessoaTelefone := TObjectList<TPessoaTelefone>.Create; end; destructor TPessoa.Destroy; begin FreeAndNil(FListaPessoaContato); FreeAndNil(FListaPessoaEndereco); FreeAndNil(FPessoaFisica); FreeAndNil(FPessoaJuridica); FreeAndNil(FListaPessoaTelefone); inherited; end; procedure TPessoa.ValidarInsercao; begin inherited; end; procedure TPessoa.ValidarAlteracao; begin inherited; end; procedure TPessoa.ValidarExclusao; begin inherited; end; end.
unit uStack; interface uses System.SysUtils, System.Generics.Collections; type IStack<T> = interface ['{FB717B81-3475-4E19-9235-CAF0A44CD02B}'] procedure Push(Const pItem: T); function Pop: T; function Peek: T; function Size: Integer; function IsEmpty: Boolean; end; TStack<T> = Class(TInterfacedObject, IStack<T>) private FList: TList<T>; public constructor create; destructor Destroy; override; procedure Push(Const pItem: T); function Pop: T; function Peek: T; function Size: Integer; function IsEmpty: Boolean; end; implementation uses System.Math; { TStack<T> } constructor TStack<T>.create; begin Self.FList := TList<T>.Create; end; destructor TStack<T>.Destroy; begin Self.FList.Free; inherited; end; function TStack<T>.IsEmpty: Boolean; begin Result := Self.FList.Count = ZeroValue; end; function TStack<T>.Peek: T; begin Result := Self.FList[ZeroValue]; end; function TStack<T>.Pop: T; begin Result := Self.Peek; Self.FList.Delete(ZeroValue); end; procedure TStack<T>.Push(Const pItem: T); begin Self.FList.Insert(ZeroValue,pItem); end; function TStack<T>.Size: Integer; begin Result := Self.FList.Count; end; end.
unit SNTPWinshoe; {* Winshoe SNTP (Simple Network Time Protocol) behaves more or less according to RFC-3030 Originally by R. Brian Lindahl @author R. Brian Lindahl 01/13/2000 - MTL - Moved to new Palette Tab scheme (Winshoes Clients) *} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Winshoes, UDPWinshoe; type TWinshoeSNTP = class(TWinshoeUDPClient) protected function GetDateTime : TDateTime; public constructor Create(aowner : tComponent); override; {: @example You can use code like the following to sync your local computer time with the NTP Server.<br> <code> var SysTimeVar: TSystemTime; begin with WinshoeSNTP do begin DateTimeToSystemTime( DateTime, SysTimeVar) ; SetLocalTime( SysTimeVar ); end; end; </code>:} property DateTime : TDateTime read GetDateTime; published end; // Procs procedure Register; implementation type // format of NTP datagram tNTPGram = packed record head1, head2, head3, head4 : byte; RootDelay : longint; RootDisperson : longint; RefID : longint; Ref1, Ref2, Org1, Org2, Rcv1, Rcv2, Xmit1, Xmit2 : longint; end; // record to facilitate bigend <-> littleend conversions lr = packed record l1, l2, l3, l4 : byte; end; // convert bigendian to littleendian or vice versa function flip(var n : longint) : longint; var n1, n2 : lr; begin n1 := lr(n); n2.l1 := n1.l4; n2.l2 := n1.l3; n2.l3 := n1.l2; n2.l4 := n1.l1; flip := longint(n2); end; // get offset of time zone from Windows - returned as fractional days // (same units as TDateTime) // should be ADDED to convert local -> UTC // should be SUBTRACTED to convert UTC -> local function tzbias : double; var tz : TTimeZoneInformation; begin GetTimeZoneInformation(tz); result := tz.Bias / 1440; end; const maxint2 = 4294967296.0; // convert TDateTime to 2 longints - NTP timestamp format procedure dt2ntp(dt : tdatetime; var nsec, nfrac : longint); var d, d1 : double; begin d := dt + tzbias - 2; // convert to UTC d := d * 86400; // convert days -> seconds d1 := d; if d1 > maxint then begin d1 := d1 - maxint2; end; nsec := trunc(d1); d1 := ((frac(d) * 1000) / 1000) * maxint2; if d1 > maxint then begin d1 := d1 - maxint2; end; nfrac := trunc(d1); end; // convert 2 longints - NTP timestamp format - to TDateTime function ntp2dt(nsec, nfrac : longint) : tdatetime; var d, d1 : double; begin d := nsec; if d < 0 then d := maxint2 + d - 1; d1 := nfrac; if d1 < 0 then d1 := maxint2 + d1 - 1; d1 := d1 / maxint2; d1 := trunc(d1 * 1000) / 1000; // round to milliseconds result := (d + d1) / 86400; // account for time zone and 2 day offset of TDateTime result := result - tzbias + 2; end; constructor TWinshoeSNTP.Create(aowner : tComponent); begin inherited; // sntp is on port 123 Port := 123; end; {: @example You can use code like the following to sync your local computer time with the NTP Server.<br> <code> var SysTimeVar: TSystemTime; begin with WinshoeSNTP do begin DateTimeToSystemTime( DateTime, SysTimeVar) ; SetLocalTime( SysTimeVar ); end; end; </code>:} function TWinshoeSNTP.GetDateTime : TDateTime; var ng : TNTPGram; s : string; begin fillchar(ng, sizeof(ng), 0); // version 3, mode 3 ng.head1 := $1B; dt2ntp(now, ng.Xmit1, ng.xmit2); ng.Xmit1 := flip(ng.xmit1); ng.Xmit2 := flip(ng.xmit2); setlength(s, sizeof(ng)); move(ng, s[1], sizeof(ng)); Connect; try UDPSize := sizeof(ng); Send(s); s := receive; move(s[1], ng, sizeof(ng)); result := ntp2dt(flip(ng.xmit1), flip(ng.xmit2)); finally Disconnect; end; end; procedure Register; begin RegisterComponents('Winshoes Clients', [TWinshoeSNTP]); end; end.
unit CustomizeObjectFilters; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, CheckLst, ActnList, DB, MemDS, DBAccess, Ora, JvStringHolder, BCControls.ComboBox, JvExControls, JvSpeedButton, Vcl.ExtCtrls, BCDialogs.Dlg, System.Actions; type TCustomizeObjectFiltersDialog = class(TDialog) ActionList: TActionList; BottomPanel: TPanel; CancelButton: TButton; ClientPanel: TPanel; DeselectAllAction: TAction; DeselectAllButton: TButton; NameComboBox: TBCComboBox; NameLabel: TLabel; ObjectsCheckListBox: TCheckListBox; ObjectsQuery: TOraQuery; OKAction: TAction; OKButton: TButton; RemoveAction: TAction; RemoveSpeedButton: TJvSpeedButton; SelectAllAction: TAction; SelectAllButton: TButton; Separator1Panel: TPanel; Separator2Panel: TPanel; Separator3Panel: TPanel; SQLStringHolder: TJvMultiStringHolder; TopPanel: TPanel; procedure DeselectAllActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure NameComboBoxChange(Sender: TObject); procedure OKActionExecute(Sender: TObject); procedure RemoveActionExecute(Sender: TObject); procedure SelectAllActionExecute(Sender: TObject); private { Private declarations } FObjectType: string; FSchemaName: string; FSchemaParam: string; function GetFilterName: string; function GetObjects: string; procedure FillCombo; procedure GetTableAndField(var Table: string; var Field: String; var ExtraCondition: string); procedure SetObjects; public { Public declarations } function Open(OraSession: TOraSession; SchemaParam: string; ObjectType: string; SchemaName: string): Boolean; property FilterName: string read GetFilterName; end; function CustomizeObjectFiltersDialog: TCustomizeObjectFiltersDialog; implementation {$R *.dfm} uses BigIni, Lib, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.FileUtils, BCCommon.StringUtils; const CAPTION_TEXT = 'Customize %s Filters'; var FCustomizeObjectFiltersDialog: TCustomizeObjectFiltersDialog; function CustomizeObjectFiltersDialog: TCustomizeObjectFiltersDialog; begin if not Assigned(FCustomizeObjectFiltersDialog) then Application.CreateForm(TCustomizeObjectFiltersDialog, FCustomizeObjectFiltersDialog); Result := FCustomizeObjectFiltersDialog; SetStyledFormSize(Result); end; procedure TCustomizeObjectFiltersDialog.DeselectAllActionExecute(Sender: TObject); begin ObjectsCheckListBox.CheckAll(cbUnChecked, false, false); end; procedure TCustomizeObjectFiltersDialog.FormDestroy(Sender: TObject); begin FCustomizeObjectFiltersDialog := nil; end; procedure TCustomizeObjectFiltersDialog.SelectAllActionExecute(Sender: TObject); begin ObjectsCheckListBox.CheckAll(cbChecked, false, false); end; function TCustomizeObjectFiltersDialog.GetObjects: string; var i: Integer; begin Result := ''; for i := 0 to ObjectsCheckListBox.Count - 1 do if ObjectsCheckListBox.Checked[i] then begin if Result <> '' then Result := Result + ','; Result := Result + QuotedStr(ObjectsCheckListBox.Items.Strings[i]); end; end; function TCustomizeObjectFiltersDialog.GetFilterName: string; begin Result := Trim(NameComboBox.Text); end; procedure TCustomizeObjectFiltersDialog.OKActionExecute(Sender: TObject); var i: Integer; Objects, KeyValue: string; SchemaObjectFilters: TStrings; begin if FilterName = '' then begin ShowErrorMessage('Set name.'); Exit; end; Objects := GetObjects; SchemaObjectFilters := TStringList.Create; KeyValue := Lib.GetObjectFilterKeyValue(FObjectType, FilterName, FSchemaName); with TBigIniFile.Create(GetINIFilename) do try { delete key, string is crypted, so it must be deleted like this } ReadSectionValues('SchemaObjectFilters', SchemaObjectFilters); for i := 0 to SchemaObjectFilters.Count - 1 do if KeyValue = DecryptString(System.Copy(SchemaObjectFilters.Strings[i], 0, Pos('=', SchemaObjectFilters.Strings[i]) - 1)) then begin DeleteKey('SchemaObjectFilters', System.Copy(SchemaObjectFilters.Strings[i], 0, Pos('=', SchemaObjectFilters.Strings[i]) - 1)); Break; end; { write ini } WriteString('SchemaObjectFilters', EncryptString(KeyValue), EncryptString(Objects)); finally Free; end; ModalResult := mrOk; end; procedure TCustomizeObjectFiltersDialog.GetTableAndField(var Table: string; var Field: string; var ExtraCondition: string); begin ExtraCondition := 'AND owner = :p_owner'; if FObjectType = OBJECT_TYPE_TABLE then begin Field := 'table_name'; Table := 'all_tables'; ExtraCondition := ExtraCondition + ' AND table_name NOT IN (SELECT mview_name FROM all_mviews)'; end else if FObjectType = OBJECT_TYPE_VIEW then begin Field := 'view_name'; Table := 'all_views'; end else if FObjectType = OBJECT_TYPE_FUNCTION then begin Field := 'name'; Table := 'all_source'; ExtraCondition := ExtraCondition + ' AND type = ''FUNCTION'''; end else if FObjectType = OBJECT_TYPE_PROCEDURE then begin Field := 'name'; Table := 'all_source'; ExtraCondition := ExtraCondition + ' AND type = ''PROCEDURE'''; end else if FObjectType = OBJECT_TYPE_PACKAGE then begin Field := 'name'; Table := 'all_source'; ExtraCondition := ExtraCondition + ' AND type = ''PACKAGE'''; end else if FObjectType = OBJECT_TYPE_TRIGGER then begin Field := 'trigger_name'; Table := 'all_triggers'; end else if FObjectType = OBJECT_TYPE_CONSTRAINT then begin Field := 'constraint_name'; Table := 'all_constraints'; end else if FObjectType = OBJECT_TYPE_INDEX then begin Field := 'index_name'; Table := 'all_indexes'; end else if FObjectType = OBJECT_TYPE_SEQUENCE then begin Field := 'sequence_name'; Table := 'all_sequences'; ExtraCondition := 'AND sequence_owner = :p_owner'; end else if FObjectType = OBJECT_TYPE_SYNONYM then begin Field := 'synonym_name'; Table := 'all_synonyms'; ExtraCondition := 'AND table_owner = :p_owner'; end else if FObjectType = OBJECT_TYPE_DATABASE_LINK then begin Field := 'db_link'; Table := 'all_db_links'; end else if FObjectType = OBJECT_TYPE_USER then begin Field := 'username'; Table := 'dba_users'; ExtraCondition := ''; end end; procedure TCustomizeObjectFiltersDialog.NameComboBoxChange(Sender: TObject); begin if NameComboBox.Items.IndexOf(NameComboBox.Text) <> -1 then SetObjects; end; procedure TCustomizeObjectFiltersDialog.SetObjects; var i, ObjectsLength: Integer; Objects, Field, Table, ExtraCondition: string; begin GetTableAndField(Table, Field, ExtraCondition); Objects := Lib.GetFilterObjectsFromIni(Lib.GetObjectFilterKeyValue(FObjectType, FilterName, FSchemaName)); ObjectsLength := Length(Objects); if Objects = '' then Objects := ''''''; with ObjectsQuery do begin SQL.Clear; SQL.Add(Format(SQLStringHolder.StringsByName['ObjectsSQL'].Text, [Field, Table, Field, Objects, ObjectsLength, ExtraCondition, Field, Table, Field, Objects, ObjectsLength, ExtraCondition])); if ParamCount > 0 then ParamByName('P_OWNER').AsString := FSchemaParam; Open; try i := 0; ObjectsCheckListBox.Clear; while not Eof do begin ObjectsCheckListBox.Items.Add(FieldByName('OBJECT_NAME').AsWideString); ObjectsCheckListBox.Checked[i] := FieldByName('CHECKED').AsWideString = 'T'; Next; Inc(i); end; if FObjectType = OBJECT_TYPE_VIEW then begin Field := 'mview_name'; Table := 'all_mviews'; Close; SQL.Clear; SQL.Add(Format(SQLStringHolder.StringsByName['ObjectsSQL'].Text, [Field, Table, Field, Objects, ObjectsLength, ExtraCondition, Field, Table, Field, Objects, ObjectsLength, ExtraCondition])); if ParamCount > 0 then ParamByName('P_OWNER').AsString := FSchemaParam; Open; while not Eof do begin ObjectsCheckListBox.Items.Add(FieldByName('OBJECT_NAME').AsWideString); ObjectsCheckListBox.Checked[i] := FieldByName('CHECKED').AsWideString = 'T'; Next; Inc(i); end; end finally Close; end; end; end; procedure TCustomizeObjectFiltersDialog.FillCombo; begin NameComboBox.Items := Lib.GetObjectFilterNames(FObjectType, FSchemaName); end; function TCustomizeObjectFiltersDialog.Open(OraSession: TOraSession; SchemaParam: string; ObjectType: string; SchemaName: string): Boolean; var Rslt: Integer; begin Caption := Format(CAPTION_TEXT, [AnsiInitCap(ObjectType)]); Lib.SetSession(Self, OraSession); FSchemaParam := SchemaParam; FObjectType := ObjectType; FSchemaName := SchemaName; FillCombo; SetObjects; Rslt := ShowModal; Result := Rslt = mrOk; end; procedure TCustomizeObjectFiltersDialog.RemoveActionExecute(Sender: TObject); var i: Integer; KeyValue: string; SchemaObjectFilters: TStrings; begin if FilterName = '' then begin ShowErrorMessage('Choose a filter.'); NameComboBox.SetFocus; Exit; end; if AskYesOrNo(Format('Remove filter %s, are you sure?', [FilterName])) then begin SchemaObjectFilters := TStringList.Create; KeyValue := Lib.GetObjectFilterKeyValue(FObjectType, FilterName, FSchemaName); with TBigIniFile.Create(GetINIFilename) do try { delete key, string is crypted, so it must be deleted like this } ReadSectionValues('SchemaObjectFilters', SchemaObjectFilters); for i := 0 to SchemaObjectFilters.Count - 1 do if KeyValue = DecryptString(System.Copy(SchemaObjectFilters.Strings[i], 0, Pos('=', SchemaObjectFilters.Strings[i]) - 1)) then begin DeleteKey('SchemaObjectFilters', System.Copy(SchemaObjectFilters.Strings[i], 0, Pos('=', SchemaObjectFilters.Strings[i]) - 1)); Break; end; finally Free; end; NameComboBox.Text := ''; FillCombo; SetObjects; end; end; end.
unit Arrays; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Numbers, StdCtrls; type TArrayInt = array of integer; procedure arrayCompress(var arr: TArrayInt; ranges: TArrayRanges; var compressed: integer); procedure arrayPrint(arr: TArrayInt; var memo: TMemo); procedure arrayPush(var arr: TArrayInt; el: integer); procedure arrayRemove(var arr: TArrayInt; el: integer); function arraySearch(arr: TArrayInt; First: boolean): integer; procedure arraySort(var arr: TArrayInt); implementation {Процедура компресии массива по заданным отрезкам} procedure arrayCompress(var arr: TArrayInt; ranges: TArrayRanges; var compressed: integer); var i, j, k: integer; begin if (Length(arr) > 0) and (Length(ranges) > 0) then begin for i := High(arr) downto Low(arr) do begin if (inRange(arr[i], ranges)) then begin arrayRemove(arr, i); Inc(compressed); end; end; end; end; {Процедура вывода массива в Memo} procedure arrayPrint(arr: TArrayInt; var memo: TMemo); var i: integer; begin memo.Clear; if (Length(arr) > 0) then begin for i := Low(arr) to High(arr) do begin memo.Lines[i] := IntToStr(arr[i]); end; memo.Text := Trim(memo.Text); end; end; {Процедура для добавления нового элемента в массив целочисленных значений} procedure arrayPush(var arr: TArrayInt; el: integer); var newLength: integer; begin newLength := Length(arr) + 1; SetLength(arr, newLength); arr[High(arr)] := el; end; {Процедура удаления элемента из массива} procedure arrayRemove(var arr: TArrayInt; el: integer); var i: integer; begin if (el >= Low(arr)) or (el <= high(arr)) then begin for i := el to High(arr) - 1 do begin arr[i] := arr[i + 1]; end; SetLength(arr, Length(arr) - 1); end; end; {Функция поиска максимального значения} {arr - массив, по которому ищем, first - тип поиска, если истина - вернет первое максимальное значение} function arraySearch(arr: TArrayInt; First: boolean): integer; var i, i_max: integer; begin if (Length(arr) > 0) then begin i_max := Low(arr); for i := Low(arr) to High(arr) do begin if (First) and (arr[i] > arr[i_max]) or (not First) and (arr[i] >= arr[i_max]) then begin i_max := i; end; Result := i_max; end; end else begin Result := -1; end; end; {Процедура сортировки массива методом прямого выбора} procedure arraySort(var arr: TArrayInt); var // номер минимального элемента в части массива от i до верхней границы массива min: integer; // номер элемента, сравниваемого с минимальным j: integer; // буфер, используемый при обмене элементов массива buf: integer; i: integer; begin for i := Low(arr) to High(arr) do begin { поиск минимального элемента в массиве} min := i; for j := i + 1 to High(arr) do if arr[j] < arr[min] then min := j; { поменяем местами a [min] и a[i] } buf := arr[i]; arr[i] := arr[min]; arr[min] := buf; end; end; end.
unit uMCConnection; {$mode objfpc}{$H+} interface uses Classes, SysUtils, blcksock, synsock, uLog, uNetwork, uCrypt, uStrUtils, uScheduler, uBatchExecute, uSchedulerExecuter, uAlarm, uReportBuilder; type TThreadMCConnection = class(TThread) private ss: TSocket; trMCLogonPwd: string; // settings mirror trsManagerConsoleListeningPort: integer; trsAgentCollectorListeningPort: integer; trsAgentInformationListeningPort: integer; trsReservServiceListeningPort: integer; trsSudoPwd: string; trsMCLogonPwd: string; trsAgentInformationLogonPwd: string; trarrSchedulerEventsArr: uScheduler.TSchedulerEventArr; trarrBatchData: uBatchExecute.TBatchArray; trarrAlarmTemplates: uAlarm.TAlarmTemplateArray; trarrRTM: array of uLog.TOnLineMonitoringElement; trUptimeSec: int64; // status msg array to send trArrMSG: array of string; trLogMsg: string; //procedure toLog; procedure trWriteLog(msg_str: string); procedure trGetSettings; procedure trGetRTM; procedure trGetSchArr; procedure trSetSchArr; procedure trGetBatchList; procedure trSetBatchList; procedure trGetAlarmTemplates; procedure trSetAlarmTemplates; procedure trGetPrm; procedure trSetPrm; procedure trGetUptime; procedure trAddMSGToSend(m: string); protected { Protected declarations } procedure Execute; override; public constructor Create(in_ss: TSocket); end; implementation { TThreadMCConnection } uses uMain; constructor TThreadMCConnection.Create(in_ss: TSocket); begin inherited Create(False); FreeOnTerminate := True; ss := in_ss; end; procedure TThreadMCConnection.trGetUptime; begin cs14.Enter; trUptimeSec := trunc((Now - uMain.ServerStartTime) * 24 * 3600); cs14.Leave; end; procedure TThreadMCConnection.trGetSchArr; var x: integer; begin cs12.Enter; Setlength(trarrSchedulerEventsArr, length(uMain.arrSchedulerEventsArr)); for x := 1 to Length(uMain.arrSchedulerEventsArr) do begin trarrSchedulerEventsArr[x - 1] := uMain.arrSchedulerEventsArr[x - 1]; end; cs12.Leave; end; procedure TThreadMCConnection.trGetRTM; var x: integer; begin cs15.Enter; Setlength(trarrRTM, length(uMain.arrOnLineMonitoring)); for x := 1 to Length(uMain.arrOnLineMonitoring) do begin trarrRTM[x - 1] := uMain.arrOnLineMonitoring[x - 1]; end; cs15.Leave; end; procedure TThreadMCConnection.trSetSchArr; var x, y: integer; tmpArrEventResult: array of uSchedulerExecuter.TEventResult; found: boolean; begin cs12.Enter; Setlength(uMain.arrSchedulerEventsArr, length(trarrSchedulerEventsArr)); for x := 1 to Length(trarrSchedulerEventsArr) do begin uMain.arrSchedulerEventsArr[x - 1] := trarrSchedulerEventsArr[x - 1]; end; cs12.Leave; // check Event Result array cs8.Enter; SetLength(tmpArrEventResult, length(uMain.arrEventResultArray)); for x := 1 to length(uMain.arrEventResultArray) do begin tmpArrEventResult[x - 1] := uMain.arrEventResultArray[x - 1]; end; setlength(uMain.arrEventResultArray, 0); for x := 1 to Length(tmpArrEventResult) do begin found := False; for y := 1 to length(trarrSchedulerEventsArr) do begin if tmpArrEventResult[x - 1].er_name = trarrSchedulerEventsArr[y - 1].event_name then begin found := True; Continue; end; end; if found then begin setlength(uMain.arrEventResultArray, length(uMain.arrEventResultArray) + 1); uMain.arrEventResultArray[length(uMain.arrEventResultArray) - 1] := tmpArrEventResult[x - 1]; end; end; cs8.Leave; uMain.SaveSchedulerEvents; cs13.Enter; uMain.NeedSchedulerUpdate := True; cs13.Leave; end; procedure TThreadMCConnection.trGetBatchList; var x: integer; begin cs9.Enter; Setlength(trarrBatchData, length(uMain.arrBatchData)); for x := 1 to Length(uMain.arrBatchData) do begin trarrBatchData[x - 1] := uMain.arrBatchData[x - 1]; end; cs9.Leave; end; procedure TThreadMCConnection.trSetBatchList; var x: integer; begin cs9.Enter; Setlength(uMain.arrBatchData, length(trarrBatchData)); for x := 1 to Length(trarrBatchData) do begin uMain.arrBatchData[x - 1] := trarrBatchData[x - 1]; end; cs9.Leave; //cs13.Enter; //uMain.NeedSchedulerUpdate := True; //cs13.Leave; uMain.SaveBatchData; end; procedure TThreadMCConnection.trGetAlarmTemplates; var x: integer; begin cs10.Enter; Setlength(trarrAlarmTemplates, length(uMain.arrAlarmTemplates)); for x := 1 to Length(uMain.arrAlarmTemplates) do begin trarrAlarmTemplates[x - 1] := uMain.arrAlarmTemplates[x - 1]; end; cs10.Leave; end; procedure TThreadMCConnection.trSetAlarmTemplates; var x: integer; begin cs10.Enter; Setlength(uMain.arrAlarmTemplates, length(trarrAlarmTemplates)); for x := 1 to Length(trarrAlarmTemplates) do begin uMain.arrAlarmTemplates[x - 1] := trarrAlarmTemplates[x - 1]; end; cs10.Leave; //cs13.Enter; //uMain.NeedSchedulerUpdate:=true; //cs13.Leave; uMain.SaveAlarmTemplates; end; procedure TThreadMCConnection.trAddMSGToSend(m: string); begin SetLength(trArrMSG, length(trArrMSG) + 1); trArrMSG[length(trArrMSG) - 1] := m; end; procedure TThreadMCConnection.Execute; var S: TTCPBlockSocket; alive: boolean; res_str: string; tmp_int1: integer; tmp_str1, tmp_str2, tmp_str3, tmp_str4: string; tmp_dt1, tmp_dt2: tdatetime; is_valid_logon, is_valid_version: boolean; tmp_bool1: boolean; x: integer; curr_bch_cnt, max_bch_cnt, curr_bch_cnt_finished: integer; curr_alr_cnt, max_alr_cnt, curr_alr_cnt_finished: integer; curr_sch_cnt, max_sch_cnt, curr_sch_cnt_finished: integer; tf: textfile; last_rtm_index: int64; arrTMPRTM: array of uLog.TOnLineMonitoringElement; begin is_valid_logon := False; is_valid_version := False; //Synchronize(@trGetSettings); trGetSettings; SetLength(trArrMSG, 0); S := TTCPBlockSocket.Create; S.Socket := ss; alive := True; while alive do begin res_str := uNetwork.GetStringViaSocket(S, 600000); // 10 min if res_str = '' then begin alive := False; break; end; // login ================================== if leftstr(res_str, 9) = 'log_in_mc' then begin tmp_str1 := rightstr(res_str, length(res_str) - 9); tmp_str1 := uCrypt.DecodeString(tmp_str1); if tmp_str1 = trMCLogonPwd then begin is_valid_logon := True; uNetwork.SendStringViaSocket(S, 'LOGON SUCCESS', SNDRCVTimeout); end else begin uNetwork.SendStringViaSocket(S, 'MSGInvalid password!', SNDRCVTimeout); alive := False; break; end; Continue; end; if leftstr(res_str, 7) = 'app_ver' then begin tmp_str1 := rightstr(res_str, length(res_str) - 7); if tmp_str1 = umain.GetAppVer() then begin is_valid_version := True; uNetwork.SendStringViaSocket(S, 'APP VERSION VALID', SNDRCVTimeout); end else begin uNetwork.SendStringViaSocket( S, 'MSGIMS server and console version must be identical!', SNDRCVTimeout); alive := False; break; end; Continue; end; if (not is_valid_logon) or (not is_valid_version) then begin uNetwork.SendStringViaSocket(S, 'MSGInvalid logon sequence!', SNDRCVTimeout); alive := False; break; end; if leftstr(res_str, 7) = 'log_out' then begin uNetwork.SendStringViaSocket(S, 'LOGOUT SUCCESS', SNDRCVTimeout); alive := False; break; end; if leftstr(res_str, 6) = 'os_ver' then begin {$IFDEF WINDOWS} uNetwork.SendStringViaSocket(S, 'WIN', SNDRCVTimeout); {$ENDIF} {$IFDEF UNIX} uNetwork.SendStringViaSocket(S, 'LIN', SNDRCVTimeout); {$ENDIF} Continue; end; // ======================================== // echo ========================== if res_str = 'echo' then begin uNetwork.SendStringViaSocket(S, 'echo_answer', SNDRCVTimeout); Continue; end; // ========================================= // uptime =================================== if res_str = 'get_uptime' then begin //Synchronize(@trGetUptime); trGetUptime; uNetwork.SendStringViaSocket(S, 'uptime' + IntToStr(trUptimeSec), SNDRCVTimeout); Continue; end; // ========================================== // msg to send ============================== if res_str = 'read_msg' then begin uNetwork.SendStringViaSocket(S, 'msg_cnt' + IntToStr(Length(trArrMSG)), SNDRCVTimeout); for x := 1 to length(trArrMSG) do begin uNetwork.SendStringViaSocket(S, 'msg_str' + trArrMSG[x - 1], SNDRCVTimeout); end; SetLength(trArrMSG, 0); Continue; end; // ========================================== // real time monitoring ======================= if res_str = 'set_rtm_time' then begin last_rtm_index := 0; //Synchronize(@trGetRTM); trGetRTM; if Length(trarrRTM) > 0 then begin last_rtm_index := trarrRTM[Length(trarrRTM) - 1].olm_index; end; uNetwork.SendStringViaSocket(S, 'rtm_time_ok', SNDRCVTimeout); Continue; end; if res_str = 'read_rtm' then begin //Synchronize(@trGetRTM); trGetRTM; // selecting actual data to send SetLength(arrTMPRTM, 0); for x := 1 to Length(trarrRTM) do begin if trarrRTM[x - 1].olm_index > last_rtm_index then begin setlength(arrTMPRTM, length(arrTMPRTM) + 1); arrTMPRTM[length(arrTMPRTM) - 1] := trarrRTM[x - 1]; end; end; if Length(trarrRTM) > 0 then begin last_rtm_index := trarrRTM[Length(trarrRTM) - 1].olm_index; end; // sending data uNetwork.SendStringViaSocket(S, 'rtm_cnt' + IntToStr( Length(arrTMPRTM)), SNDRCVTimeout); for x := 1 to length(arrTMPRTM) do begin uNetwork.SendStringViaSocket(S, 'rtm_str' + arrTMPRTM[x - 1].olm_msg, SNDRCVTimeout); uNetwork.SendStringViaSocket(S, 'rtm_typ' + IntToStr( arrTMPRTM[x - 1].olm_type), SNDRCVTimeout); end; Continue; end; // ========================================== // settings param rsv and snd ============= if leftstr(res_str, 7) = 'get_prm' then begin //Synchronize(@trGetPrm); trGetPrm; tmp_str1 := rightstr(res_str, length(res_str) - 7); // param name if tmp_str1 = 'ManagerConsoleListeningPort' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + IntToStr( trsManagerConsoleListeningPort), SNDRCVTimeout); end; if tmp_str1 = 'AgentCollectorListeningPort' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + IntToStr( trsAgentCollectorListeningPort), SNDRCVTimeout); end; if tmp_str1 = 'AgentInformationListeningPort' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + IntToStr( trsAgentInformationListeningPort), SNDRCVTimeout); end; if tmp_str1 = 'ReservServiceListeningPort' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + IntToStr( trsReservServiceListeningPort), SNDRCVTimeout); end; if tmp_str1 = 'SudoPwd' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + uCrypt.EncodeString( trsSudoPwd), SNDRCVTimeout); end; if tmp_str1 = 'MCLogonPwd' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + uCrypt.EncodeString( trsMCLogonPwd), SNDRCVTimeout); end; if tmp_str1 = 'AILogonPwd' then begin uNetwork.SendStringViaSocket(S, 'res_prm' + uCrypt.EncodeString( trsAgentInformationLogonPwd), SNDRCVTimeout); end; Continue; end; if leftstr(res_str, 7) = 'set_prm' then begin tmp_str1 := rightstr(res_str, length(res_str) - 7); // param name and new value tmp_str2 := GetFieldFromString(tmp_str1, uMain.ParamLimiter, 1); // param name tmp_str3 := GetFieldFromString(tmp_str1, uMain.ParamLimiter, 2); // param value if tmp_str2 = 'ManagerConsoleListeningPort' then begin tmp_int1 := trsManagerConsoleListeningPort; try trsManagerConsoleListeningPort := StrToInt(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_int1 <> trsManagerConsoleListeningPort then begin trAddMSGToSend('Restarting MC listening service...'); //Synchronize(@trSetPrm); trSetPrm; trAddMSGToSend('MC listening service restarted!'); end; end; if tmp_str2 = 'AgentCollectorListeningPort' then begin tmp_int1 := trsAgentCollectorListeningPort; try trsAgentCollectorListeningPort := StrToInt(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_int1 <> trsAgentCollectorListeningPort then begin //Synchronize(@trSetPrm); trSetPrm; end; end; if tmp_str2 = 'AgentInformationListeningPort' then begin tmp_int1 := trsAgentInformationListeningPort; try trsAgentInformationListeningPort := StrToInt(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_int1 <> trsAgentInformationListeningPort then begin //Synchronize(@trSetPrm); trSetPrm; end; end; if tmp_str2 = 'ReservServiceListeningPort' then begin tmp_int1 := trsReservServiceListeningPort; try trsReservServiceListeningPort := StrToInt(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_int1 <> trsReservServiceListeningPort then begin //Synchronize(@trSetPrm); trSetPrm; end; end; if tmp_str2 = 'SudoPwd' then begin tmp_str4 := trsSudoPwd; try trsSudoPwd := uCrypt.DecodeString(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_str4 <> trsSudoPwd then begin //Synchronize(@trSetPrm); trSetPrm; end; end; if tmp_str2 = 'MCLogonPwd' then begin tmp_str4 := trsMCLogonPwd; try trsMCLogonPwd := uCrypt.DecodeString(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_str4 <> trsMCLogonPwd then begin //Synchronize(@trSetPrm); trSetPrm; end; end; if tmp_str2 = 'AILogonPwd' then begin tmp_str4 := trsAgentInformationLogonPwd; try trsAgentInformationLogonPwd := uCrypt.DecodeString(tmp_str3); uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; if tmp_str4 <> trsAgentInformationLogonPwd then begin //Synchronize(@trSetPrm); trSetPrm; end; end; Continue; end; // ======================================== // sch list rsv and snd =================== if leftstr(res_str, 8) = 'read_sch' then begin //Synchronize(@trGetSchArr); trGetSchArr; uNetwork.SendStringViaSocket(S, 'sch_cnt' + IntToStr( Length(trarrSchedulerEventsArr)), SNDRCVTimeout); for x := 1 to length(trarrSchedulerEventsArr) do begin //ev_days_of_month: string; // 1,2,5,10,24,31 //ev_days_of_week: string; // 1,2,5 //ev_repeat_type: integer; // 1-once per day, 2-every X seconds //ev_repeat_interval: integer; // X seconds //ev_time_h: word; //ev_time_m: word; //ev_time_s: word; //ev_end_time_h: word; //ev_end_time_m: word; //ev_end_time_s: word; - by single string tmp_str1 := trarrSchedulerEventsArr[x - 1].ev_days_of_month + ParamLimiter; tmp_str1 := tmp_str1 + trarrSchedulerEventsArr[x - 1].ev_days_of_week + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_repeat_type) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr( trarrSchedulerEventsArr[x - 1].ev_repeat_interval) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_time_h) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_time_m) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_time_s) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_end_time_h) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_end_time_m) + ParamLimiter; tmp_str1 := tmp_str1 + IntToStr(trarrSchedulerEventsArr[x - 1].ev_end_time_s); uNetwork.SendStringViaSocket(S, 'sch_prm1' + tmp_str1, SNDRCVTimeout); //event_name: string; uNetwork.SendStringViaSocket( S, 'sch_prm2' + trarrSchedulerEventsArr[x - 1].event_name, SNDRCVTimeout); //event_str: string; uNetwork.SendStringViaSocket( S, 'sch_prm3' + trarrSchedulerEventsArr[x - 1].event_str, SNDRCVTimeout); //event_main_param: string; uNetwork.SendStringViaSocket( S, 'sch_prm4' + trarrSchedulerEventsArr[x - 1].event_main_param, SNDRCVTimeout); //event_alarm_str: string; uNetwork.SendStringViaSocket( S, 'sch_prm5' + trarrSchedulerEventsArr[x - 1].event_alarm_str, SNDRCVTimeout); //event_execution_str: string; uNetwork.SendStringViaSocket( S, 'sch_prm6' + trarrSchedulerEventsArr[x - 1].event_execution_str, SNDRCVTimeout); end; Continue; end; if leftstr(res_str, 11) = 'set_sch_cnt' then begin max_sch_cnt := StrToInt(rightstr(res_str, length(res_str) - 11)); setlength(trarrSchedulerEventsArr, max_sch_cnt); curr_sch_cnt := 0; curr_sch_cnt_finished := 0; if max_sch_cnt = 0 then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetSchArr); trSetSchArr; end; Continue; end; if leftstr(res_str, 12) = 'set_sch_prm1' then begin curr_sch_cnt := curr_sch_cnt + 1; tmp_str1 := rightstr(res_str, length(res_str) - 12); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_days_of_month := GetFieldFromString(tmp_str1, uMain.ParamLimiter, 1); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_days_of_week := GetFieldFromString(tmp_str1, uMain.ParamLimiter, 2); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_repeat_type := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 3)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_repeat_interval := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 4)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_time_h := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 5)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_time_m := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 6)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_time_s := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 7)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_end_time_h := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 8)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_end_time_m := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 9)); trarrSchedulerEventsArr[curr_sch_cnt - 1].ev_end_time_s := StrToInt(GetFieldFromString(tmp_str1, uMain.ParamLimiter, 10)); Continue; end; if leftstr(res_str, 12) = 'set_sch_prm2' then begin trarrSchedulerEventsArr[curr_sch_cnt - 1].event_name := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_sch_prm3' then begin trarrSchedulerEventsArr[curr_sch_cnt - 1].event_str := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_sch_prm4' then begin trarrSchedulerEventsArr[curr_sch_cnt - 1].event_main_param := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_sch_prm5' then begin trarrSchedulerEventsArr[curr_sch_cnt - 1].event_alarm_str := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_sch_prm6' then begin trarrSchedulerEventsArr[curr_sch_cnt - 1].event_execution_str := rightstr(res_str, length(res_str) - 12); curr_sch_cnt_finished := curr_sch_cnt_finished + 1; if curr_sch_cnt_finished = max_sch_cnt then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetSchArr); trSetSchArr; end; Continue; end; // ======================================== // bch list rsv and snd ============= if leftstr(res_str, 8) = 'read_bch' then begin //Synchronize(@trGetBatchList); trGetBatchList; uNetwork.SendStringViaSocket(S, 'bch_cnt' + IntToStr( Length(trarrBatchData)), SNDRCVTimeout); for x := 1 to length(trarrBatchData) do begin //event_name: string; uNetwork.SendStringViaSocket( S, 'bch_prm1' + trarrBatchData[x - 1].batch_name, SNDRCVTimeout); //batch_str: string; uNetwork.SendStringViaSocket( S, 'bch_prm2' + trarrBatchData[x - 1].batch_str, SNDRCVTimeout); //batch_params: string; uNetwork.SendStringViaSocket( S, 'bch_prm3' + trarrBatchData[x - 1].batch_params, SNDRCVTimeout); end; Continue; end; if leftstr(res_str, 11) = 'set_bch_cnt' then begin max_bch_cnt := StrToInt(rightstr(res_str, length(res_str) - 11)); setlength(trarrBatchData, max_bch_cnt); curr_bch_cnt := 0; curr_bch_cnt_finished := 0; if max_bch_cnt = 0 then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetBatchList); trSetBatchList; end; Continue; end; if leftstr(res_str, 12) = 'set_bch_prm1' then begin curr_bch_cnt := curr_bch_cnt + 1; trarrBatchData[curr_bch_cnt - 1].batch_name := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_bch_prm2' then begin trarrBatchData[curr_bch_cnt - 1].batch_str := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_bch_prm3' then begin trarrBatchData[curr_bch_cnt - 1].batch_params := rightstr(res_str, length(res_str) - 12); curr_bch_cnt_finished := curr_bch_cnt_finished + 1; if curr_bch_cnt_finished = max_bch_cnt then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetBatchList); trSetBatchList; end; Continue; end; // ======================================== // alarm templates rsv and snd ============= if leftstr(res_str, 8) = 'read_alr' then begin //Synchronize(@trGetAlarmTemplates); trGetAlarmTemplates; uNetwork.SendStringViaSocket(S, 'alr_cnt' + IntToStr( Length(trarrAlarmTemplates)), SNDRCVTimeout); for x := 1 to length(trarrAlarmTemplates) do begin //event_name: string; uNetwork.SendStringViaSocket( S, 'alr_prm1' + trarrAlarmTemplates[x - 1].alarm_template_name, SNDRCVTimeout); //batch_str: string; uNetwork.SendStringViaSocket( S, 'alr_prm2' + trarrAlarmTemplates[x - 1].alarm_template_str, SNDRCVTimeout); //batch_params: string; uNetwork.SendStringViaSocket( S, 'alr_prm3' + trarrAlarmTemplates[x - 1].alarm_template_params, SNDRCVTimeout); end; Continue; end; if leftstr(res_str, 11) = 'set_alr_cnt' then begin max_alr_cnt := StrToInt(rightstr(res_str, length(res_str) - 11)); setlength(trarrAlarmTemplates, max_alr_cnt); curr_alr_cnt := 0; curr_alr_cnt_finished := 0; if max_alr_cnt = 0 then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetAlarmTemplates); trSetAlarmTemplates; end; Continue; end; if leftstr(res_str, 12) = 'set_alr_prm1' then begin curr_alr_cnt := curr_alr_cnt + 1; trarrAlarmTemplates[curr_alr_cnt - 1].alarm_template_name := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_alr_prm2' then begin trarrAlarmTemplates[curr_alr_cnt - 1].alarm_template_str := rightstr(res_str, length(res_str) - 12); Continue; end; if leftstr(res_str, 12) = 'set_alr_prm3' then begin trarrAlarmTemplates[curr_alr_cnt - 1].alarm_template_params := rightstr(res_str, length(res_str) - 12); curr_alr_cnt_finished := curr_alr_cnt_finished + 1; if curr_alr_cnt_finished = max_alr_cnt then begin uNetwork.SendStringViaSocket(S, 'res_suc', SNDRCVTimeout); // reload execution //Synchronize(@trSetAlarmTemplates); trSetAlarmTemplates; end; Continue; end; // ======================================== // report generate ======================== if leftstr(res_str, 7) = 'get_rep' then begin tmp_str1 := rightstr(res_str, length(res_str) - 7); tmp_dt1 := strtofloat(GetFieldFromString(tmp_str1, ParamLimiter, 1)); tmp_dt2 := strtofloat(GetFieldFromString(tmp_str1, ParamLimiter, 2)); tmp_str2 := GetFieldFromString(tmp_str1, ParamLimiter, 3); tmp_str3 := uReportBuilder.BuildReport(tmp_dt1, tmp_dt2, tmp_str2, True, S); if FileExists(tmp_str3) then begin uNetwork.SendStringViaSocket(S, 'rep_res_fname' + ExtractFileName(tmp_str3), SNDRCVTimeout); assignFile(tf, tmp_str3); try reset(tf); while not EOF(tf) do begin readln(tf, tmp_str2); uNetwork.SendStringViaSocket(S, 'rep_res_str' + tmp_str2, SNDRCVTimeout); end; closefile(tf); except uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; try DeleteFile(tmp_str3); except end; uNetwork.SendStringViaSocket(S, 'rep_fin', SNDRCVTimeout); end else begin uNetwork.SendStringViaSocket(S, 'res_err', SNDRCVTimeout); end; end; // ======================================== end; s.CloseSocket; end; procedure TThreadMCConnection.trGetSettings; begin cs1.Enter; trMCLogonPwd := uMain.sMCLogonPwd; cs1.Leave; end; procedure TThreadMCConnection.trGetPrm; begin cs1.Enter; trsMCLogonPwd := uMain.sMCLogonPwd; trsAgentInformationLogonPwd := uMain.sAgentInformationLogonPwd; trsManagerConsoleListeningPort := umain.sManagerConsoleListeningPort; trsAgentCollectorListeningPort := umain.sAgentCollectorListeningPort; trsAgentInformationListeningPort := umain.sAgentInformationListeningPort; trsReservServiceListeningPort := umain.sReservServiceListeningPort; trsSudoPwd := umain.sSudoPwd; cs1.Leave; end; procedure TThreadMCConnection.trSetPrm; begin cs1.Enter; if uMain.sManagerConsoleListeningPort <> trsManagerConsoleListeningPort then begin uMain.sManagerConsoleListeningPort := trsManagerConsoleListeningPort; // restart ManagerConsoleListening thread uMain.StopManagerConsoleListener; uMain.StartManagerConsoleListener; end; if uMain.sAgentCollectorListeningPort <> trsAgentCollectorListeningPort then begin uMain.sAgentCollectorListeningPort := trsAgentCollectorListeningPort; // restart AgentCollectorListening thread end; if uMain.sAgentInformationListeningPort <> trsAgentInformationListeningPort then begin uMain.sAgentInformationListeningPort := trsAgentInformationListeningPort; // restart AgentInformationListening thread end; if uMain.sReservServiceListeningPort <> trsReservServiceListeningPort then begin uMain.sReservServiceListeningPort := trsReservServiceListeningPort; // restart ReservServiceListening thread end; if uMain.sMCLogonPwd <> trsMCLogonPwd then begin uMain.sMCLogonPwd := trsMCLogonPwd; end; if uMain.sAgentInformationLogonPwd <> trsAgentInformationLogonPwd then begin uMain.sAgentInformationLogonPwd := trsAgentInformationLogonPwd; end; if uMain.sSudoPwd <> trsSudoPwd then begin uMain.sSudoPwd := trsSudoPwd; end; cs1.Leave; uMain.SaveSettings; end; //procedure TThreadMCConnection.toLog; //begin // uLog.WriteLogMsg(trLogMsg); //end; procedure TThreadMCConnection.trWriteLog(msg_str: string); begin //trLogMsg:=msg_str; //Synchronize(@toLog); uLog.WriteLogMsg(msg_str); end; end.
program vga; (* Test program. *) uses andante, anBitmap, anVga; (* Helper to show error messages. *) procedure ShowError (aMessage: String); begin WriteLn ('Error [', anError, ']: ', aMessage); WriteLn end; begin WriteLn ('Andante ', anVersionString); WriteLn; if not anInstall then begin ShowError ('Can''t initialize Andante!'); Halt end; if not anInstallKeyboard then begin ShowError ('Keyboard out.'); Halt end; if not anSetGraphicsMode (anGfx13) then begin ShowError ('Can''t initialize VGA.'); Halt end; Randomize; repeat anDrawPixel (anScreen, Random (320), Random (200), Random (256)) until anKeyState[anKeyEscape] end.
unit UDevolucionEstado; interface uses Windows, SysUtils, StdCtrls, StrUtils, Controls, Classes, Graphics, Forms, ComCtrls, ExtCtrls, Buttons, IdIPWatch, DBCtrls, Grids, DBGrids, RxCtrls, DB, UDMConexion, UProcesoDevolucionEsta, UGlobales; type TFrmDevolucionEstado = class(TForm) stbBarraEstado: TStatusBar; PnlTitulo: TPanel; GrpPie: TGroupBox; spbSalir: TSpeedButton; RpnCriteriosBusqueda: TRxPanel; RpnCaptura: TRxPanel; GrpSeleccionCarpeta: TGroupBox; GrpSeleccionEstado: TGroupBox; dblEstadoDevolver: TDBLookupComboBox; EdtCodigoCaja: TEdit; LblCodigoCaja: TLabel; LblEme: TLabel; spbConsultarCarpeta: TSpeedButton; PnlCriteriosAportes: TPanel; stgDatosCarpeta: TStringGrid; LblDatosCarpeta: TLabel; LblEstadoDevolver: TLabel; GrpCriteriosAdicionales: TGroupBox; bbtEfectuarDevolucion: TBitBtn; bbtOtraCaja: TBitBtn; chkEliminaCarpeta: TCheckBox; Lbl1: TLabel; LblMensajeError: TLabel; PnlListaCarpetas: TPanel; LblListaCarpetas: TLabel; LblAyudaCarpetas: TLabel; LblCantidadCarpetas: TLabel; dbgListaCarpetas: TDBGrid; PnlCaja: TPanel; PnlEstadoProceso: TPanel; LblDevolverCarpeta: TLabel; PnlTituloEstado: TPanel; stgEstadoProceso: TStringGrid; RpnMensajeProceso: TRxPanel; bbtOtraCarpeta: TBitBtn; procedure FormCreate(Sender: TObject); procedure EdtCodigoCajaChange(Sender: TObject); procedure EdtCodigoCajaKeyPress(Sender: TObject; var Key: Char); procedure spbSalirClick(Sender: TObject); procedure spbConsultarCarpetaClick(Sender: TObject); procedure stgDatosCarpetaDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure dbgListaCarpetasDblClick(Sender: TObject); procedure bbtOtraCajaClick(Sender: TObject); {DECLARACIÓN DEL EVENTO DataChange DEL DATASOURCE QUE SE ENCUENTRA EN EL DbGrid} procedure dbgListaCarpetasDataSourceDataChange(Sender: TObject; Field: TField); procedure dblEstadoDevolverEnter(Sender: TObject); procedure dblEstadoDevolverCloseUp(Sender: TObject); procedure bbtEfectuarDevolucionClick(Sender: TObject); procedure stgEstadoProcesoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure bbtOtraCarpetaClick(Sender: TObject); private { Private declarations } public { Public declarations } DireccIP : String; procedure ConfigurarAmbiente; procedure LimpiarControles; procedure LimpiarDatosCarpeta; procedure LimpiarEstadoProceso; end; var FrmDevolucionEstado : TFrmDevolucionEstado; NombModu : string; ProcDevo : TProcesoDevolucionEsta; VersModu : string; implementation {$R *.dfm} {$REGION 'EVENTOS' } procedure TFrmDevolucionEstado.bbtEfectuarDevolucionClick(Sender: TObject); begin ProcDevo.DatosCarpeta.IdFlujoNuevo := dblEstadoDevolver.ListSource.DataSet.FieldByName('idflujo').Value; ProcDevo.DatosCarpeta.DescTareFlujNuev:= dblEstadoDevolver.ListSource.DataSet.FieldByName('descripciontarea').Value; if Application.MessageBox( PChar('Está seguro(a) de devolver la Carpeta [' + ProcDevo.DatosCarpeta.CodigoCarpeta + '] desde el Estado [' + ProcDevo.DatosCarpeta.DescTareCarpeta + '] hasta el Estado [' + ProcDevo.DatosCarpeta.DescTareFlujNuev + '] ?'), 'Confirmación Devolución', MB_YESNO OR MB_ICONQUESTION) = IDYES then begin try GrpSeleccionCarpeta.Enabled := False; GrpSeleccionEstado.Enabled := False; bbtOtraCaja.Enabled := False; spbSalir.Enabled := False; bbtEfectuarDevolucion.Visible := False; RpnMensajeProceso.Caption := 'DEVOLVIENDO CARPETA ....'; RpnMensajeProceso.Font.Color := clMaroon; RpnMensajeProceso.Visible := True; ProcDevo.DevolverEstadoCarpeta(chkEliminaCarpeta.checked); RpnMensajeProceso.Caption := 'DEVOLUCIÓN FINALIZADA'; RpnMensajeProceso.Font.Color := clBlue; Application.ProcessMessages; bbtOtraCaja.Enabled := true; bbtOtraCarpeta.Visible := true; spbSalir.Enabled := True; except on E:exception do begin Application.MessageBox(PChar(E.Message),'Devolución de Estado',MB_OK OR MB_ICONERROR); bbtOtraCaja.OnClick(Sender); end; end; end; end; procedure TFrmDevolucionEstado.bbtOtraCajaClick(Sender: TObject); begin LimpiarControles; end; procedure TFrmDevolucionEstado.bbtOtraCarpetaClick(Sender: TObject); var PosiActu : TBookmark; begin LimpiarEstadoProceso; LimpiarDatosCarpeta; PosiActu:= dbgListaCarpetas.DataSource.DataSet.GetBookmark; spbConsultarCarpetaClick(sender); if not dbgListaCarpetas.DataSource.DataSet.BookmarkValid(PosiActu) then PosiActu[0]:= dbgListaCarpetas.DataSource.DataSet.RecordCount; dbgListaCarpetas.DataSource.DataSet.GotoBookmark(PosiActu); dbgListaCarpetas.SetFocus; end; {DEFINICIÓN DEL EVENTO DataChange DEL DATASOURCE QUE SE ENCUENTRA EN EL DbGrid} procedure TFrmDevolucionEstado.dbgListaCarpetasDataSourceDataChange(Sender: TObject; Field: TField); begin LimpiarDatosCarpeta; end; procedure TFrmDevolucionEstado.dbgListaCarpetasDblClick(Sender: TObject); begin with dbgListaCarpetas.DataSource.DataSet do ProcDevo.ObtenerDatosCarpeta(FieldByName('idcarpeta').value, FieldByName('codigocarpeta').asstring ); with ProcDevo.DatosCarpeta do begin with stgDatosCarpeta do begin Cells[1,0] := 'M' + CodigoCaja; CodiCompCarpeta := 'M' + CodigoCarpeta + ' - ' + ifthen(ClaseCarpeta = 'C', 'Creación', 'Inserción - ' + IntToStr(SecuenciaClase)); CodiResuCarpeta := 'M' + CodigoCarpeta + ifthen(ClaseCarpeta = 'C', '','-I-' + IntToStr(SecuenciaClase)); Cells[1,1] := CodiCompCarpeta; Cells[1,2] := DescSeriDocumental; Cells[1,3] := DescTareCarpeta; Cells[1,4] := formatfloat('#,##0',CantidadAletas); Cells[1,5] := formatfloat('#,##0',CantidadFolios); Cells[1,6] := formatfloat('#,##0',CantRegiPersonas); Cells[1,7] := formatfloat('#,##0',CantFoliFirmados); ProcDevo.ObtenerEstadosDevolver(IdFLujo); dblEstadoDevolver.ListSource := ProcDevo.EstadosDevolver; dblEstadoDevolver.ListField := 'descripciontarea'; dblEstadoDevolver.KeyField := 'idflujo'; dblEstadoDevolver.KeyValue := 0; GrpSeleccionEstado.Enabled := True; dblEstadoDevolver.SetFocus; end; end; end; procedure TFrmDevolucionEstado.dblEstadoDevolverCloseUp(Sender: TObject); begin bbtEfectuarDevolucion.Enabled := True; if dblEstadoDevolver.ListSource.DataSet.FieldByName('descripciontarea').Value = 'RECEPCION' then begin if (dblEstadoDevolver.ListSource.DataSet.RecordCount = 1) and (ProcDevo.DatosCarpeta.CantidadAletas = 0 )then begin chkEliminaCarpeta.Enabled:= false; chkEliminaCarpeta.Checked:= true; end else chkEliminaCarpeta.Enabled:= True; end else begin chkEliminaCarpeta.Enabled:= false; chkEliminaCarpeta.Checked:= false; end; end; procedure TFrmDevolucionEstado.dblEstadoDevolverEnter(Sender: TObject); begin dblEstadoDevolver.DropDown; end; procedure TFrmDevolucionEstado.EdtCodigoCajaChange(Sender: TObject); begin LblMensajeError.Visible:=False; if Length(EdtCodigoCaja.Text) = 4 then spbConsultarCarpeta.Enabled:= True else spbConsultarCarpeta.Enabled:= False; if EdtCodigoCaja.Text = '' then bbtOtraCaja.Enabled:=False else bbtOtraCaja.Enabled:=True; end; procedure TFrmDevolucionEstado.EdtCodigoCajaKeyPress(Sender: TObject; var Key: Char); begin if (Key <> #8) and ((Key < '0') or (Key > '9')) then Key := #0; end; procedure TfrmDevolucionEstado.FormCreate(Sender: TObject); begin try ConfigurarAmbiente; except on e:Exception do begin Application.MessageBox(PChar(e.Message),'Devolución de Estado',MB_OK OR MB_ICONERROR); ExitProcess(0); end; end; end; procedure TFrmDevolucionEstado.spbConsultarCarpetaClick(Sender: TObject); begin spbConsultarCarpeta.Enabled:= False; ProcDevo.ObtenerCarpetas(EdtCodigoCaja.Text); with ProcDevo.Carpetas.DataSet do begin if (FieldByName('idcaja').IsNull) or (FieldByName('idcarpeta').IsNull) then begin if FieldByName('idcaja').isnull then LblMensajeError.Caption := 'ESTE CODIGO DE CAJA NO EXISTE' else LblMensajeError.Caption := 'ESTA CAJA NO POSEE CARPETAS ASOCIADAS'; LblMensajeError.Visible:= True; Application.ProcessMessages; Sleep(2000); LblMensajeError.Visible:= False; end else begin dbgListaCarpetas.DataSource := ProcDevo.Carpetas; LblCantidadCarpetas.Caption := 'CANTIDAD DE CARPETAS:' + #13#10 + '[' + IntToStr(ProcDevo.Carpetas.DataSet.RecordCount) + ']'; LblCantidadCarpetas.Visible := True; dbgListaCarpetas.Enabled := True; PnlCaja.Enabled:= False; {LAS 2 SIGUIENTES LINEAS SON PARA FORZAR A QUE SE MUESTRE LA BARRA DE DESPLAZAMIENTO YA QUE EL OBJETO DGBGRID TIENE UN BUG. HAY QUE HACER QUE SE ACTIVE EL METODO RESIZE} dbgListaCarpetas.Height:= dbgListaCarpetas.Height + 1; dbgListaCarpetas.Height:= dbgListaCarpetas.Height - 1; {ASIGNACION DEL EVENTO DataChange DEL DataSource ASIGNADO AL DBGRID} dbgListaCarpetas.DataSource.OnDataChange:= dbgListaCarpetasDataSourceDataChange; end; end; end; procedure TFrmDevolucionEstado.spbSalirClick(Sender: TObject); begin Self.Close; end; procedure TFrmDevolucionEstado.stgDatosCarpetaDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin with (Sender as TStringGrid) do begin if ACol = 0 then begin Canvas.Font.Color:= clBlack; Canvas.Font.Style:= []; Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2,Cells[ACol,ARow]); end else begin Canvas.Font.Color:= clWhite; Canvas.Font.Name := 'Arial'; Canvas.Font.size := 12; Canvas.Font.Style:= [fsbold]; Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2,Cells[ACol,ARow]); end end; end; procedure TFrmDevolucionEstado.stgEstadoProcesoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin with (Sender as TStringGrid) do begin if ACol = 0 then begin Canvas.Brush.Color := clWhite; Rect.Left:= 0; Canvas.Font.Color:= clBlack; Canvas.Font.Style:= []; Canvas.TextRect(Rect, Rect.Left+5, Rect.Top+2,Cells[ACol,ARow]); end else begin Canvas.Font.Color:= clBlack; Canvas.Font.Name := 'Arial'; Canvas.Font.size := 12; Canvas.Font.Style:= [fsbold]; Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2,Cells[ACol,ARow]); end; end; end; {$ENDREGION} {$REGION 'METODOS PROPIOS'} procedure TfrmDevolucionEstado.ConfigurarAmbiente; begin {SE CREAN OBJETOS DE LA CAPA LOGICA } ProcDevo := TProcesoDevolucionEsta.Create; NombModu:= 'MODULODEVOLUCIONESTADO'; VersModu:= '20170706.M01'; ProcDevo.VerificarVersion(NombModu, VersModu, VeriRuta); with TIdIPWatch.Create() do begin DireccIP := LocalIP; Free; end; FrmDevolucionEstado.Caption:= 'Devolución de Estado para Carpetas - [ ' + VersModu + ' ]'; stbBarraEstado.Panels[0].Text :='Usuario: ' + ParamStr(1) + ' - ' + ParamStr(2) ; stbBarraEstado.Panels[1].Text:='IP: ' + DireccIP; if DMConexion.Ambiente <> 'PRODUCCIÓN' then begin if DMConexion.Ambiente = 'DESARROLLO' then PnlTitulo.Font.Color := clPurple else if DMConexion.Ambiente = 'PRUEBAS' then PnlTitulo.Font.Color := clMaroon; PnlTitulo.Caption := PnlTitulo.Caption + ' [' + DMConexion.Ambiente + ']'; end; with stgDatosCarpeta do begin Cells[0,0]:='Código de la Caja'; Cells[0,1]:='Código de la Carpeta'; Cells[0,2]:='Serie Documental'; Cells[0,3]:='Estado Actual Carpeta'; Cells[0,4]:='Cantidad de Aletas'; Cells[0,5]:='Cantidad de Folios'; Cells[0,6]:='Cantidad Registros Personas'; Cells[0,7]:='Cantidad Folios Firmados'; ColWidths[0]:= 200; ColWidths[1]:= 300; end; with stgEstadoProceso do begin Cells[0,0]:='* Aletas Eliminadas'; Cells[0,1]:='* Folios Actualizados'; Cells[0,2]:='* Folios Eliminados'; Cells[0,3]:='* Registros de Identificación Eliminados'; Cells[0,4]:='* Registros de Control Folio Eliminados'; Cells[0,5]:='* Registros de Imagen Eliminados'; Cells[0,6]:='* Registros de Novedades Folio Eliminados'; Cells[0,7]:='* Registros de Planillas Eliminados'; Cells[0,8]:='* Registros de Observaciones Eliminados'; Cells[0,9]:='* Registros de Firma Eliminados'; ColWidths[0]:= Trunc(stgEstadoProceso.Width / 2); ColWidths[1]:= stgEstadoProceso.Width - ColWidths[0]; end; end; procedure TFrmDevolucionEstado.LimpiarControles; begin LimpiarEstadoProceso; LimpiarDatosCarpeta; dbgListaCarpetas.DataSource.DataSet.First; dbgListaCarpetas.DataSource:= nil; {LA SIGUIENTE SENTENCIA OCULTA LA BARRA DE DESPLAZAMIENTO DEL GRID PORQUE CUANDO SE LIMPIA NO QUITA DICHA BARRA} ShowScrollBar(dbgListaCarpetas.Handle, SB_VERT, FALSE); dbgListaCarpetas.Enabled := false; EdtCodigoCaja.Clear; LblCantidadCarpetas.Caption:= 'CANTIDAD CARPETAS'; PnlCaja.Enabled:= true; EdtCodigoCaja.SetFocus; end; procedure TFrmDevolucionEstado.LimpiarDatosCarpeta; Var I: Integer; begin for I := 0 to stgDatosCarpeta.RowCount - 1 do stgDatosCarpeta.Cells[1,I] := ''; dblEstadoDevolver.ListSource := nil; dblEstadoDevolver.KeyValue := -1; chkEliminaCarpeta.Checked := False; GrpSeleccionEstado.Enabled := False; bbtEfectuarDevolucion.Enabled :=False; ProcDevo.VerificarVersion(NombModu, VersModu, VeriRuta); end; procedure TFrmDevolucionEstado.LimpiarEstadoProceso; Var I: Integer; begin for I := 0 to stgEstadoProceso.RowCount - 1 do stgEstadoProceso.Cells[1,I] := ''; LblDevolverCarpeta.Caption := ''; stgEstadoProceso.Visible := False; bbtEfectuarDevolucion.Visible := true; RpnMensajeProceso.Visible := False; GrpSeleccionCarpeta.Enabled := True; bbtOtraCarpeta.Visible := False; end; {$ENDREGION} end.
unit Editor; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, checklst, ExtCtrls, ShellApi, RichEdit; type TOptions = record Str : TColor; Keyword : TColor; BoolValue : TColor; Rem : TColor; Number : TColor; Error : TColor; BGColor : TColor; NormalText : TColor; CurKeyWords : Byte; ListKeyWord : array[0..100] of String[100]; end; TfrmEditor = class(TForm) Status: TStatusBar; rtbEdit: TRichEdit; rtbTemp: TRichEdit; procedure rtbEditKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rtbEditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rtbEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rtbEditChange(Sender: TObject); procedure FormShow(Sender: TObject); private public EditorOptions : TOptions; Procedure Must_Die_Editor; end; procedure ProcessText; procedure SelectWord(sWord : string; CurPos : LongInt); function CaseWordType(sWord : string) : Integer; function IsKeyword(sWord : string) : Boolean; function GetNextWord(sStr : string; var CurPos : Longint) : string; procedure SkipSpace(sStr : string; var CurPos : LongInt); function BreakSymbol(cSymbol : Char) : Boolean; var frmEditor: TfrmEditor; Struct : String; CharPos : TPoint; fProcessText : Boolean; implementation uses Options, mdl_dsg, frmUser; {$R *.DFM} { ------------------------------------------------------------------- } { Нормальный ли символ ? } function BreakSymbol(cSymbol : Char) : Boolean; begin if cSymbol in [#9,' ',#13,#10] then BreakSymbol := True else BreakSymbol := False; end; { Пропускает пробелы } procedure SkipSpace(sStr : string; var CurPos : LongInt); begin if CurPos >= Length(sStr) then Exit; while BreakSymbol(sStr[CurPos]) do begin If (CurPos >= Length(sStr)) then Exit; Inc(CurPos); end; {while} end; { Возвращает следующее слово после CurPos } function GetNextWord(sStr : string; var CurPos : Longint) : string; var sTemp : string; begin SkipSpace(sStr, CurPos); if Length(sStr) > Length(Struct) then begin if Copy(sStr, CurPos, Length(Struct)) = Struct then begin CurPos := CurPos + Length(Struct); sTemp := Struct + sTemp; if CurPos > Length(sStr) then begin GetNextWord := sTemp; Exit; end; end; end; while not BreakSymbol(sStr[CurPos]) do begin sTemp := sTemp + sStr[CurPos]; Inc(CurPos); if CurPos > Length(sStr) then begin GetNextWord := sTemp; Break; end; end; {while} GetNextWord := sTemp; end; { Ключевое ли это слово ? } function IsKeyword(sWord : string) : Boolean; var i : Integer; begin IsKeyword := False; sWord := AnsiLowerCase(sWord); for i := 0 To frmEditor.EditorOptions.CurKeyWords do if frmEditor.EditorOptions.ListKeyWord[i] = sWord then begin IsKeyword := True; Exit; end; {if} End; { Возвращает тип слова } function CaseWordType(sWord : string) : Integer; begin case sWord[1] of #39 : Result := 0; '0'..'9' : Result := 1; '.' : Result := 2; else if IsKeyword(sWord) then Result := 3 else Result := 4; end; {case} end; { Выделяет слово в rtbTemp } procedure SelectWord(sWord : string; CurPos : LongInt); begin frmEditor.rtbTemp.SelStart := CurPos - Length(sWord) - 1; frmEditor.rtbTemp.SelLength := Length(sWord); // 1 - Цифра // 2 - Логическая константа // 3 - Ключевое слово // 4 - Идентификатор case CaseWordType(sWord) of 0 : frmEditor.rtbTemp.SelAttributes.Color := frmEditor.EditorOptions.Str; 1 : frmEditor.rtbTemp.SelAttributes.Color := frmEditor.EditorOptions.Number; 2 : frmEditor.rtbTemp.SelAttributes.Color := frmEditor.EditorOptions.BoolValue; 3 : frmEditor.rtbTemp.SelAttributes.Color := frmEditor.EditorOptions.KeyWord; 4 : frmEditor.rtbTemp.SelAttributes.Color := frmEditor.EditorOptions.NormalText; end; end; { Разбор и обработка текста } procedure ProcessText; var CurPos, TextCur : Longint; sWord : string; sText : string; begin If Not fProcessText then Exit; frmEditor.rtbTemp.Text := frmEditor.rtbEdit.Text; sText := frmEditor.rtbEdit.Text; TextCur := frmEditor.rtbEdit.SelStart; CurPos := 1; { Теперь все выделения делаем в rtbTemp } while CurPos < Length(sText) do begin sWord := GetNextWord(sText, CurPos); If sWord <> '' Then SelectWord(sWord, CurPos); end; frmEditor.rtbTemp.Lines.SaveToFile('editcode.$$$'); frmEditor.rtbEdit.Lines.LoadFromFile('editcode.$$$'); frmEditor.rtbEdit.SelStart := TextCur; end; { ------------------------------------------------------------------ } { Начальная инициализация редактора } procedure Init; var F : File of TOptions; begin fProcessText := True; AssignFile(F,'ini/editor.ini'); Reset(F); Read(F,frmEditor.EditorOptions); CloseFile(f); frmEditor.rtbEdit.Color:=frmEditor.EditorOptions.BGColor; Struct := #39; end; { ------------------------------------------------------------------ } procedure TfrmEditor.rtbEditKeyPress(Sender: TObject; var Key: Char); begin // Если нажали Enter if Key = #13 then ProcessText; end; procedure TfrmEditor.FormCreate(Sender: TObject); begin { Инициализируем редактор } Init; rtbEdit.Lines.Add('Проц Старт()'); rtbEdit.Lines.Add(' '); rtbEdit.Lines.Add('Кон проц '); rtbEdit.SelStart := 16; ProcessText; end; Procedure tfrmEditor.Must_Die_Editor; var F : File of TOptions; begin AssignFile(F,'ini\editor.ini'); ReWrite(F); Write(F,frmEditor.EditorOptions); CloseFile(F); //DeleteFile('editcode.$$$'); end; procedure TfrmEditor.FormClose(Sender: TObject; var Action: TCloseAction); var F : File of TOptions; begin AssignFile(F,'ini\editor.ini'); ReWrite(F); Write(F,frmEditor.EditorOptions); CloseFile(F); //DeleteFile('editcode.$$$'); end; procedure TfrmEditor.rtbEditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If (ssShift in Shift) And (Key = VK_INSERT) then ProcessText; end; procedure TfrmEditor.rtbEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin rtbEdit.SelAttributes.Color:=frmEditor.EditorOptions.NormalText; end; procedure TfrmEditor.rtbEditChange(Sender: TObject); begin CharPos.Y := SendMessage(rtbEdit.Handle, EM_EXLINEFROMCHAR, 0, rtbEdit.SelStart); CharPos.X := (rtbEdit.SelStart - SendMessage(rtbEdit.Handle, EM_LINEINDEX, CharPos.Y, 0)); Inc(CharPos.Y); Inc(CharPos.X); Status.Panels[0].Text := Format('Line: %3d Col: %3d', [CharPos.Y, CharPos.X]); end; procedure TfrmEditor.FormShow(Sender: TObject); begin ProcessText; end; end.
{ 单元名称: uJxdDataStruct 单元作者: 江晓德(Terry) 邮 箱: jxd524@163.com 说 明: 数据结构操作 开始时间: 2011-04-18 修改时间: 2011-04-18 (最后修改) 注意事项: 非线程安全 http://blog.csdn.net/hqd_acm/archive/2010/09/23/5901955.aspx HashArray 中ID是不可重复的。 散列函数方法:除留余数法;f(k) = k mod m 其中 m = 散列值, n: 散列列表 为让散列比较均衡,减少冲突,m 的取值比较重要, m 的取值按以下算法进行 m要求: 素数(只能被1和本身整除); 常用的字符串Hash函数还有ELFHash,APHash等等,都是十分简单有效的方法。这些函数使用位运算使得每一个字符都对最后的函数值产生影响。 另外还有以MD5和SHA1为代表的杂凑函数,这些函数几乎不可能找到碰撞。 常用字符串哈希函数有BKDRHash,APHash,DJBHash,JSHash,RSHash,SDBMHash,PJWHash,ELFHash等等。对于以上几种哈希函数,我对其进行了一个小小的评测。 Hash函数 数据1 数据2 数据3 数据4 数据1得分 数据2得分 数据3得分 数据4得分 平均分 BKDRHash 2 0 4774 481 96.55 100 90.95 82.05 92.64 APHash 2 3 4754 493 96.55 88.46 100 51.28 86.28 DJBHash 2 2 4975 474 96.55 92.31 0 100 83.43 JSHash 1 4 4761 506 100 84.62 96.83 17.95 81.94 RSHash 1 0 4861 505 100 100 51.58 20.51 75.96 SDBMHash 3 2 4849 504 93.1 92.31 57.01 23.08 72.41 PJWHash 30 26 4878 513 0 0 43.89 0 21.95 ELFHash 30 26 4878 513 0 0 43.89 0 21.95 其中 数据1为 100000个字母和数字组成的随机串哈希冲突个数。 数据2为100000个有意义的英文句子哈希冲突个数。 数据3为数据1的哈希值与1000003(大素数)求模后存储到线性表中冲突的个数。 数据4为数据1的哈希值与10000019(更大素数)求模后存储到线性表中冲突的个数。 经过比较,得出以上平均得分。平均数为平方平均数。可以发现, BKDRHash无论是在实际效果还是编码实现中,效果都是最突出的。 APHash也是较为优秀的算法。 DJBHash,JSHash,RSHash与SDBMHash各有千秋。PJWHash与ELFHash效果最差,但得分相似,其算法本质是相似的。 在信息修竞赛中,要本着易于编码调试的原则,个人认为BKDRHash是最适合记忆和使用的 // BKDR Hash Function unsigned int BKDRHash(char*str) [ unsigned int seed=131 ;// 31 131 1313 13131 131313 etc.. unsigned int hash=0 ; while(*str) [ hash=hash*seed+(*str++); [ return(hash % M); [ // RS Hash Function function RSHash(S: string): Cardinal; var a, b: Cardinal; I: Integer; begin Result := 0; a := 63689; b := 378551; for I := 1 to Length(S) do begin Result := Result * a + Ord(S[I]); a := a * b; end; Result := Result and $7FFFFFFF; end; // JS Hash Function function JSHash(S: string): Cardinal; var I: Integer; begin Result := 1315423911; for I := 1 to Length(S) do begin Result := ((Result shl 5) + Ord(S[I]) + (Result shr 2)) xor Result; end; Result := Result and $7FFFFFFF; end; // P.J.Weinberger Hash Function function PJWHash(S: string): Cardinal; var OneEighth, ThreeQuarters, BitsInUnignedInt, HighBits, test: Cardinal; I: Integer; begin Result := 0; test := 0; BitsInUnignedInt := SizeOf(Cardinal) * 8; ThreeQuarters := BitsInUnignedInt * 3 div 4; OneEighth := BitsInUnignedInt div 8; HighBits := $FFFFFFFF shl (BitsInUnignedInt - OneEighth); for I := 1 to Length(S) do begin Result := (Result shl OneEighth) + Ord(S[I]); test := Result and HighBits; if test <> 0 then Result := ((Result xor (test shr ThreeQuarters)) and not HighBits); end; Result := Result and $7FFFFFFF; end; // ELF Hash Function function ELFHash(S: string): Cardinal; var X: Cardinal; I: Integer; begin Result := 0; X := 0; for I := 1 to Length(S) do begin Result := (Result shl 4) + Ord(S[I]); X := Result and $F0000000; if X <> 0 then begin Result := Result xor (X shr 24); Result := Result and not X; end; end; Result := Result and $7FFFFFFF; end; // BKDR Hash Function function BKDRHash(S: string): Cardinal; var seed: Cardinal; I: Integer; begin Result := 0; seed := 131; // 31 131 1313 13131 131313 etc.. for I := 1 to Length(S) do begin Result := Result * seed + Ord(S[I]); end; Result := Result and $7FFFFFFF; end; // SDBM Hash Function function SDBMHash(S: string): Cardinal; var I: Integer; begin Result := 0; for I := 1 to Length(S) do begin Result := Ord(S[I]) + (Result shl 6) + (Result shl 16) - Result; end; Result := Result and $7FFFFFFF; end; // DJB Hash Function function DJBHash(S: string): Cardinal; var I: Integer; begin Result := 5381; for I := 1 to Length(S) do begin Result := Result + (Result shl 5) + Ord(S[I]); end; Result := Result and $7FFFFFFF; end; // AP Hash Function function APHash(S: string): Cardinal; var I: Integer; begin Result := 0; for I := 1 to Length(S) do begin if (i and 1) <> 0 then Result := Result xor ((Result shl 7) xor Ord(S[I]) xor (Result shr 3)) else Result := Result xor (not (Result shl 11) xor Ord(S[I]) xor (Result shr 5)); end; Result := Result and $7FFFFFFF; end; function THashTable.HashOf(const Key: string): Cardinal; var I: Integer; begin Result := 0; for I := 1 to Length(Key) do Result := ((Result shl 2) or (Result shr (SizeOf(Result) * 8 - 2))) xor Ord(Key[I]); end; } unit uHashFun; interface function HashFun_BKDR(const ApKey: PByte; const ALen: Integer): Cardinal; function HashFun_AP(const ApKey: PByte; const ALen: Integer): Cardinal; function HashFun_DJB(const ApKey: PByte; const ALen: Integer): Cardinal; var HashSeed: Cardinal; implementation function HashFun_BKDR(const ApKey: PByte; const ALen: Integer): Cardinal; var i: Integer; begin Result := 0; for i := 0 to ALen - 1 do Result := Result * HashSeed + Ord(PByte(Integer(ApKey) + i)^); end; function HashFun_AP(const ApKey: PByte; const ALen: Integer): Cardinal; var i: Integer; begin Result := 0; for i := 1 to ALen - 1 do begin if (i and 1) <> 0 then Result := Result xor ((Result shl 7) xor Ord(PByte(Integer(ApKey) + i)^) xor (Result shr 3)) else Result := Result xor (not (Result shl 11) xor Ord(PByte(Integer(ApKey) + i)^) xor (Result shr 5)); end; end; function HashFun_DJB(const ApKey: PByte; const ALen: Integer): Cardinal; var i: Integer; begin Result := 5381; for i := 1 to ALen - 1 do Result := Result + (Result shl 5) + Ord(PByte(Integer(ApKey) + i)^); end; initialization HashSeed := 1313; end.
// AVIRecorder {: Component to make it easy to record GLScene frames into an AVI file<p> <b>History : </b><font size=-1><ul> <li<02/03/01 - EG - Added TAVIImageRetrievalMode <li>24/02/01 - Creation and initial code by Nelson Chu </ul></font> } unit AVIRecorder; interface uses Windows, Classes, Controls, Forms, Extctrls, Graphics, vfw, GLScene; type TAVICompressor = (acDefault, acShowDialog); TAVISizeRestriction = ( srNoRestriction, srForceBlock2x2, srForceBlock4x4, srForceBlock8x8); TAVIRecorderState = (rsNone, rsRecording); TAVIImageRetrievalMode = (irmSnapShot, irmRenderToBitmap); // TAVIRecorder // {: Component to make it easy to record GLScene frames into an AVI file. } TAVIRecorder = class (TComponent) private { Private Declarations } AVIBitmap : TBitmap; AVIFrameIndex : integer; AVI_DPI : integer; pfile : PAVIFile; asi : TAVIStreamInfo; ps, ps_c : PAVIStream; // AVI stream and stream to be compressed BitmapInfo : PBitmapInfoHeader; BitmapBits : Pointer; BitmapSize : Dword; TempName : String; // so that we know the filename to delete case of user abort FAVIFilename : string; FFPS: byte; FWidth : integer; FHeight : integer; FSizeRestriction : TAVISizeRestriction; FImageRetrievalMode : TAVIImageRetrievalMode; RecorderState : TAVIRecorderState; procedure SetHeight(const val : integer); procedure SetWidth(const val : integer); procedure SetSizeRestriction(const val : TAVISizeRestriction); protected { Protected Declarations } // Now, TAVIRecorder is tailored for GLScene. Maybe we should make a generic // TAVIRecorder, and then sub-class it to use a GLSceneViewer FGLSceneViewer : TGLSceneViewer; // FCompressor determines if the user is to choose a compressor via a dialog box, or // just use a default compressor without showing a dialog box. FCompressor : TAVICompressor; // some video compressor assumes input dimensions to be multiple of 2, 4 or 8. // Restricted() is for rounding off the width and height. // Currently I can't find a simple way to know which compressor imposes // what resiction, so the SizeRestiction property is there for the user to set. // The source code of VirtualDub (http://www.geocities.com/virtualdub/index.html) // may give us some cues on this. // ( BTW, VirtualDub is an excellent freeware for editing your AVI. For // converting AVI into MPG, try AVI2MPG1 - http://www.mnsi.net/~jschlic1 ) function Restricted(s:integer):integer; public { Public Declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; function CreateAVIFile(DPI : integer = 0) : boolean; procedure AddAVIFrame; procedure CloseAVIFile(UserAbort : boolean = false); published { Published Declarations } property FPS : byte read FFPS write FFPS default 25; property GLSceneViewer : TGLSceneViewer read FGLSceneViewer write FGLSceneViewer; property Width : integer read FWidth write SetWidth; property Height : integer read FHeight write SetHeight; property Filename : String read FAVIFilename write FAVIFilename; property Compressor : TAVICompressor read FCompressor write FCompressor default acDefault; property SizeRestriction : TAVISizeRestriction read FSizeRestriction write SetSizeRestriction default srForceBlock8x8; property ImageRetrievalMode : TAVIImageRetrievalMode read FImageRetrievalMode write FImageRetrievalMode default irmRenderToBitmap; end; procedure Register; // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- implementation // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- uses SysUtils, Dialogs, Messages, GLGraphics; procedure Register; begin RegisterComponents('GLScene', [TAVIRecorder]); end; // DIB support rountines for AVI output procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var BI: TBitmapInfoHeader); var BM: Windows.TBitmap; begin GetObject(Bitmap, SizeOf(BM), @BM); with BI do begin biSize := SizeOf(BI); biWidth := BM.bmWidth; biHeight := BM.bmHeight; biPlanes := 1; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; biCompression := BI_RGB; biBitCount := 24; // force 24 bits. Most video compressors would deal with 24-bit frames only. biSizeImage := (((biWidth * biBitCount) + 31) div 32) * 4 * biHeight; end; end; procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: Integer; var ImageSize: DWORD); var BI: TBitmapInfoHeader; begin InitializeBitmapInfoHeader(Bitmap, BI); with BI do InfoHeaderSize:=SizeOf(TBitmapInfoHeader); ImageSize:=BI.biSizeImage; end; function InternalGetDIB(Bitmap: HBITMAP; var BitmapInfo; var Bits): Boolean; var Focus: HWND; DC: HDC; begin InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo)); Focus := GetFocus; DC := GetDC(Focus); try Result := GetDIBits(DC, Bitmap, 0, TBitmapInfoHeader(BitmapInfo).biHeight, @Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0; finally ReleaseDC(Focus, DC); end; end; // ------------------ // ------------------ TAVIRecorder ------------------ // ------------------ constructor TAVIRecorder.Create(AOwner : TComponent); begin inherited; FWidth:=320; // default values FHeight:=200; FFPS:=25; FCompressor:=acDefault; RecorderState:=rsNone; FSizeRestriction:=srForceBlock8x8; FImageRetrievalMode:=irmRenderToBitmap; end; destructor TAVIRecorder.Destroy; begin inherited; end; function TAVIRecorder.Restricted(s:integer):integer; begin case FSizeRestriction of srForceBlock2x2: result:=(s div 2) * 2; srForceBlock4x4: result:=(s div 4) * 4; srForceBlock8x8: result:=(s div 8) * 8; else result:=s; end; end; procedure TAVIRecorder.SetHeight(const val : integer); begin if RecorderState=rsRecording then exit; if val<>FHeight then if val>0 then FHeight:=Restricted(val); end; procedure TAVIRecorder.SetWidth(const val : integer); begin if RecorderState=rsRecording then exit; if val<>FWidth then if val>0 then FWidth:=Restricted(val); end; procedure TAVIRecorder.SetSizeRestriction(const val : TAVISizeRestriction); begin if val<>FSizeRestriction then begin FSizeRestriction:=val; FHeight:=Restricted(FHeight); FWidth:=Restricted(FWidth); end; end; procedure TAVIRecorder.AddAVIFrame; var bmp32 : TGLBitmap32; bmp : TBitmap; begin if RecorderState<>rsRecording then raise Exception.create('Cannot add frame to AVI. AVI file not created.'); Assert(FGLSceneViewer<>nil); case ImageRetrievalMode of irmSnapShot : begin bmp32:=GLSceneViewer.CreateSnapShot; bmp:=bmp32.Create32BitsBitmap; AVIBitmap.Canvas.Draw(0, 0, bmp); bmp.Free; bmp32.Free; end; irmRenderToBitmap : begin GLSceneViewer.RenderToBitmap(AVIBitmap, AVI_DPI); end; else Assert(False); end; with AVIBitmap do begin InternalGetDIB( Handle, BitmapInfo^, BitmapBits^); if AVIStreamWrite( ps_c, AVIFrameIndex, 1, BitmapBits, BitmapSize, AVIIF_KEYFRAME, nil, nil)<> AVIERR_OK then raise Exception.Create('Add Frame Error'); Inc(AVIFrameIndex); end; end; function TAVIRecorder.CreateAVIFile(DPI : integer = 0) : boolean; var SaveDialog: TSaveDialog; SaveAllowed: Boolean; gaAVIOptions : TAVICOMPRESSOPTIONS; galpAVIOptions : PAVICOMPRESSOPTIONS; BitmapInfoSize : Integer; AVIResult : Cardinal; ResultString : string; begin SaveDialog := nil; Assert(FGLSceneViewer<>nil); try TempName := FAVIFilename; SaveAllowed := True; if TempName = '' then // if user didn't supply a filename, then ask for it begin SaveDialog := TSaveDialog.Create(Application); with SaveDialog do begin Options := [ofHideReadOnly, ofNoReadOnlyReturn]; DefaultExt:='.avi'; Filter := 'AVI Files (*.avi)|*.avi'; SaveAllowed := Execute; end; end; if SaveAllowed then begin if TempName = '' then begin TempName := SaveDialog.FileName; if (FileExists(SaveDialog.FileName)) then SaveAllowed := MessageDlg(Format('Overwrite file %s?', [SaveDialog.FileName]), mtConfirmation, [mbYes, mbNo], 0) = mrYes; end; end; finally if SaveDialog<>nil then SaveDialog.Free; end; result:=SaveAllowed; if not SaveAllowed then exit; AVIFileInit; // init. the AVI lib. AVIBitmap:=TBitmap.Create; AVIFrameIndex:=0; RecorderState:=rsRecording; try AVIBitmap.PixelFormat := pf24Bit; AVIBitmap.Width := FWidth; AVIBitmap.Height := FHeight; // note: a filename with extension other then AVI give generate an error. if AVIFileOpen(pfile, PChar(TempName), OF_WRITE or OF_CREATE, nil)<>AVIERR_OK then raise Exception.Create('Cannot create AVI file. Disk full or file in use?'); with AVIBitmap do begin InternalGetDIBSizes( Handle, BitmapInfoSize, BitmapSize); BitmapInfo:=AllocMem(BitmapInfoSize); BitmapBits:=AllocMem(BitmapSize); InternalGetDIB(Handle, BitmapInfo^, BitmapBits^); end; FillChar(asi,sizeof(asi),0); with asi do begin fccType := streamtypeVIDEO; // Now prepare the stream fccHandler:= 0; dwScale := 1; // dwRate / dwScale = frames/second dwRate := FFPS; dwSuggestedBufferSize:=BitmapSize; rcFrame.Right := BitmapInfo^.biWidth; rcFrame.Bottom := BitmapInfo^.biHeight; end; if AVIFileCreateStream(pfile, ps, @asi)<>AVIERR_OK then raise Exception.Create('Cannot create AVI stream.'); with AVIBitmap do InternalGetDIB( Handle, BitmapInfo^, BitmapBits^); galpAVIOptions:=@gaAVIOptions; fillchar(gaAVIOptions, sizeof(gaAVIOptions), 0); if (FCompressor=acShowDialog) and // the following line will call a dialog box for the user to choose the compressor options AVISaveOptions( FGLSceneViewer.parent.Handle, ICMF_CHOOSE_KEYFRAME or ICMF_CHOOSE_DATARATE, 1, ps, galpAVIOptions ) then else with gaAVIOptions do // or, you may want to fill the compression options yourself begin fccType:=streamtypeVIDEO; fccHandler:=mmioFOURCC('M','S','V','C'); // User MS video 1 as default. // I guess it is installed on every Win95 or later. dwQuality:=7500; // compress quality 0-10,000 dwFlags:=0; // setting dwFlags to 0 would lead to some default settings end; AVIResult:=AVIMakeCompressedStream(ps_c, ps, galpAVIOptions, nil); if AVIResult <> AVIERR_OK then begin if AVIResult = AVIERR_NOCOMPRESSOR then ResultString:='No such compressor found' else ResultString:=''; raise Exception.Create('Cannot make compressed stream. ' + ResultString); end; if AVIStreamSetFormat(ps_c, 0, BitmapInfo, BitmapInfoSize) <> AVIERR_OK then raise Exception.Create('AVIStreamSetFormat Error'); // no error description found in MSDN. AVI_DPI:=DPI; except CloseAVIFile(true); end; end; procedure TAVIRecorder.CloseAVIFile(UserAbort:boolean=false); // if UserAbort, CloseAVIFile will also delete the unfinished file. begin if RecorderState<>rsRecording then raise Exception.create('Cannot close AVI file. AVI file not created.'); AVIBitmap.Free; FreeMem(BitmapInfo); FreeMem(BitmapBits); AVIStreamRelease(ps); AVIStreamRelease(ps_c); AVIFileRelease(pfile); AVIFileExit; // finalize the AVI lib. if UserAbort then deleteFile(TempName); RecorderState:=rsNone; end; end.
unit CRPartPlacementsReportFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CRPartPlacementsEditorFrame, ImgList, CommonFrame, CRPartPlacementEditorFrame, ComCtrls, ExtCtrls, StdCtrls, Mask, ToolEdit, BaseObjects; type TfrmPartPlacementsReport = class(TfrmPartPlacements) gbxSettings: TGroupBox; chbxAreaTotals: TCheckBox; chbxPlacementTotals: TCheckBox; chbxOverallTotal: TCheckBox; chbxSaveFiles: TCheckBox; edtReportPath: TDirectoryEdit; procedure chbxSaveFilesClick(Sender: TObject); private function GetAreaTotals: boolean; function GetPlacementTotals: boolean; function GetOverallTotal: boolean; function GetSaveResult: boolean; function GetSavingPath: string; { Private declarations } public { Public declarations } property AreaTotals: boolean read GetAreaTotals; property PlacementTotals: boolean read GetPlacementTotals; property OverallTotal: boolean read GetOverallTotal; property SaveResult: boolean read GetSaveResult; property SavingPath: string read GetSavingPath; property SelectedObjects: TIDObjects read GetSelectedObjects write SetSelectedObjects; constructor Create(AOwner: TComponent); override; end; var frmPartPlacementsReport: TfrmPartPlacementsReport; implementation uses Facade; {$R *.dfm} { TfrmPartPlacementsReport } constructor TfrmPartPlacementsReport.Create(AOwner: TComponent); begin inherited; Root := TMainFacade.GetInstance.CoreLibrary; frmPartPlacement1.Visible := false; edtReportPath.Enabled := chbxSaveFiles.Checked; MultiSelect := true; end; function TfrmPartPlacementsReport.GetAreaTotals: boolean; begin result := chbxAreaTotals.Checked; end; function TfrmPartPlacementsReport.GetPlacementTotals: boolean; begin result := chbxPlacementTotals.Checked; end; function TfrmPartPlacementsReport.GetOverallTotal: boolean; begin Result := chbxOverallTotal.Checked; end; function TfrmPartPlacementsReport.GetSaveResult: boolean; begin Result := chbxSaveFiles.Checked; end; function TfrmPartPlacementsReport.GetSavingPath: string; begin Result := edtReportPath.Text; end; procedure TfrmPartPlacementsReport.chbxSaveFilesClick(Sender: TObject); begin inherited; edtReportPath.Enabled := chbxSaveFiles.Checked; end; end.
unit uEditAlert; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uForm, ICSLanguages, Vcl.StdCtrls, Vcl.ExtCtrls, XML.XMLIntf, Vcl.Imaging.pngimage, Vcl.Buttons, PngBitBtn, ICSSpinLabeledEdit; type TfrmEditAlert = class(TfrmForm) GroupBox1: TGroupBox; cbScreenMessage: TCheckBox; cbEMail: TCheckBox; cbSMS: TCheckBox; cbGoodAlert: TCheckBox; leRepeatInterval: TICSSpinLabeledEdit; Bevel1: TBevel; btnOk: TPngBitBtn; btnCancel: TPngBitBtn; Image1: TImage; leNegativeTriggerCount: TICSSpinLabeledEdit; leName: TLabeledEdit; procedure FormShow(Sender: TObject); private FAlertXMLNode: IXMLNode; procedure FillControls; public procedure ApplyXML; property AlertXMLNode: IXMLNode read FAlertXMLNode write FAlertXMLNode; end; var frmEditAlert: TfrmEditAlert; implementation {$R *.dfm} uses uCommonTools, uXMLTools, uClasses; { TfrmEditAlert } procedure TfrmEditAlert.ApplyXML; begin xmlSetItemString(FAlertXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE, icsB64Encode(leName.Text)); xmlSetItemString(FAlertXMLNode.ChildNodes[ND_SILENT_COUNT], ND_PARAM_VALUE, leNegativeTriggerCount.Text); xmlSetItemBoolean(FAlertXMLNode.ChildNodes[ND_SCREEN_MSG], ND_PARAM_VALUE, cbScreenMessage.Checked); xmlSetItemBoolean(FAlertXMLNode.ChildNodes[ND_SEND_MAIL], ND_PARAM_VALUE,cbEMail.Checked); xmlSetItemBoolean(FAlertXMLNode.ChildNodes[ND_SEND_SMS], ND_PARAM_VALUE, cbSMS.Checked); xmlSetItemString(FAlertXMLNode.ChildNodes[ND_INTERVAL], ND_PARAM_VALUE, leRepeatInterval.Text); xmlSetItemBoolean(FAlertXMLNode.ChildNodes[ND_GOOD_ALERT], ND_PARAM_VALUE, cbGoodAlert.Checked); end; procedure TfrmEditAlert.FillControls; begin leName.Text := icsB64Decode(xmlGetItemString(FAlertXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE)); leNegativeTriggerCount.Text := xmlGetItemString(FAlertXMLNode.ChildNodes[ND_SILENT_COUNT], ND_PARAM_VALUE, '0'); cbScreenMessage.Checked := xmlGetItemBoolean(FAlertXMLNode.ChildNodes[ND_SCREEN_MSG], ND_PARAM_VALUE); cbEMail.Checked := xmlGetItemBoolean(FAlertXMLNode.ChildNodes[ND_SEND_MAIL], ND_PARAM_VALUE); cbSMS.Checked := xmlGetItemBoolean(FAlertXMLNode.ChildNodes[ND_SEND_SMS], ND_PARAM_VALUE); leRepeatInterval.Text := xmlGetItemString(FAlertXMLNode.ChildNodes[ND_INTERVAL], ND_PARAM_VALUE, '0'); cbGoodAlert.Checked := xmlGetItemBoolean(FAlertXMLNode.ChildNodes[ND_GOOD_ALERT], ND_PARAM_VALUE); end; procedure TfrmEditAlert.FormShow(Sender: TObject); begin inherited; FillControls; end; end.
unit Dao.DB; interface uses Data.DB, System.SysUtils, Vcl.Forms, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.Phys.MSSQL, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TParametroQuery = record Name: string; Value: Variant; end; TConexao = class strict private FConexao: TFDConnection; class var FInstancia: TConexao; constructor CreatePrivate; published property Conexao: TFDConnection read FConexao write FConexao; public constructor Create; class function GetInstancia: TConexao; function ExecuteSQL(const ASQL: string; const Parametros: array of TParametroQuery): Boolean; function CriaDataSource(const ASQL: string; const Parametros: array of TParametroQuery): TDataSource; function CriaQuery(const ASQL: string; const Parametros: array of TParametroQuery): TFDQuery; overload; function Open(var Erro: string): Boolean; function DataHoraAtualBanco: TDateTime; end; implementation uses Lib.SO; constructor TConexao.Create; begin raise Exception.Create('só uma conexão permitida'); end; constructor TConexao.CreatePrivate; var Erro: string; begin inherited Create; FConexao := TFDConnection.Create(nil); if not Open(Erro) then raise Exception.Create(Erro); end; function TConexao.CriaDataSource(const ASQL: string; const Parametros: array of TParametroQuery): TDataSource; begin try Result := TDataSource.Create(nil); Result.DataSet := CriaQuery(ASQL, Parametros); finally if Assigned(Result) then begin if not Assigned(Result.DataSet) then Result.DataSet.Free; Result.Free; end; end; end; function TConexao.CriaQuery(const ASQL: string; const Parametros: array of TParametroQuery): TFDQuery; var I: Integer; Parametro: TParametroQuery; begin Result := TFDQuery.Create(nil); Result.Connection := FConexao; Result.Close; Result.SQL.Clear; Result.SQL.Text := ASQL; for Parametro in Parametros do Result.Params.ParamByName(Parametro.Name).Value := Parametro.Value; Result.Open(); end; function TConexao.DataHoraAtualBanco: TDateTime; var QryTemp: TDataSet; begin QryTemp := CriaQuery('SELECT GETDATE()', []); try Result := QryTemp.Fields[0].AsDateTime; finally QryTemp.Close; FreeAndNil(QryTemp); end; end; function TConexao.ExecuteSQL(const ASQL: string; const Parametros: array of TParametroQuery): Boolean; begin FConexao.ExecSQL(ASQL); Result := True; end; class function TConexao.GetInstancia: TConexao; begin if not Assigned(FInstancia) then FInstancia := TConexao.CreatePrivate; Result := FInstancia; end; function TConexao.Open(var Erro: string): Boolean; begin try FConexao.Connected := False; FConexao.Params.Clear; FConexao.Params.LoadFromFile(ChangeFileExt(TLibSO.ApplicationFileName, '.ini')); FConexao.Connected := True; Result := FConexao.Connected except on E: Exception do begin Result := False; Erro := E.Message; end; end; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Classe de controle de Logs de Importação de Dados. The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit LogImportacaoController; interface uses Classes, SQLExpr, SysUtils, LogImportacaoVO, T2TiORM; type TLogImportacaoController = class protected public class procedure GravarLogImportacao(pTupla: String; pErro: String); end; implementation class procedure TLogImportacaoController.GravarLogImportacao(pTupla: String; pErro: String); var ObjetoLogImportacaoVO: TLogImportacaoVO; begin try ObjetoLogImportacaoVO := TLogImportacaoVO.Create; ObjetoLogImportacaoVO.Registro := pTupla; ObjetoLogImportacaoVO.Erro := pErro; ObjetoLogImportacaoVO.DataImportacao := Date; ObjetoLogImportacaoVO.HoraImportacao := TimeToStr(Now); TT2TiORM.Inserir(ObjetoLogImportacaoVO); finally FreeAndNil(ObjetoLogImportacaoVO); end; end; end.
unit prodPriceDataSource; interface uses Classes, cxCustomData; type TPriceItem = class(TCollectionItem) private FTitle: String; public property Title: String read FTitle write FTitle; end; TPriceDataSource = class(TcxCustomDataSource) private FPrice: TCollection; protected function GetRecordCount: Integer; override; function GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant; override; public constructor Create; destructor Destroy; override; end; implementation uses progDataModule, DB, cxGridCustomTableView, Variants; { TPriceDataSource } constructor TPriceDataSource.Create; var p: TPriceItem; begin FPrice := TCollection.Create(TPriceItem); with DM.Products do begin DisableControls; Filter := 'is_folder=0 and is_printable=1'; Filtered := True; First; while not EOF do begin p := TPriceItem(FPrice.Add); p.Title := FieldValues['title']; Next; end; Filtered := False; EnableControls; end; end; destructor TPriceDataSource.Destroy; begin FPrice.Free; inherited; end; function TPriceDataSource.GetRecordCount: Integer; begin Result := FPrice.Count; end; function TPriceDataSource.GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant; var PriceItem: TPriceItem; begin Result := Null; { //Get column’s DataBinding based on the index ADataBinding := GetDataBinding(Integer(AItemHandle)); //Get a specific record from the FCustomers list ACustomer := FCustomers[Integer(ARecordHandle)]; //Return a value according to DataBinding.Data } PriceItem := TPriceItem(FPrice.Items[Integer(ARecordHandle)]); case Integer(AItemHandle) of 0: Result := PriceItem.Title; else Result := Null; end; end; end.
unit uparser; {$mode objfpc}{$H+} interface uses SysUtils, ulexer; procedure checkSyntax(token: Ptoken); function doPostfix(token: PToken; out signal: PToken): PToken; function getSyntaxErrors(): string; procedure reInitRule();inline; implementation uses uStack; type TRuleWord = (C_NOP, C_CONST, C_ID, C_PLUS, C_MINUS, C_MUL, C_DIV, C_MOD, C_POW, C_ASGN, C_UM, C_COMMA, C_IE, C_OP, C_VB, C_E, C_CP, C_VE, C_P, C_K, C_PE); // Order has rule!! Trule = set of TRuleWord; var rules: array [0..2, TTokenType] of Trule; stack: TStack; currentRule: array of TRule; rix: byte = 0; top: byte = 0; LIST_ERROR: string = ''; const CR_INIT_LEN = 10; function getSyntaxErrors(): string; begin result := LIST_ERROR end; procedure reInitRule; begin currentRule[0] := [C_E]; end; procedure error(); begin LIST_ERROR := LIST_ERROR + 'Syntax error at ' + intToStr(getLineNo()) + ':' + intToStr(getColNo() - 1) + #13#10; end; function popFromRuleStack(): TRuleWord; var i: TRuleWord; begin for i in TRuleWord do if i in currentRule[top] then begin result := i; currentRule[top] -= [i]; if (currentRule[top] = []) then begin rix := top; if top > 0 then dec(top) end; break end; end; procedure pushToRuleStack(value: Trule); begin if rix = length(currentRule) then setLength(currentRule, length(currentRule) + CR_INIT_LEN); currentRule[rix] += value; top := rix; inc(rix) end; function priority(token: PToken): integer; begin case token^.typeof of tAssign : result := 5; tPlus, tMinus : result := 10; tMultiply, tDivide, tMod : result := 20; tPower : result := 30; tUnarMinus : result := 40; else result := 0; end; end; function instructionEnd(token: PToken; out signal: PToken): PToken; begin if token^.typeof = tNone then exit(token); if stack.empty then exit(nil); pop(@stack, result); signal := token; end; function comma(token: PToken; out signal: PToken): PToken; begin if stack.empty then exit(nil); if read(@stack)^.typeof = tVectorBegin then exit(token); // Не извлекаем tVectorBegin так как он в дольнейшем нужен pop(@stack, result); signal := token; end; function vectorEnd(token: PToken; out signal: PToken): PToken; begin if not stack.empty then exit(nil); pop(@stack, result); if result^.typeof = tVectorBegin then exit(token); signal := token; end; function vectorBegin(token: PToken): PToken; begin push(@stack, token); result := token; end; function openParenthses(token: PToken): PToken; begin push(@stack, token); result := token; end; function closeParenthses(token: PToken; out signal: PToken): PToken; begin pop(@stack, result); if result^.typeof = tOpParenthes then result := nil; signal := token; end; function other(token: PToken; out signal: PToken): PToken; var p1, p2: integer; t: TToken; begin result := nil; signal := nil; with token^ do begin if stack.empty then begin push(@stack, token); end else begin result := read(@stack); p1 := priority(token); p2 := priority(result); if p1 > p2 then begin push(@stack, token); result := nil; end else if p1 <= p2 then begin pop(@stack, result); t := result^; push(@stack, token); result := @t; end end end end; function doPostfix(token: PToken; out signal: PToken): PToken; begin result := nil; signal := nil; if token = nil then exit; case token^.typeof of tNone, tInstructionEnd: result := instructionEnd(token, signal); tComma: result := comma(token, signal); tVectorEnd: result := vectorEnd(token, signal); tVectorBegin: result := vectorBegin(token); tOpParenthes: result := openParenthses(token); tClParenthes: result := closeParenthses(token, signal); tNum, tId: result := token; else result := other(token, signal); end; end; procedure terminal(r: TruleWord; token: PToken); begin with token^ do begin if ((r = C_CONST) and (typeof = tNum)) or ((r = C_ID) and (typeof = tId)) or ((r = C_PLUS) and (typeof = tPlus)) or ((r = C_MINUS) and (typeof = tMinus)) or ((r = C_MUL) and (typeof = tMultiply)) or ((r = C_DIV) and (typeof = tDivide)) or ((r = C_MOD) and (typeof = tMod)) or ((r = C_POW) and (typeof = tPower)) or ((r = C_OP) and (typeof = tOpParenthes)) or ((r = C_CP) and (typeof = tClParenthes)) or ((r = C_VB) and (typeof = tVectorBegin)) or ((r = C_VE) and (typeof = tVectorEnd)) or ((r = C_ASGN) and (typeof = tAssign)) or ((r = C_COMMA) and (typeof = tComma)) or ((r = C_IE) and (typeof = tInstructionEnd)) or ((r = C_UM) and (typeof = tUnarMinus)) or ((r = C_PE) and (typeof = tNone)) then begin end else error(); // Unexpected statement end end; procedure notTerminal(r: TRuleWord; token: PToken); var rule: Trule; begin case r of C_E: rule := rules[0, token^.typeof]; C_P: rule := rules[1, token^.typeof]; C_K: rule := rules[2, token^.typeof]; else error(); end; pushToRuleStack(rule); end; procedure checkSyntax(token: PToken); var r: TruleWord; begin while (currentRule[top] <> []) do begin r := popFromruleStack(); case r of C_NOP:; C_E, C_P, C_K: notTerminal(r, token); else begin terminal(r, token); exit; end; end; end; if token^.typeof <> tNone then error(); end; initialization clear(@stack); setLength(currentRule, CR_INIT_LEN); currentRule[0] := [C_E]; // c x + - * / ^ -- ( ) none \ := ; { } , // E cP xP --K (E)P {E}P // P +E -E *E /E ^E # $ \E :=E ;E # ,E // K xP (E)P {E}P rules[1, tNone] := [C_PE]; rules[0, tNum] := [C_CONST, C_P]; rules[0, tId] := [C_ID, C_P]; rules[1, tPlus] := [C_PLUS, C_E]; rules[1, tMinus] := [C_MINUS, C_E]; rules[1, tMultiply] := [C_MUL, C_E]; rules[1, tDivide] := [C_DIV, C_E]; rules[1, tMod] := [C_MOD, C_E]; rules[1, tPower] := [C_POW, C_E]; rules[0, tUnarMinus] := [C_UM, C_K]; // '--(E)P'; rules[0, tOpParenthes] := [C_OP, C_E, C_CP, C_P]; //'(E)P'; rules[1, tClParenthes] := [C_NOP]; rules[1, tAssign] := [C_ASGN, C_E]; //':=E'; rules[0, tVectorBegin] := [C_VB, C_E, C_VE, C_P]; //'{E}P'; rules[1, tVectorEnd] := [C_NOP]; rules[1, tComma] := [C_COMMA, C_E]; rules[1, tInstructionEnd] := [C_IE, C_E]; rules[2, tId] := [C_ID, C_P]; rules[2, tOpParenthes] := [C_OP, C_E, C_CP, C_P]; rules[2, tVectorBegin] := [C_VB, C_E, C_VE, C_P]; end.
unit frMenu; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts, System.Threading, FMX.Objects, FMX.ListBox, FMX.Effects, System.ImageList, FMX.ImgList; type TFMenu = class(TFrame) loMain: TLayout; imgHeader: TImage; Label15: TLabel; lbMenu: TListBox; loHeader: TLayout; reHeader: TRectangle; seHeader: TShadowEffect; btnBack: TCornerButton; btnMore: TCornerButton; background: TRectangle; img: TImageList; seHeaderImg: TShadowEffect; btnBackToFeed: TCornerButton; procedure FirstShow; procedure btnBackClick(Sender: TObject); procedure lbMenuItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure btnBackToFeedClick(Sender: TObject); private statF : Boolean; procedure addMenu(menu : String; gl : Integer); procedure fnCekPermission; procedure setFrame; procedure fnReload(Sender : TObject); public { Public declarations } procedure ReleaseFrame; procedure fnGoBack; end; var FMenu : TFMenu; implementation {$R *.fmx} uses frMain, uFunc, uDM, uMain, uOpenUrl, uRest; { TFTemp } const spc = 10; pad = 8; procedure TFMenu.addMenu(menu: String; gl: Integer); var lb : TListBoxItem; begin lb := TListBoxItem.Create(lbMenu); lb.Parent := lbMenu; lb.Height := 130;//175; lb.Width := lbMenu.Width; lb.Tag := gl; lb.Selectable := False; lb.Text := menu; lb.FontColor := $00000000; lb.StyledSettings := []; lb.StyleLookup := 'lbMenu'; lb.StylesData['lblMenu'] := menu; lb.StylesData['glMenu.Images'] := img; lb.StylesData['glMenu.ImageIndex'] := gl; end; procedure TFMenu.btnBackClick(Sender: TObject); begin fnGoBack; end; procedure TFMenu.btnBackToFeedClick(Sender: TObject); begin fnGoFrame(MENUADMIN, FEED); end; procedure TFMenu.FirstShow; begin setFrame; if lbMenu.Items.Count > 0 then Exit; lbMenu.Items.Clear; TTask.Run(procedure () begin fnCekPermission; end).Start; end; procedure TFMenu.fnCekPermission; var arr : TStringArray; req, str : String; i, idx: Integer; sl : TStringList; begin fnLoadLoading(True); req := 'loadPermission'; try sl := TStringList.Create; try sl.AddPair('id', aIDUser); arr := fnPostJSON(DM.nHTTP, req, sl); finally sl.DisposeOf; end; if arr[0,0] = 'null' then begin fnShowE(arr[1, 0]); fnShowReload(fnReload); Exit; end; for i := 0 to Length(arr[0]) - 1 do begin if arr[2, i] = '1' then begin idx := 0; if arr[1, i] = 'DATA JAMAAH' then idx := 0 else if arr[1, i] = 'JADWAL IMAM' then idx := 1 else if arr[1, i] = 'KEGIATAN TPQ' then idx := 8//2 else if arr[1, i] = 'JADWAL KAJIAN' then idx := 3 else if arr[1, i] = 'LAPORAN KEUANGAN' then idx := 8//4 else if arr[1, i] = 'PENGUMUMAN' then idx := 5 else if arr[1, i] = 'AKUN' then idx := 6 else if arr[1, i] = 'PROSES JADWAL' then idx := 8{7} else if arr[1, i] = 'MANAJEMEN FEED' then idx := 9{7}; TThread.Synchronize(nil, procedure begin addMenu(arr[1, i], idx); end); end; end; finally fnLoadLoading(False); end; end; procedure TFMenu.fnGoBack; begin fnGoFrame(goFrame, fromFrame); end; procedure TFMenu.fnReload(Sender: TObject); begin fnShowReload(False); lbMenu.Items.Clear; TTask.Run(procedure () begin fnCekPermission; end).Start; end; procedure TFMenu.lbMenuItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin if Item.Tag = 8 then begin fnShowE('FITUR AKAN SEGERA HADIR'); Exit; end; fnGoFrame(MENUADMIN, Item.Text); end; procedure TFMenu.ReleaseFrame; begin DisposeOf; end; procedure TFMenu.setFrame; begin if statF then Exit; statF := True; end; end.
Unit ZTerminl; {################################} {# ZiLEM Z80 Emulator #} {# Terminal Emulator #} {# Copyright (c) 1994 James Ots #} {# All rights reserved #} {################################} Interface Uses Objects, Drivers, App, Menus, Crt, ZGlobals, ZConsts; Type PScreen = ^TScreen; TScreen = Array[1..25,1..80] of Word; PZTerminal = ^TZTerminal; TZTerminal = object(TObject) Mode : Integer; TempScreenMode : Word; TheDesktop : PDesktop; TheMenuBar : PMenuView; TheStatusLine : PStatusLine; Screen : PScreen; Status : Word; TempScreen : PScreen; Attrib : Integer; Terminal : Record Width : Integer; Height : Integer; Wrap : Boolean; Scroll : Boolean; ScrollViewport : Boolean; End; Pos : Record Y,X : Integer; End; Viewport : Record A,B : Record X,Y : Integer; End; End; Constructor Init(ADesktop : PDesktop; AMenuBar : PMenuView; AStatusLine : PStatusLine); Destructor Done; virtual; Procedure Z80Screen; Procedure ZiLEMScreen; Procedure PrintChar(AChar : Char); Procedure Scroll(Line : Integer); Procedure UpdateCursor; Procedure ClearViewport; Procedure HomeCursor; Procedure CursorUp; Procedure CursorDown; Procedure CursorLeft; Procedure CursorRight; Procedure Control(AByte : Byte); Function ReadChar : Char; Procedure ShowCursor; Procedure HideCursor; Function KeyStatus : Boolean; End; Implementation Procedure TZTerminal.ShowCursor; Begin InLine($B4/$01/$B9/$07/$06/$CD/$10); End; {of TZTerminal.ShowCursor} Procedure TZTerminal.HideCursor; Begin InLine($B4/$01/$B9/$20/$21/$CD/$10); End; {of TZTerminal.HideCursor} Procedure TZTerminal.UpdateCursor; Begin GotoXY(Pos.X+Pred(Viewport.A.X),Pos.Y+Pred(ViewPort.A.Y)); End; {of TZTerminal.UpdateCursor} Procedure TZTerminal.CursorUp; Begin Dec(Pos.Y); If Pos.Y<1 then Pos.Y:=1; UpdateCursor; End; {of TZTerminal.CursorUp} Procedure TZTerminal.CursorDown; Begin Inc(Pos.Y); If Pos.Y>Terminal.Height then Pos.Y := Terminal.Height; UpdateCursor; End; {of TZTerminal.CursorDown} Procedure TZTerminal.CursorLeft; Begin Dec(Pos.X); If Pos.X<1 then If Pos.Y>1 then Begin Pos.X := Terminal.Width; Dec(Pos.Y); End else Inc(Pos.X); UpdateCursor; End; {of TZTerminal.CursorLeft} Procedure TZTerminal.CursorRight; Begin Inc(Pos.X); If Pos.X>Terminal.Width then If Pos.Y<Terminal.Height then Begin Pos.X := 1; Inc(Pos.Y); End else Dec(Pos.X); UpdateCursor; End; {of TZTerminal.Cursor.Right} Function TZTerminal.KeyStatus : Boolean; Begin KeyStatus := KeyPressed; End; {of TZTerminal.KeyStatus} Function TZTerminal.ReadChar : Char; Begin ReadChar := ReadKey; End; {of TZTerminal.ReadChar} Procedure TZTerminal.Control(AByte : Byte); Begin Case Status of teOk : Case Char(AByte) of #$1B : Status := teEscape; #$07 : Write(#7); #$08 : CursorLeft; #$0D : Begin Pos.X := 1; UpdateCursor; End; #$0A : Begin CursorDown; If Pos.Y = Terminal.Height then Scroll(Terminal.Height); End; Else PrintChar(Char(AByte)); End; tePositionColumn : Begin Pos.X := AByte-32; If Pos.X>Terminal.Width then Pos.X := Terminal.Width; If Pos.X<1 then Pos.X := 1; UpdateCursor; Status := teOk; End; tePositionRow : Begin Pos.Y := AByte-32; If Pos.Y>Terminal.Height then Pos.Y := Terminal.Height; If Pos.Y<1 then Pos.Y := 1; Status := tePositionColumn; End; teEscape : Case Char(AByte) of 'A' : Begin CursorUp; Status := teOk; End; 'B' : Begin CursorDown; Status := teOk; End; 'C' : Begin CursorRight; Status := teOk; End; 'D' : Begin CursorLeft; Status := teOk; End; 'E' : Begin ClearViewport; Status := teOk; End; 'H' : Begin HomeCursor; Status := teOk; End; 'Y' : Status := tePositionRow; 'v' : Begin Terminal.Wrap := True; Status := teOk; End; 'w' : Begin Terminal.Wrap := False; Status := teOk; End; 'f' : Begin HideCursor; Status := teOk; End; 'e' : Begin ShowCursor; Status := teOk; End; 'p' : Begin Attrib := $70; Status := teOk; End; 'q' : Begin Attrib := $07; Status := teOk; End; Else Status := teOk; End; Else Status := teOk; End; End; {of TZTerminal.Control} Procedure TZTerminal.ClearViewport; Var XX : Integer; YY : Integer; Begin For YY := Viewport.A.Y to Viewport.B.Y do If Terminal.ScrollViewport then For XX := Viewport.A.X to Viewport.B.X do Screen^[YY,XX] := Word(256*Attrib+32) else For XX := 1 to Terminal.Width do Screen^[YY,XX] := Word(256*Attrib+32); End; {of TZTerminal.ClearViewport} Procedure TZTerminal.HomeCursor; Begin Pos.X := 1; Pos.Y := 1; UpdateCursor; End; {of TZTerminal.HomeCursor} Procedure TZTerminal.Scroll(Line : Integer); Var XX : Integer; YY : Integer; Begin With Terminal do Begin If Line>Height then Line := Height; For YY := Succ(Viewport.A.Y) to Viewport.A.Y+Pred(Line) do If Terminal.ScrollViewport then For XX := Viewport.A.X to Viewport.B.X do Screen^[Pred(XX),XX] := Screen^[YY,XX] else For XX := 0 to Width do Screen^[Pred(YY),XX] := Screen^[YY,XX]; For XX := 0 to Width do Screen^[Viewport.A.Y+Pred(Line),XX] := Attrib*256+32; End; End; {of TZTerminal.Scroll} Procedure TZTerminal.PrintChar(AChar : Char); Var Swapped : Boolean; Begin If Mode=tmZiLEM then Begin Z80Screen; Mode := tmZ80; Swapped := True; End else Swapped := False; With Terminal, Pos do Begin Screen^[Y+Pred(Viewport.A.Y),X+Pred(Viewport.A.X)] := Byte(AChar)+ 256*Attrib; Inc(X); If X > (Viewport.B.X-Pred(Viewport.A.X)) then If Wrap then Begin X := 1; Inc(Y); If Y > (Viewport.B.Y-Pred(Viewport.A.Y)) then Begin If Scroll then TZTerminal.Scroll(Viewport.B.Y-Pred(Viewport.A.Y)); Y := Viewport.B.Y-Pred(Viewport.A.Y); End; End else X := Viewport.B.X-Pred(Viewport.A.X); UpdateCursor; End; If Swapped then Begin ZiLEMScreen; Mode := tmZiLEM; End; End; {of TZTerminal.PrintChar} Destructor TZTerminal.Done; Begin Dispose(TempScreen); End; {of TZTerminal.Done} Constructor TZTerminal.Init(ADesktop : PDesktop ; AMenuBar : PMenuView; AStatusLine : PStatusLine); Var x,y : Integer; Begin TheDesktop := ADesktop; TheMenuBar := AMenuBar; TheStatusLine := AStatusLine; New(Screen); Screen := Ptr($B800,0000); New(TempScreen); Attrib := $07; For y := 1 to 25 do For x := 1 to 80 do TempScreen^[y,x] := Word(Attrib*256+32); Pos.X := 1; Pos.Y := 1; Mode := tmZiLEM; With Terminal do Begin Width := 80; Height := 24; Wrap := True; Scroll := True; ScrollViewport := False; End; With Viewport do Begin A.X := 1; A.Y := 1; B.X := Terminal.Width; B.Y := Terminal.Height; End; End; {of TZTerminal.Init} Procedure TZTerminal.ZiLEMScreen; Begin HideCursor; TempScreen^ := Screen^; SetVideoMode(TempScreenMode); InitEvents; TheDesktop^.Redraw; TheMenuBar^.Draw; TheStatusLine^.Draw; Mode := tmZiLEM; End; {of TZTerminal.ZiLEMScreen} Procedure TZTerminal.Z80Screen; Begin DoneEvents; TempScreenMode := ScreenMode; SetVideoMode(ScreenMode and not smFont8x8); Screen^ := TempScreen^; ShowCursor; UpdateCursor; Mode := tmZ80; End; {of TZTerminal.Z80Screen} End. {of Unit ZTerminl}
unit SubDividerCommon; interface uses Classes, ClientCommon, SubDividerCommonObjects, SysUtils, Variants; type TDicts = class public EdgesDict: variant; //EdgeRangesDict: variant; TectBlockDict: variant; CommentDict: variant; FullCommentDict: variant; StratonsDict: variant; AreaDict: variant; AreaSynonyms: variant; StrRegions: variant; PetrolRegions: variant; procedure ReloadStratons; procedure MakeList(ALst: TStringList; ADict: variant); procedure AddAreaSynonym(AAreaID: integer; AAreaName, AAreaSynonym: string); constructor Create; end; function Split(const S: string; const Splitter: char): TStrArr; function EngTransLetter(const S: string): string; function RusTransLetter(const S: string): string; function FullTrim(const S: string): string; function DigitPos(S: string): integer; var AllDicts: TDicts; AllStratons: TStratons; AllSynonyms: TSynonymStratons; Allregions: TRegions; AllWells: TWells; ActiveWells: TWells; ConvertedWells: TWells; GatherComponents: boolean = true; implementation function FullTrim(const S: string): string; var i: integer; begin Result := ''; for i := 1 to Length(S) do if S[i] <> ' ' then Result := Result + S[i]; end; function DigitPos(S: string): integer; var i: char; iPos: integer; begin S := trim(S); Result := pos('-', S) - 1; if Result <= 0 then Result := Length(S); for i := '1' to '9' do begin iPos := pos(i, S); if iPos in [1 .. Result - 1] then Result := iPos; end; end; function RusTransLetter(const S: string): string; begin //Result := AnsiUpperCase(S); Result := S; Result := StringReplace(Result,'E','Е',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'T','Т',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Y','У',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'D','Д',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'O','О',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'P','Р',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'A','А',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'H','Н',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'K','К',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'X','Х',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'C','С',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'B','В',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'M','М',[rfReplaceAll,rfIgnoreCase]); end; function EngTransLetter(const S: string): string; begin Result := AnsiUpperCase(S); Result := StringReplace(Result,'Е','E',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Т','T',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'З','3',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'У','Y',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Д','D',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'О','O',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Р','P',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'А','A',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Н','H',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'К','K',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'Х','X',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'С','C',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'В','B',[rfReplaceAll,rfIgnoreCase]); Result := StringReplace(Result,'М','M',[rfReplaceAll,rfIgnoreCase]); end; function Split(const S: string; const Splitter: char): TStrArr; var i, iLen, iPrev: integer; begin SetLength(Result, 0); iLen := 0; iPrev := 1; for i := 1 to Length(S) do if (S[i] = Splitter) or (i = Length(S)) then begin inc(iLen); SetLength(Result, iLen); Result[iLen - 1] := Copy(S, iPrev, i - iPrev + ord(i = Length(S))); iPrev := i + 1; end; end; procedure TDicts.MakeList(ALst: TStringList; ADict: variant); var i, id: integer; begin for i := 0 to varArrayHighBound(ADict, 2) do begin id := ADict[0, i]; ALst.AddObject(ADict[1, i], TObject(id)); end; end; procedure TDicts.AddAreaSynonym(AAreaID: integer; AAreaName, AAreaSynonym: string); var iHB: integer; begin iHB := VarArrayHighBound(AreaSynonyms, 2); inc(iHB); VarArrayRedim(AreaSynonyms, iHB); AreaSynonyms[0, iHB] := AAreaID; AreaSynonyms[1, iHB] := AAreaName; AreaSynonyms[2, iHB] := AAreaSynonym; end; constructor TDicts.Create; var iResult: integer; begin inherited Create; CommentDict := GetDictEx('TBL_SUBDIVISION_COMMENT', '*', '(COMMENT_ID <> 3) and (Comment_ID <> 4)'); FullCommentDict := GetDictEx('TBL_SUBDIVISION_COMMENT'); TectBlockDict := GetDictEx('TBL_TECTONIC_BLOCK'); iResult := IServer.ExecuteQuery('select sr.region_id, sr.straton_id, sr.vch_region_name, ' + 'sn.vch_straton_index from tbl_stratotype_region_dict sr, ' + 'tbl_stratigraphy_name_dict sn ' + 'where sn.straton_id = sr.straton_id'); if iResult > 0 then StrRegions := IServer.QueryResult; //GetDictEx('TBL_STRATOTYPE_REGION_DICT'); PetrolRegions := GetDictEx('TBL_PETROLIFEROUS_REGION_DICT', '*', ' where NUM_REGION_TYPE = 3'); // такой таблицы покамест нету // EdgeRangesDict := GetDictEx('TBL_EDGES_RANGES_DICT'); //SubDivisionProperties := GetDictEx('TBL_SUBDIVISION_COMMENT_DICT'); { iResult := IServer.ExecuteQuery('SELECT distinct s.straton_id, s.vch_straton_index, ' + 's.vch_straton_definition, s.vch_taxonomy_unit_name, ' + 's.num_Age_Of_Base, s.num_Age_Of_Top, ' + 's.vch_Straton_Def_Synonym, s.num_taxonomy_unit_range ' + 'FROM VW_STRATIGRAPHY_DICT s ' + 'where ((s.num_taxonomy_unit_range < 9) or ' + 's.num_taxonomy_unit_range in (15, 16, 17, 35, 36)) ' + 'and s.vch_straton_index<>"" ' + 'order by s.num_age_of_base, s.num_range desc, s.num_taxonomy_unit_range'); iResult := IServer.ExecuteQuery('SELECT distinct s.straton_Region_id, s.vch_straton_index, ' + 's.vch_straton_definition, s.vch_taxonomy_unit_name, ' + 's.num_Age_Of_Base, s.num_Age_Of_Top, ' + 's.vch_Straton_Def_Synonym, s.num_taxonomy_unit_range ' + 'FROM VW_STRATIGRAPHY_DICT s ' + 'where s.Scheme_ID = 1 ' + 'order by s.num_age_of_base, s.num_range desc, s.num_taxonomy_unit_range');} {iResult := IServer.ExecuteQuery('SELECT distinct s.straton_id, max(s.vch_straton_index), ' + 'max(s.vch_straton_definition), max(s.vch_taxonomy_unit_name), ' + 'max(s.num_Age_Of_Base), min(s.num_Age_Of_Top), ' + 'max(s.vch_Straton_Def_Synonym), max(s.num_taxonomy_unit_range) ' + 'FROM VW_STRATIGRAPHY_DICT s ' + 'where s.Scheme_ID = 1 ' + // не выводим биозоны 'and not((s.vch_Taxonomy_Unit_Name containing ' + '''' + 'зона' + ''''+') or ' + '(s.vch_Taxonomy_Unit_Name containing ' + '''' + 'лона' + ''''+') or ' + '(s.vch_Taxonomy_Unit_Name containing ' + '''' + 'шкала'+ ''''+') or ' + '(s.vch_Taxonomy_Unit_Name containing ' + '''' + 'слой' + ''''+') or ' + '(s.vch_Taxonomy_Unit_Name containing ' + '''' + 'слои' + ''''+')) ' + 'group by s.Straton_ID ' + 'order by 5, 6, 8'); if iResult > 0 then StratonsDict := IServer.QueryResult;} ReloadStratons; AreaDict := GetDictEx('TBL_AREA_DICT'); // создаем справочник синонимов площадей // ID площади // её правильное название // встетившийся синоним AreaSynonyms := VarArrayCreate([0, 2, 0, 0], varVariant); end; procedure TDicts.ReloadStratons; var iResult: integer; begin iResult := IServer.ExecuteQuery ('Select * from spd_Get_Straton_For_Subdivision(0)'); if iResult > 0 then StratonsDict := IServer.QueryResult; end; end.
{*******************************************************} { } { Gospel Compiler System } { } { Copyright (C) 1999 Voltus Corporation } { } {*******************************************************} unit GraphSys; interface uses Windows, Classes, SysUtils, Kernel, Graphics; type TPoint = class private FY: real; FX: real; FZ: real; public constructor Create(const aX, aY, aZ: real); property X: real read FX; property Y: real read FY; property Z: real read FZ; end; TPointsType = class(TDataType) public function Instantiate: TData; override; function Assignable(AssignType: TDataType): boolean; override; end; TPoints = class(TData) private FPoints: TList; fColor: TColor; function GeTDXFPoint(const i: integer): TPoint; function GetPointCount: integer; public constructor CreateFrom(aDataType: TDataType); override; destructor Destroy; override; procedure Assign(Data: TData); override; function Duplicate: TData; override; public property Point[const i: integer]: TPoint read GeTDXFPoint; property Color: TColor read fColor write fColor; property PointCount: integer read GetPointCount; procedure Concat(Points: TPoints); procedure AddPoint(aPoint: TPoint); procedure Clear; procedure Draw(Canvas: TCanvas); function WriteToBitmap: TBitmap; end; TBmpType = class(TDataType) public function Instantiate: TData; override; function Assignable(AssignType: TDataType): boolean; override; end; TBmp = class(TData) private FBitmap: TBitmap; public constructor CreateFrom(aDataType: TDataType); override; destructor Destroy; override; procedure Assign(Data: TData); override; function Duplicate: TData; override; function LoadFromFile(const FileName: TFileName): boolean; procedure SaveToFile(const FileName: TFileName); property Bitmap: TBitmap read FBitmap; public procedure Draw(Canvas: TCanvas); function WriteToPoints(const Color: TColor): TPoints; procedure GrayLevel; procedure Umbralize(const Umbral: Integer); end; var BitmapType: TBmpType; PointsType: TPointsType; implementation uses Dialogs, Constants; { TPoint } constructor TPoint.Create(const aX, aY, aZ: real); begin inherited Create; FX := aX; FY := aY; FZ := aZ; end; { TPoints } procedure TPoints.AddPoint(aPoint: TPoint); begin FPoints.Add(aPoint); end; procedure TPoints.Assign(Data: TData); begin if Data is TPoints then begin Clear; Concat(TPoints(Data)); end; end; procedure TPoints.Clear; var i: integer; begin for i := 0 to pred(FPoints.Count) do TPoint(FPoints.Items[i]).free; FPoints.Clear; end; procedure TPoints.Concat(Points: TPoints); var i: integer; begin for i := 0 to pred(Points.PointCount) do with Points.Point[i] do AddPoint(TPoint.Create(X, Y, Z)); end; constructor TPoints.CreateFrom(aDataType: TDataType); begin inherited; FPoints := TList.Create; FColor := clBlack; end; destructor TPoints.Destroy; begin FPoints.free; inherited; end; procedure TPoints.Draw(Canvas: TCanvas); var i: integer; begin for i := 0 to pred(FPoints.Count) do Canvas.Pixels[trunc(Point[i].X), trunc(Point[i].Y)] := Color; end; function TPoints.Duplicate: TData; begin Result := DataType.Instantiate; Result.Assign(Self); end; function TPoints.GeTDXFPoint(const i: integer): TPoint; begin Result := FPoints.Items[i]; end; function TPoints.GetPointCount: integer; begin Result := FPoints.Count; end; function TPoints.WriteToBitmap: TBitmap; var i: integer; begin Result := TBitmap.Create; for i := 0 to pred(FPoints.Count) do with Point[i] do Result.Canvas.Pixels[trunc(X), trunc(Y)] := Color; end; { TBmpType } function TBmpType.Assignable(AssignType: TDataType): boolean; begin Result := AssignType = Self; end; function TBmpType.Instantiate: TData; begin Result := TBmp.CreateFrom(Self); end; { TBmp } procedure TBmp.Assign(Data: TData); begin if Data is TBmp then FBitmap.Assign(TBmp(Data).Bitmap); end; constructor TBmp.CreateFrom(aDataType: TDataType); begin inherited; FBitmap := TBitmap.Create; end; destructor TBmp.Destroy; begin FBitmap.free; inherited; end; procedure TBmp.Draw(Canvas: TCanvas); begin Canvas.Draw(0, 0, FBitmap); end; function TBmp.Duplicate: TData; begin Result := DataType.Instantiate; Result.Assign(Self); end; procedure TBmp.GrayLevel; var x, y: Integer; ImageDst: TBitmap; R, G, B, Inten: DWORD; //RGB and Intensity Color: COLORREF; begin ImageDst := TBitmap.Create; ImageDst.PixelFormat := pf8bit; ImageDst.ReleaseMaskHandle; ImageDst.Width := Bitmap.Width; ImageDst.Height := Bitmap.Height; for x := 0 to pred(Bitmap.Width) do for y := 0 to pred(Bitmap.Height) do begin Color := GetPixel(Bitmap.Canvas.Handle, x, y); R := GetRValue(Color); G := GetGValue(Color); B := GetBValue(Color); Inten := Round((R + B + G) / 3); //GrayLevel ImageDst.Canvas.Pixels[x, y] := RGB(Inten, Inten, Inten); end; FBitmap := ImageDst; ImageDst.FreeImage; end; function TBmp.LoadFromFile(const FileName: TFileName): boolean; begin Result := false; try FBitmap.LoadFromFile(FileName); Result := true; except on EFOpenError do MessageDlg(Format(emFileNotFound, [FileName]), mtError, [mbOK], 0); end; end; procedure TBmp.SaveToFile(const FileName: TFileName); begin FBitmap.SaveToFile(FileName); end; procedure TBmp.Umbralize(const Umbral: Integer); var x, y: Integer; R, G, B, Inten: DWORD; //RGB and Intensity Color: COLORREF; begin for x := 0 to pred(Bitmap.Width) do for y := 0 to pred(Bitmap.Height) do begin Color := GetPixel(Bitmap.Canvas.Handle, x, y); R := GetRValue(Color); G := GetGValue(Color); B := GetBValue(Color); Inten := Round((R + B + G) / 3); //GrayLevel if Inten <= DWORD(Umbral) then Bitmap.Canvas.Pixels[x, y] := ClBlack else Bitmap.Canvas.Pixels[x, y] := ClWhite; end; end; function TBmp.WriteToPoints(const Color: TColor): TPoints; var x, y: Integer; begin Result := TPoints(PointsType.Instantiate); for y := 0 to pred(Bitmap.Height) do for x := 0 to pred(Bitmap.Width) do if Bitmap.Canvas.Pixels[x, y] = Color then Result.AddPoint(TPoint.Create(x, y, 0)); end; { TPointsType } function TPointsType.Assignable(AssignType: TDataType): boolean; begin Result := AssignType = Self; end; function TPointsType.Instantiate: TData; begin Result := TPoints.CreateFrom(Self); end; initialization BitmapType := TBmpType.CreateIdent('Bitmap'); PointsType := TPointsType.CreateIdent('Points'); with SystemBlock do begin Types.AddEntry(BitmapType); Types.AddEntry(PointsType); end; end.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0005.PAS Description: GLOBALS.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:51 *) Unit globals; { Use this Unit For Procedures, Functions and Variables that every Program you Write will share. } Interface Uses Dos; Type str1 = String[1]; str2 = String[2]; str3 = String[3]; str4 = String[4]; str5 = String[5]; str6 = String[6]; str7 = String[7]; str8 = String[8]; str9 = String[9]; str10 = String[10]; str11 = String[11]; str12 = String[12]; str13 = String[13]; str14 = String[14]; str15 = String[15]; str16 = String[16]; str17 = String[17]; str18 = String[18]; str19 = String[19]; str20 = String[20]; str21 = String[21]; str22 = String[22]; str23 = String[23]; str24 = String[24]; str25 = String[25]; str26 = String[26]; str27 = String[27]; str28 = String[28]; str29 = String[29]; str30 = String[30]; str31 = String[31]; str32 = String[32]; str33 = String[33]; str34 = String[34]; str35 = String[35]; str36 = String[36]; str37 = String[37]; str38 = String[38]; str39 = String[39]; str40 = String[40]; str41 = String[41]; str42 = String[42]; str43 = String[43]; str44 = String[44]; str45 = String[45]; str46 = String[46]; str47 = String[47]; str48 = String[48]; str49 = String[49]; str50 = String[50]; str51 = String[51]; str52 = String[52]; str53 = String[53]; str54 = String[54]; str55 = String[55]; str56 = String[56]; str57 = String[57]; str58 = String[58]; str59 = String[59]; str60 = String[60]; str61 = String[61]; str62 = String[62]; str63 = String[63]; str64 = String[64]; str65 = String[65]; str66 = String[66]; str67 = String[67]; str68 = String[68]; str69 = String[69]; str70 = String[70]; str71 = String[71]; str72 = String[72]; str73 = String[73]; str74 = String[74]; str75 = String[75]; str76 = String[76]; str77 = String[77]; str78 = String[78]; str79 = String[79]; str80 = String[80]; str81 = String[81]; str82 = String[82]; str83 = String[83]; str84 = String[84]; str85 = String[85]; str86 = String[86]; str87 = String[87]; str88 = String[88]; str89 = String[89]; str90 = String[90]; str91 = String[91]; str92 = String[92]; str93 = String[93]; str94 = String[94]; str95 = String[95]; str96 = String[96]; str97 = String[97]; str98 = String[98]; str99 = String[99]; str100 = String[100]; str101 = String[101]; str102 = String[102]; str103 = String[103]; str104 = String[104]; str105 = String[105]; str106 = String[106]; str107 = String[107]; str108 = String[108]; str109 = String[109]; str110 = String[110]; str111 = String[111]; str112 = String[112]; str113 = String[113]; str114 = String[114]; str115 = String[115]; str116 = String[116]; str117 = String[117]; str118 = String[118]; str119 = String[119]; str120 = String[120]; str121 = String[121]; str122 = String[122]; str123 = String[123]; str124 = String[124]; str125 = String[125]; str126 = String[126]; str127 = String[127]; str128 = String[128]; str129 = String[129]; str130 = String[130]; str131 = String[131]; str132 = String[132]; str133 = String[133]; str134 = String[134]; str135 = String[135]; str136 = String[136]; str137 = String[137]; str138 = String[138]; str139 = String[139]; str140 = String[140]; str141 = String[141]; str142 = String[142]; str143 = String[143]; str144 = String[144]; str145 = String[145]; str146 = String[146]; str147 = String[147]; str148 = String[148]; str149 = String[149]; str150 = String[150]; str151 = String[151]; str152 = String[152]; str153 = String[153]; str154 = String[154]; str155 = String[155]; str156 = String[156]; str157 = String[157]; str158 = String[158]; str159 = String[159]; str160 = String[160]; str161 = String[161]; str162 = String[162]; str163 = String[163]; str164 = String[164]; str165 = String[165]; str166 = String[166]; str167 = String[167]; str168 = String[168]; str169 = String[169]; str170 = String[170]; str171 = String[171]; str172 = String[172]; str173 = String[173]; str174 = String[174]; str175 = String[175]; str176 = String[176]; str177 = String[177]; str178 = String[178]; str179 = String[179]; str180 = String[180]; str181 = String[181]; str182 = String[182]; str183 = String[183]; str184 = String[184]; str185 = String[185]; str186 = String[186]; str187 = String[187]; str188 = String[188]; str189 = String[189]; str190 = String[190]; str191 = String[191]; str192 = String[192]; str193 = String[193]; str194 = String[194]; str195 = String[195]; str196 = String[196]; str197 = String[197]; str198 = String[198]; str199 = String[199]; str200 = String[200]; str201 = String[201]; str202 = String[202]; str203 = String[203]; str204 = String[204]; str205 = String[205]; str206 = String[206]; str207 = String[207]; str208 = String[208]; str209 = String[209]; str210 = String[210]; str211 = String[211]; str212 = String[212]; str213 = String[213]; str214 = String[214]; str215 = String[215]; str216 = String[216]; str217 = String[217]; str218 = String[218]; str219 = String[219]; str220 = String[220]; str221 = String[221]; str222 = String[222]; str223 = String[223]; str224 = String[224]; str225 = String[225]; str226 = String[226]; str227 = String[227]; str228 = String[228]; str229 = String[229]; str230 = String[230]; str231 = String[231]; str232 = String[232]; str233 = String[233]; str234 = String[234]; str235 = String[235]; str236 = String[236]; str237 = String[237]; str238 = String[238]; str239 = String[239]; str240 = String[240]; str241 = String[241]; str242 = String[242]; str243 = String[243]; str244 = String[244]; str245 = String[245]; str246 = String[246]; str247 = String[247]; str248 = String[248]; str249 = String[249]; str250 = String[250]; str251 = String[251]; str252 = String[252]; str253 = String[253]; str254 = String[254]; str255 = String[255]; Const MaxWord = $ffff; MinWord = 0; MinInt = Integer($8000); MinLongInt = $80000000; UseCfg = True; {Color Constants: Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Brown = 6; LtGray = 7; DkGray = 8; LtBlue = 9; LtGreen = A; LtCyan = B; LtRed = C; LtMagenta = D; Yellow = E; White = F } Const Blink = $80; {Screen color Constants} Const BlackOnBlack = $00; BlueOnBlack = $01; Const BlackOnBlue = $10; BlueOnBlue = $11; Const BlackOnGreen = $20; BlueOnGreen = $21; Const BlackOnCyan = $30; BlueOnCyan = $31; Const BlackOnRed = $40; BlueOnRed = $41; Const BlackOnMagenta = $50; BlueOnMagenta = $51; Const BlackOnBrown = $60; BlueOnBrown = $61; Const BlackOnLtGray = $70; BlueOnLtGray = $71; Const GreenOnBlack = $02; CyanOnBlack = $03; Const GreenOnBlue = $12; CyanOnBlue = $13; Const GreenOnGreen = $22; CyanOnGreen = $23; Const GreenOnCyan = $32; CyanOnCyan = $33; Const GreenOnRed = $42; CyanOnRed = $43; Const GreenOnMagenta = $52; CyanOnMagenta = $53; Const GreenOnBrown = $62; CyanOnBrown = $63; Const GreenOnLtGray = $72; CyanOnLtGray = $73; Const RedOnBlue = $14; MagentaOnBlue = $15; Const RedOnGreen = $24; MagentaOnGreen = $25; Const RedOnCyan = $34; MagentaOnCyan = $35; Const RedOnRed = $44; MagentaOnRed = $45; Const RedOnMagenta = $54; MagentaOnMagenta = $55; Const RedOnBrown = $64; MagentaOnBrown = $65; Const RedOnLtGray = $74; MagentaOnLtGray = $75; Const BrownOnBlack = $06; LtGrayOnBlack = $07; Const BrownOnBlue = $16; LtGrayOnBlue = $17; Const BrownOnGreen = $26; LtGrayOnGreen = $27; Const BrownOnCyan = $36; LtGrayOnCyan = $37; Const BrownOnRed = $46; LtGrayOnRed = $47; Const BrownOnMagenta = $56; LtGrayOnMagenta = $57; Const BrownOnBrown = $66; LtGrayOnBrown = $67; Const BrownOnLtGray = $76; LtGrayOnLtGray = $77; Const DkGrayOnBlack = $08; LtBlueOnBlack = $09; Const DkGrayOnBlue = $18; LtBlueOnBlue = $19; Const DkGrayOnGreen = $28; LtBlueOnGreen = $29; Const DkGrayOnCyan = $38; LtBlueOnCyan = $39; Const DkGrayOnRed = $48; LtBlueOnRed = $49; Const DkGrayOnMagenta = $58; LtBlueOnMagenta = $59; Const DkGrayOnBrown = $68; LtBlueOnBrown = $69; Const DkGrayOnLtGray = $78; LtBlueOnLtGray = $79; Const LtGreenOnBlack = $0A; LtCyanOnBlack = $0B; Const LtGreenOnBlue = $1A; LtCyanOnBlue = $1B; Const LtGreenOnGreen = $2A; LtCyanOnGreen = $2B; Const LtGreenOnCyan = $3A; LtCyanOnCyan = $3B; Const LtGreenOnRed = $4A; LtCyanOnRed = $4B; Const LtGreenOnMagenta = $5A; LtCyanOnMagenta = $5B; Const LtGreenOnBrown = $6A; LtCyanOnBrown = $6B; Const LtGreenOnLtGray = $7A; LtCyanOnLtGray = $7B; Const LtRedOnBlue = $1C; LtMagentaOnBlue = $1D; Const LtRedOnGreen = $2C; LtMagentaOnGreen = $2D; Const LtRedOnCyan = $3C; LtMagentaOnCyan = $3D; Const LtRedOnRed = $4C; LtMagentaOnRed = $4D; Const LtRedOnMagenta = $5C; LtMagentaOnMagenta = $5D; Const LtRedOnBrown = $6C; LtMagentaOnBrown = $6D; Const LtRedOnLtGray = $7C; LtMagentaOnLtGray = $7D; Const YellowOnBlack = $0E; WhiteOnBlack = $0F; Const YellowOnBlue = $1E; WhiteOnBlue = $1F; Const YellowOnGreen = $2E; WhiteOnGreen = $2F; Const YellowOnCyan = $3E; WhiteOnCyan = $3F; Const YellowOnRed = $4E; WhiteOnRed = $4F; Const YellowOnMagenta = $5E; WhiteOnMagenta = $5F; Const YellowOnBrown = $6E; WhiteOnBrown = $6F; Const YellowOnLtGray = $7E; WhiteOnLtGray = $7F; Const BlackOnDkGray = Blink + $00; BlueOnDkGray = Blink + $01; Const BlackOnLtBlue = Blink + $10; BlueOnLtBlue = Blink + $11; Const BlackOnLtGreen = Blink + $20; BlueOnLtGreen = Blink + $21; Const BlackOnLtCyan = Blink + $30; BlueOnLtCyan = Blink + $31; Const BlackOnLtRed = Blink + $40; BlueOnLtRed = Blink + $41; Const BlackOnLtMagenta = Blink + $50; BlueOnLtMagenta = Blink + $51; Const BlackOnYellow = Blink + $60; BlueOnYellow = Blink + $61; Const BlackOnWhite = Blink + $70; BlueOnWhite = Blink + $71; Const GreenOnDkGray = Blink + $02; CyanOnDkGray = Blink + $03; Const GreenOnLtBlue = Blink + $12; CyanOnLtBlue = Blink + $13; Const GreenOnLtGreen = Blink + $22; CyanOnLtGreen = Blink + $23; Const GreenOnLtCyan = Blink + $32; CyanOnLtCyan = Blink + $33; Const GreenOnLtRed = Blink + $42; CyanOnLtRed = Blink + $43; Const GreenOnLtMagenta = Blink + $52; CyanOnLtMagenta = Blink + $53; Const GreenOnYellow = Blink + $62; CyanOnYellow = Blink + $63; Const GreenOnWhite = Blink + $72; CyanOnWhite = Blink + $73; Const RedOnDkGray = Blink + $04; MagentaOnDkGray = Blink + $05; Const RedOnLtBlue = Blink + $14; MagentaOnLtBlue = Blink + $15; Const RedOnLtGreen = Blink + $24; MagentaOnLtGreen = Blink + $25; Const RedOnLtCyan = Blink + $34; MagentaOnLtCyan = Blink + $35; Const RedOnLtRed = Blink + $44; MagentaOnLtRed = Blink + $45; Const RedOnLtMagenta = Blink + $54; MagentaOnLtMagenta= Blink + $55; Const RedOnYellow = Blink + $64; MagentaOnYellow = Blink + $65; Const RedOnWhite = Blink + $74; MagentaOnWhite = Blink + $75; Const BrownOnDkGray = Blink + $06; LtGrayOnDkGray = Blink + $07; Const BrownOnLtBlue = Blink + $16; LtGrayOnLtBlue = Blink + $17; Const BrownOnLtGreen = Blink + $26; LtGrayOnLtGreen = Blink + $27; Const BrownOnLtCyan = Blink + $36; LtGrayOnLtCyan = Blink + $37; Const BrownOnLtRed = Blink + $46; LtGrayOnLtRed = Blink + $47; Const BrownOnLtMagenta = Blink + $56; LtGrayOnLtMagenta = Blink + $57; Const BrownOnYellow = Blink + $66; LtGrayOnYellow = Blink + $67; Const BrownOnWhite = Blink + $76; LtGrayOnWhite = Blink + $77; Const DkGrayOnDkGray = Blink + $08; LtBlueOnDkGray = Blink + $09; Const DkGrayOnLtBlue = Blink + $18; LtBlueOnLtBlue = Blink + $19; Const DkGrayOnLtGreen = Blink + $28; LtBlueOnLtGreen = Blink + $29; Const DkGrayOnLtCyan = Blink + $38; LtBlueOnLtCyan = Blink + $39; Const DkGrayOnLtRed = Blink + $48; LtBlueOnLtRed = Blink + $49; Const DkGrayOnLtMagenta = Blink + $58; LtBlueOnLtMagenta = Blink + $59; Const DkGrayOnYellow = Blink + $68; LtBlueOnYellow = Blink + $69; Const DkGrayOnWhite = Blink + $78; LtBlueOnWhite = Blink + $79; Const LtGreenOnDkGray = Blink + $0A; LtCyanOnDkGray = Blink + $0B; Const LtGreenOnLtBlue = Blink + $1A; LtCyanOnLtBlue = Blink + $1B; Const LtGreenOnLtGreen = Blink + $2A; LtCyanOnLtGreen = Blink + $2B; Const LtGreenOnLtCyan = Blink + $3A; LtCyanOnLtCyan = Blink + $3B; Const LtGreenOnLtRed = Blink + $4A; LtCyanOnLtRed = Blink + $4B; Const LtGreenOnLtMagenta= Blink + $5A; LtCyanOnLtMagenta = Blink + $5B; Const LtGreenOnYellow = Blink + $6A; LtCyanOnYellow = Blink + $6B; Const LtGreenOnWhite = Blink + $7A; LtCyanOnWhite = Blink + $7B; Const LtRedOnDkGray = Blink + $0C; LtMagentaOnDkGray = Blink + $0D; Const LtRedOnLtBlue = Blink + $1C; LtMagentaOnLtBlue = Blink + $1D; Const LtRedOnLtGreen = Blink + $2C; LtMagentaOnLtGreen= Blink + $2D; Const LtRedOnLtCyan = Blink + $3C; LtMagentaOnLtCyan = Blink + $3D; Const LtRedOnLtRed = Blink + $4C; LtMagentaOnLtRed = Blink + $4D; Const LtRedOnLtMagenta = Blink + $5C; LtMagentaOnLtMagenta= Blink + $5D; Const LtRedOnYellow = Blink + $6C; LtMagentaOnYellow = Blink + $6D; Const LtRedOnWhite = Blink + $7C; LtMagentaOnWhite = Blink + $7D; Const YellowOnDkGray = Blink + $0E; WhiteOnDkGray = Blink + $0F; Const YellowOnLtBlue = Blink + $1E; WhiteOnLtBlue = Blink + $1F; Const YellowOnLtGreen = Blink + $2E; WhiteOnLtGreen = Blink + $2F; Const YellowOnLtCyan = Blink + $3E; WhiteOnLtCyan = Blink + $3F; Const YellowOnLtRed = Blink + $4E; WhiteOnLtRed = Blink + $4F; Const YellowOnLtMagenta = Blink + $5E; WhiteOnLtMagenta = Blink + $5F; Const YellowOnYellow = Blink + $6E; WhiteOnYellow = Blink + $6F; Const YellowOnWhite = Blink + $7E; WhiteOnWhite = Blink + $7F; Var TempStr : String; TempStrLen : Byte Absolute TempStr; Function Exist(fn: str80): Boolean; { Returns True if File fn exists in the current directory } Function ExistsOnPath(Var fn: str80): Boolean; { Returns True if File fn exists in any directory specified in the current } { path and changes fn to a fully qualified path/File. } Function StrUpCase(s : String): String; { Returns an upper Case String from s. Applicable to the English language. } Function StrLowCase(s : String): String; { Returns a String = to s With all upper Case Characters converted to lower } Function Asc2Str(Var s; max: Byte): String; { Converts an ASCIIZ String to a Turbo Pascal String With a maximum length } { of max Characters. } Procedure Str2Asc(s: String; Var ascStr; max: Word); { Converts a TP String to an ASCIIZ String of no more than max length. } { WARNinG: No checks are made that there is sufficient room in destination } { Variable. } Function LastPos(ch: Char; s: String): Byte; { Returns the last position of ch in s } Procedure CheckIO(a: Byte); Implementation Function Exist(fn: str80): Boolean; begin TempStrLen := 0; TempStr := FSearch(fn,''); Exist := TempStrLen <> 0; end; { Exist } Function ExistsOnPath(Var fn: str80): Boolean; begin TempStrLen := 0; TempStr := FSearch(fn,GetEnv('PATH')); ExistsOnPath := TempStrLen <> 0; fn := FExpand(TempStr); end; { ExistsOnPath } Function StrUpCase(s : String): String; Var x : Byte; begin StrUpCase[0] := s[0]; For x := 1 to length(s) do StrUpCase[x] := UpCase(s[x]); end; { StrUpCase } Function StrLowCase(s : String): String; Var x : Byte; begin StrLowCase[0] := s[0]; For x := 1 to length(s) do Case s[x] of 'a'..'z': StrLowCase[x] := chr(ord(s[x]) and $df); else StrLowCase[x] := s[x]; end; { Case } end; { StrLowCase } Function Asc2Str(Var s; max: Byte): String; Var stArray : Array[1..255] of Char Absolute s; len : Integer; begin len := pos(#0,stArray)-1; { Get the length } if (len > max) or (len < 0) then { length exceeds maximum } len := max; { so set to maximum } Asc2Str := stArray; Asc2Str[0] := chr(len); { Set length } end; { Asc2Str } Procedure Str2Asc(s: String; Var ascStr; max: Word); begin FillChar(AscStr,max,0); if length(s) < max then move(s[1],AscStr,length(s)) else move(s[1],AscStr,max); end; { Str2Asc } Function LastPos(ch: Char; s: String): Byte; Var x : Word; begin x := succ(length(s)); Repeat dec(x); Until (s[x] = ch) or (x = 0); end; { LastPos } Procedure CheckIO(a: Byte); Var e : Integer; begin e := Ioresult; if e <> 0 then begin Writeln('I/O error ',e,' section ',a); halt(e); end; end; { CheckIO } end. { Globals }
unit AnnotationsTests; interface uses TestFrameWork, AnnotationsModelIntf; type TAnnotationsTests = class(TTestCase) private FAddress1: IAddress; FAddress2: IAddress; protected procedure SetUp; override; procedure TearDown; override; published procedure TestAnnotate; procedure TestChangeAnnotationProperty; procedure TestIsAnnotationPresent; procedure TestGetAnnotation; procedure TestSupportAnnotation; procedure TestAnnotationByClass; procedure TestAnnotationByInstance; procedure TestIsAnnotation; end; implementation uses SysUtils, InfraCommonIntf, AnnotationsModel; { TAnnotationsTests } procedure TAnnotationsTests.SetUp; begin inherited; TSetupModel.RegisterAddress; TSetupModel.RegisterVersion; FAddress1 := TAddress.Create; with FAddress1 do begin Street.AsString := 'Filiph Street'; City.AsString := 'Filiph City'; Quarter.AsString := 'Filiph Quarter'; Number.AsInteger := 100; end; FAddress2 := TAddress.Create; with FAddress2 do begin Street.AsString := 'John Street'; City.AsString := 'John City'; Quarter.AsString := 'John Quarter'; Number.AsInteger := 2000; end; end; procedure TAnnotationsTests.TearDown; begin TSetupModel.RemoveTypeInfo(IVersion); TSetupModel.RemoveTypeInfo(IAddress); inherited; end; procedure TAnnotationsTests.TestAnnotate; var c: IClassInfo; v: IVersion; begin c := TypeService.GetType(IAddress); CheckFalse(c.isAnnotationPresent(IVersion), 'IAddress não deveria estar anotado com IVersion'); // Anotando TypeInfo de IAddress. v := c.Annotate(IVersion) as IVersion; CheckTrue(Assigned(v), 'Variavel deveria ter uma referencia à anotação IVersion'); CheckTrue(c.isAnnotationPresent(IVersion), 'IAddress deveria estar anotado com IVersion'); CheckEquals('1.0', v.VersionNumber.AsString, 'Valor de IVersion no TypeInfo de IAddres deveria ser 1.0'); end; procedure TAnnotationsTests.TestChangeAnnotationProperty; var c: IClassInfo; v: IVersion; begin c := TypeService.GetType(IAddress); // Anotando TypeInfo de IAddress. v := c.Annotate(IVersion) as IVersion; CheckEquals('1.0', v.VersionNumber.AsString, 'Valor de IVersion no TypeInfo de IAddres deveria ser 1.0'); // Mudando a versão no objeto anotado v.VersionNumber.AsString := '2.0'; CheckEquals('2.0', v.VersionNumber.AsString, 'Valor de IVersion no TypeInfo de IAddres deveria ser 2.0'); end; procedure TAnnotationsTests.TestSupportAnnotation; var c: IClassInfo; begin c := TypeService.GetType(IAddress); CheckFalse(Supports(c, IVersion), 'IAddress não deveria estar anotado com IVersion aqui'); // Anotando TypeInfo de IAddress. c.Annotate(IVersion); CheckTrue(Supports(c, IVersion), 'IAddress deveria estar anotado com IVersion aqui'); CheckEquals('1.0', (c as IVersion).VersionNumber.AsString, 'Valor de IVersion no TypeInfo de IAddres deveria ser 2.0'); end; procedure TAnnotationsTests.TestGetAnnotation; var c: IClassInfo; v: IVersion; begin c := TypeService.GetType(IAddress); v := c.GetAnnotation(IVersion) as IVersion; CheckNull(v, 'IAddress não deveria estar anotado com IVersion aqui'); // Anotando TypeInfo de IAddress. c.Annotate(IVersion); v := c.GetAnnotation(IVersion) as IVersion; CheckNotNull(v, 'IAddress deveria estar anotado com IVersion aqui'); CheckEquals('1.0', v.VersionNumber.AsString, 'Valor de IVersion no TypeInfo de IAddres deveria ser 2.0'); end; procedure TAnnotationsTests.TestIsAnnotationPresent; var c: IClassInfo; begin c := TypeService.GetType(IAddress); CheckFalse(c.isAnnotationPresent(IVersion), 'IAddress não deveria estar presente'); // Anotando TypeInfo de IAddress com IVersion. c.Annotate(IVersion); CheckTrue(c.isAnnotationPresent(IVersion), 'IVersion deveria estar presente'); end; procedure TAnnotationsTests.TestAnnotationByClass; begin end; procedure TAnnotationsTests.TestAnnotationByInstance; begin end; procedure TAnnotationsTests.TestIsAnnotation; var c: IClassInfo; begin c := TypeService.GetType(IAddress); CheckFalse(c.IsAnnotation, 'IAddress não deveria ser uma anotação'); c := TypeService.GetType(IVersion); CheckTrue(c.IsAnnotation, 'IVersion deveria ser uma anotação'); end; initialization TestFramework.RegisterTest('AnnotationsTests Suite', TAnnotationsTests.Suite); end.
unit ParseMath; {$mode objfpc}{$H+} interface uses Classes, SysUtils, math, fpexprpars, Dialogs, Integral; type TParseMath = Class Private FParser: TFPExpressionParser; identifier: array of TFPExprIdentifierDef; Procedure AddFunctions(); Public f:string; Expression: string; function NewValue( Variable:string; Value: Double ): Double; procedure AddVariable( Variable: string; Value: Double ); procedure AddString( Variable: string; Value: string ); function Evaluate( ): Double; constructor create(); destructor destroy; end; implementation constructor TParseMath.create; begin FParser:= TFPExpressionParser.Create( nil ); FParser.Builtins := [ bcMath ]; AddFunctions(); end; destructor TParseMath.destroy; begin FParser.Destroy; end; function TParseMath.NewValue( Variable: string; Value: Double ): Double; begin FParser.IdentifierByName(Variable).AsFloat:= Value; end; function TParseMath.Evaluate(): Double; begin FParser.Expression:= Expression; Result:= ArgToFloat( FParser.Evaluate ); end; function IsNumber(AValue: TExprFloat): Boolean; begin result := not (IsNaN(AValue) or IsInfinite(AValue) or IsInfinite(-AValue)); end; procedure ExprFloor(var Result: TFPExpressionResult; Const Args: TExprParameterArray); // maximo entero var x: Double; begin x := ArgToFloat( Args[ 0 ] ); if x > 0 then Result.ResFloat:= trunc( x ) else Result.ResFloat:= trunc( x ) - 1; end; Procedure ExprTan( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x - 0.5) / pi) <> 0.0) then begin if((tan(x)>xmin) or (tan(x)<-xmin)) then begin Result.resFloat :=NaN; end else if (IsNumber(x) and ((frac(x - 0.5) / pi) <> 0.0)) then begin Result.resFloat := tan(x); end; end else Result.resFloat := NaN; end; Procedure ExprSin( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := sin(x) end; Procedure ExprCos( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := cos(x) end; Procedure ExprLn( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and (x > 0) then Result.resFloat := ln(x) else Result.resFloat := NaN; end; Procedure ExprLog( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and (x > 0) then Result.resFloat := ln(x) / ln(10) else Result.resFloat := NaN; end; Procedure ExprSQRT( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and (x > 0) then Result.resFloat := sqrt(x) else Result.resFloat := NaN; end; Procedure ExprPower( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x,y: Double; begin x := ArgToFloat( Args[ 0 ] ); y := ArgToFloat( Args[ 1 ] ); Result.resFloat := power(x,y); end; //Funciones nuevas Procedure ExprSinh( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := sinh(x) end; //e Procedure ExprCsch( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x-0.5)/pi)<>0.0) then begin if((1/sinh(x)>xmin) or (1/sinh(x)<-xmin)) then begin Result.ResFloat:=NaN; end else if (IsNumber(x) and ((frac(x-0.5)/pi)<>0.0)) then begin Result.resFloat := (1/sinh(x)) end; end else Result.ResFloat:=NaN; //e end; Procedure ExprCosh( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := Cosh(x) //e end; Procedure ExprSech( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := (1/cosh(x)) //e end; Procedure ExprTanh( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := tanh(x) //e end; Procedure ExprCoth( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x-0.5)/pi)<>0.0) then begin if((1/tanh(x)>xmin) or (1/tanh(x)<-xmin)) then begin Result.ResFloat:=NaN; end else if (IsNumber(x) and ((frac(x-0.5)/pi)<>0.0)) then begin Result.resFloat := (1/tanh(x)) end; end else Result.ResFloat:=NaN; //e end; Procedure ExprArcsen( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := Arcsin(x) //e end; Procedure ExprArcCos( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := ArcCos(x) //e end; Procedure ExprArcTan( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; begin x := ArgToFloat( Args[ 0 ] ); Result.resFloat := ArcTan(x) //e end; Procedure ExprSec( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x-0.5)/pi)<>0.0) then begin if((sec(x)>xmin) or (sec(x)<-xmin)) then begin Result.ResFloat:=NaN; end else if (IsNumber(x) and ((frac(x-0.5)/pi)<>0.0)) then begin Result.resFloat := sec(x) end; end else Result.ResFloat:=NaN; //e end; Procedure ExprCsc( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x-0.5)/pi)<>0.0) then begin if((Csc(x) >xmin) or (Csc(x)<-xmin)) then begin Result.ResFloat:=NaN; end else if (IsNumber(x) and ((frac(x-0.5)/pi)<>0.0)) then begin Result.resFloat := Csc(x) end; end else Result.ResFloat:=NaN; //e end; Procedure ExprCot( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var x: Double; xmin:Double; begin xmin:=100; x := ArgToFloat( Args[ 0 ] ); if IsNumber(x) and ((frac(x-0.5)/pi)<>0.0) then begin if((cot(x) >xmin) or (cot(x)<-xmin)) then begin Result.ResFloat:=NaN; end else if (IsNumber(x) and ((frac(x-0.5)/pi)<>0.0)) then begin Result.resFloat := cot(x) end; end else Result.ResFloat:=NaN; //e end; Procedure ExprIntegral( var Result: TFPExpressionResult; Const Args: TExprParameterArray); var a,b,n: Double; Method: string; Integrar:TIntegral; begin a:= ArgToFloat( Args[ 0 ] ); b:= ArgToFloat( Args[ 1 ] ); n:= ArgToFloat( Args[ 2 ] ); Integrar := TIntegral.create; // Result.ResFloat := Integrar.Trapesio2(TParseMath.f,a,b,n); Integrar.Destroy; end; Procedure TParseMath.AddFunctions(); begin with FParser.Identifiers do begin AddFunction('tan', 'F', 'F', @ExprTan); AddFunction('sin', 'F', 'F', @ExprSin); AddFunction('sen', 'F', 'F', @ExprSin); AddFunction('cos', 'F', 'F', @ExprCos); AddFunction('ln', 'F', 'F', @ExprLn); AddFunction('log', 'F', 'F', @ExprLog); AddFunction('sqrt', 'F', 'F', @ExprSQRT); AddFunction('floor', 'F', 'F', @ExprFloor ); AddFunction('power', 'F', 'FF', @ExprPower); //two float arguments 'FF' , returns float //AddFunction('Newton', 'F', 'SF', @ExprNewton ); // Una sring argunmen and one float argument, returns float AddFunction('senh', 'F', 'F', @ExprSinh); AddFunction('csch', 'F', 'F', @ExprCsch); AddFunction('cosh', 'F', 'F', @ExprCosh); AddFunction('sech', 'F', 'F', @ExprSech); AddFunction('tanh', 'F', 'F', @ExprTanh); AddFunction('coth', 'F', 'F', @ExprCoth); AddFunction('arcsen', 'F', 'F', @ExprArcsen); AddFunction('arccos', 'F', 'F', @ExprArcCos); AddFunction('arctan', 'F', 'F', @ExprArcTan); AddFunction('sec', 'F', 'F', @ExprSec); AddFunction('csc', 'F', 'F', @ExprCsc); AddFunction('cot', 'F', 'F', @ExprCot); //Metodos Numericos AddFunction('Integrar', 'F', 'SF', @ExprIntegral); end end; procedure TParseMath.AddVariable( Variable: string; Value: Double ); var Len: Integer; begin Len:= length( identifier ) + 1; SetLength( identifier, Len ) ; identifier[ Len - 1 ]:= FParser.Identifiers.AddFloatVariable( Variable, Value); end; procedure TParseMath.AddString( Variable: string; Value: string ); var Len: Integer; begin Len:= length( identifier ) + 1; SetLength( identifier, Len ) ; identifier[ Len - 1 ]:= FParser.Identifiers.AddStringVariable( Variable, Value); end; end.
unit MainModel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, entities, Graphics, AbstractModel, fphttpclient, Dialogs, fpjson, jsonparser, VKDAO, sqlite3conn, vkcmconfig, DB, sqldb, longpoll, vkcmobserver; type { IMainModel } {Interface for mainview's model with long comments} IMainModel = interface(IModel) {Returns full information about community} function GetExtendedCommunityInformation(CommunityId, AccessKey: string): TCommunity; {Saves community information in local databse} procedure SaveCommunityInfo(Communty: TCommunity); {Reads access keys from local database and loads community information from internet or (in case when there is no internet) from local storage} function GetCommunities: TCommunityList; {Returns photo that is used as avatar for communities with no photo} function GetNoPhotoAvatar: TPicture; {Returns photo for "Add new community" button} function GetAddNewCommunityPhoto: TPicture; {Loads frame image for toolbar} function LoadFrameImage: TPicture; end; { TMainModel } TMainModel = class(TObserverModel, IMainModel, IModel) private Connection: TSQLite3Connection; LongpollWorker: TLongPollWorker; procedure ParseGroupGetByIdResponse(const JSONResponseDocument: TJSONObject; const AccessKey: string; var Community: TCommunity); procedure OnNotified; public constructor Create; function GetExtendedCommunityInformation(CommunityId, AccessKey: string): TCommunity; procedure SaveCommunityInfo(Community: TCommunity); function GetCommunities: TCommunityList; function GetNoPhotoAvatar: TPicture; function GetAddNewCommunityPhoto: TPicture; function LoadFrameImage: TPicture; destructor Destroy; override; end; var LMainModel: TMainModel; implementation { TMainModel } procedure TMainModel.ParseGroupGetByIdResponse(const JSONResponseDocument: TJSONObject; const AccessKey: string; var Community: TCommunity); var JSONCommunityObject: TJSONObject; ResponseArray: TJSONArray; HTTPClient: TFPHTTPClient; begin HTTPClient := TFPHTTPClient.Create(nil); ResponseArray := (JSONResponseDocument['response'] as TJSONArray); JSONCommunityObject := (ResponseArray[0] as TJSONObject); {Serialize} Community.AccessKey := AccessKey; Community.CommunityType := StringToCommunityType( JSONCommunityObject['type'].AsString); if Assigned(JSONCommunityObject.Find('deactivated')) then Community.Deactivated := True else Community.Deactivated := False; Community.HasPhoto := JSONCommunityObject['has_photo'].AsBoolean; Community.Id := JSONCommunityObject['id'].AsString; Community.IsClosed := JSONCommunityObject['is_closed'].AsBoolean; Community.Name := JSONCommunityObject['name'].AsString; Community.ScreenName := JSONCommunityObject['screen_name'].AsString; if Community.HasPhoto then Community.Photo := DAO.LoadPhoto(HTTPClient, JSONCommunityObject['photo_50'].AsString); FreeAndNil(HTTPClient); end; procedure TMainModel.OnNotified; begin Observable.NotifyObservers; end; constructor TMainModel.Create; begin Connection := TSQLite3Connection.Create(nil); Connection.DatabaseName := DATABASE_PATH; if not FileExists(DATABASE_PATH) then try DAO.Database.ExecuteDatabaseCreationScript(Connection); except raise Exception.Create('Ошибка при создании базы'); end; Connection.Open; Observer := TVKCMObserver.Create; Observer.Notify := @OnNotified; Observable := TVKCMObservable.Create; LongpollWorker := TLongPollWorker.Create(True, GetCommunities); LongpollWorker.SubscribeForNotifications(Observer); LongpollWorker.Start; end; function TMainModel.GetExtendedCommunityInformation(CommunityId, AccessKey: string): TCommunity; var JSONResponseDocument: TJSONObject; HTTPClient: TFPHTTPClient; begin HTTPClient := TFPHTTPClient.Create(nil); Result := TCommunity.Create; try JSONResponseDocument := DAO.Groups.GetById(HTTPClient, AccessKey, CommunityId); if Assigned(JSONResponseDocument.Find('error')) then raise Exception.Create('Неправильные Id и/или ключ доступа'); ParseGroupGetByIdResponse(JSONResponseDocument, AccessKey, Result); except raise; end; FreeAndNil(HTTPClient); end; procedure TMainModel.SaveCommunityInfo(Community: TCommunity); begin try DAO.Database.SaveCommunity(Connection, Community); except raise; end; LongpollWorker.FreeOnTerminate := True; LongpollWorker.Terminate; LongpollWorker := TLongPollWorker.Create(True, GetCommunities); LongpollWorker.SubscribeForNotifications(Observer); LongpollWorker.Start; end; function TMainModel.GetCommunities: TCommunityList; var Community: TCommunity; CommunitiesDataset: TDataset; QueryTransaction: TSQLTransaction; i: integer; begin Result := TCommunityList.Create; try CommunitiesDataset := DAO.Database.LoadDatabaseDataset(Connection, QueryTransaction); CommunitiesDataset.Open; CommunitiesDataset.First; for i := 0 to CommunitiesDataset.RecordCount - 1 do begin Community := TCommunity.Create; Community.HasPhoto := CommunitiesDataset.FieldByName('HasPhoto').AsBoolean; if Community.HasPhoto then begin Community.Photo := TPicture.Create; Community.Photo.LoadFromStream(CommunitiesDataset.CreateBlobStream( CommunitiesDataset.FieldByName('Photo'), bmRead)); end; Community.AccessKey := CommunitiesDataset.FieldByName('AccessKey').AsString; Community.CommunityType := StringToCommunityType(CommunitiesDataset.FieldByName('CommunityType').AsString); Community.Deactivated := CommunitiesDataset.FieldByName('Deactivated').AsBoolean; Community.Id := CommunitiesDataset.FieldByName('Id').AsString; Community.IsClosed := CommunitiesDataset.FieldByName('IsClosed').AsBoolean; Community.Name := CommunitiesDataset.FieldByName('Name').AsString; Community.ScreenName := CommunitiesDataset.FieldByName('ScreenName').AsString; Community.Chatbot.FillFromString(CommunitiesDataset.FieldByName( 'SerializedChatBot').AsString); Result.Add(Community); CommunitiesDataset.Next; end; FreeAndNil(CommunitiesDataset); FreeAndNil(QueryTransaction); finally DatabaseCS.Leave; end; end; function TMainModel.GetNoPhotoAvatar: TPicture; begin Result := TPicture.Create; Result.LoadFromFile('img/noavatar.bmp'); end; function TMainModel.GetAddNewCommunityPhoto: TPicture; begin Result := TPicture.Create; Result.LoadFromFile('img/newuser.bmp'); end; function TMainModel.LoadFrameImage: TPicture; begin Result := TPicture.Create; Result.LoadFromFile('img/frame.bmp'); end; destructor TMainModel.Destroy; begin Connection.Close(); FreeAndNil(Connection); LongpollWorker.Terminate; LongpollWorker.WaitFor; FreeAndNil(LongpollWorker); inherited Destroy; end; end.
// **************************************************************************** // * mxProtector component for Delphi. // **************************************************************************** // * Copyright 2001-2003, Bitvadász Kft. All Rights Reserved. // **************************************************************************** // * Feel free to contact me if you have any questions, comments or suggestions // * at support@maxcomponents.net // **************************************************************************** // * Web page: www.maxcomponents.net // **************************************************************************** // * Date last modified: 18.06.2003 // **************************************************************************** // * TmxProtector v1.30 // **************************************************************************** // * Description: // * // * You can add protection to your applications. // * // **************************************************************************** Unit mxProtectorReg; Interface {$I MAX.INC} // ************************************************************************************* // ** Component registration // ************************************************************************************* Procedure Register; Implementation // ************************************************************************************* // ** List of used units // ************************************************************************************* Uses SysUtils, Classes, {$IFDEF Delphi6_Up} DesignIntf, DesignEditors, {$ELSE} Dsgnintf, {$ENDIF} Dialogs, Forms, mxProtector, mxProtectorAbout; Type TDesigner = IDesigner; {$IFDEF Delphi6_Up} TFormDesigner = IDesigner; {$ELSE} TFormDesigner = IFormDesigner; {$ENDIF} // ************************************************************************************* // ** Component Editor // ************************************************************************************* TmxProtectorEditor = Class( TComponentEditor ) Function GetVerbCount: integer; Override; Function GetVerb( Index: integer ): String; Override; Procedure ExecuteVerb( Index: integer ); Override; End; // ************************************************************************************* // ** GetVerbCount // ************************************************************************************* Function TmxProtectorEditor.GetVerbCount: integer; Begin Result := 3; End; // ************************************************************************************* // ** GetVerb // ************************************************************************************* Function TmxProtectorEditor.GetVerb( Index: integer ): String; Begin Case Index Of 0: Result := 'TmxProtector (C) 2001-2002 Bitvadász Kft.'; 1: Result := '-'; 2: Result := 'Generate serial number for UserName'; End; End; // ************************************************************************************* // ** ExecuteVerb // ************************************************************************************* Procedure TmxProtectorEditor.ExecuteVerb( Index: integer ); Var mxProtector: TmxProtector; Serial: String; Begin Case Index Of 0: ShowAboutBox( 'TmxProtector' ); 2: Begin mxProtector := ( Component As TmxProtector ); With mxProtector Do Begin Serial := GenerateSerialNumber( UserName ); If Serial <> '' Then MessageDlg( 'Your new serial number is: ' + Serial, mtInformation, [ mbOK ], 0 ); End; End; End; End; // ************************************************************************************* // ** Register, 4/5/01 11:46:42 AM // ************************************************************************************* Procedure Register; Begin RegisterComponents( 'Max', [ TmxProtector ] ); RegisterComponentEditor( TmxProtector, TmxProtectorEditor ); End; End.
unit Lebtn; interface Uses wintypes,SysUtils,Classes,Controls,ExtCtrls,LblEdit, BMPBtn,Menus,Messages,SQLCtrls,DBTables,TSQLCls; Type TLabelEditBmpBtn=class(TSQLControl) protected substr:string; CurrentOfs:integer; FTable:TSQLString; FID:TSQLString; FInfo:TSQLString; FWhere:string; fInfoField:String; fData:longint; fOnChangeData:TNotifyEvent; procedure WriteCaption(s:string); Function ReadCaption:String; procedure WriteBmpFile(s:string); Function ReadBmpFile:String; procedure WritePC(s:boolean); Function ReadPC:boolean; procedure WriteRO(s:boolean); Function ReadRO:boolean; procedure WriteML(s:integer); Function ReadML:integer; procedure WriteData(s:longint); procedure WriteText(s:string); Function ReadText:string; procedure KeyPress(Sender:TObject;var Key:char); procedure KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnLabelEditExit(Sender:TObject); public PrevData:longint; PrevInfo:string; LabelEdit:TLabelEdit; Parm:Longint; Button:TBMPBtn; FOnBtnClick:TNotifyEvent; procedure BtnClick(Sender:TObject); constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure WMSize(var Msg:TMessage); message WM_SIZE; function GetHeight:integer; procedure Value(sl:TStringList); override; procedure SetValue(var q:TQuery); override; procedure Clear; procedure OnLabelEnter(Sender:TObject); published property Caption:String read ReadCaption write WriteCaption; property InfoField:string read fInfoField write fInfoField; property Table:TSQLString read fTable write fTable; property ID:TSQLString read fID write fID; property Info:TSQLString read fInfo write fInfo; property Where:string read fWhere write fWhere; property BmpFile:String read ReadBmpFile write WriteBmpFile; property ParentColor:boolean read ReadPC write WritePC; property ReadOnly:boolean read ReadRO write WriteRO; property MaxLength:integer read ReadML write WriteML; property Text:string read ReadText write WriteText; property Data:longint read fData write WriteData; property OnChangeData:TNotifyEvent read fOnChangeData write fOnChangeData; property Height default 70; property Width default 100; property Align; property DragCursor; property DragMode; property Enabled; property ParentCtl3D; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnButtonClick:TNotifyEvent read FOnBtnClick write FOnBtnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; end; procedure Register; implementation function TLabelEditBMPBtn.GetHeight:integer; begin GetHeight:=-LabelEdit.Edit.Font.Height+13-LabelEdit.Lbl.Font.Height end; destructor TLabelEditBMPBtn.Destroy; begin LabelEdit.Free; Button.Free; inherited Destroy; end; constructor TLabelEditBMPBtn.Create(AOwner:TComponent); begin fInfoField:=''; inherited create(AOwner); LabelEdit:=TLabelEdit.Create(self); Button:=TBMPBtn.Create(self); Button.OnClick:=BtnClick; LabelEdit.Parent:=self; Button.Parent:=self; PrevInfo:=''; PrevData:=0; LabelEdit.Edit.OnKeyPress:=KeyPress; LabelEdit.Edit.OnKeyDown:=KeyDown; CurrentOfs:=0; Button.NumGlyphs:=3; LabelEdit.OnExit:=OnLabelEditExit end; procedure TLabelEditBMPBtn.WMSize(var Msg:TMessage); begin LabelEdit.Lbl.Height:=-LabelEdit.Lbl.Font.Height+3; LabelEdit.Edit.Height:=-LabelEdit.Edit.Font.Height+10; LabelEdit.Height:=LabelEdit.Edit.Height+LabelEdit.Lbl.Height+1; LabelEdit.Width:=Msg.LParamLo-LabelEdit.Edit.Height; Button.Left:=LabelEdit.Width; Button.Top:=LabelEdit.Height-LabelEdit.Edit.Height; Button.Height:=LabelEdit.Edit.Height-1; Button.Width:=LabelEdit.Edit.Height-1; ClientHeight:=LabelEdit.Height; ClientWidth:=Msg.LParamLo end; procedure TLabelEditBMPBtn.WriteCaption(s:String); begin LabelEdit.Caption:=s end; function TLabelEditBMPBtn.ReadCaption:String; begin ReadCaption:=LabelEdit.Caption end; procedure TLabelEditBMPBtn.WriteBMPFile(s:String); begin Button.FileName:=s end; function TLabelEditBMPBtn.ReadBMPFile:String; begin ReadBMPFile:=Button.FileName end; procedure TLabelEditBMPBtn.BtnClick(Sender:TObject); begin if Sender=Button then if Assigned(FOnBtnClick) then FOnBtnClick(self); end; procedure TLabelEditBmpBtn.WritePC(s:boolean); begin LabelEdit.ParentColor:=s end; function TLabelEditBmpBtn.ReadPC:boolean; begin ReadPC:=LabelEdit.ParentColor end; procedure TLabelEditBmpBtn.WriteRO(s:boolean); begin LabelEdit.ReadOnly:=s end; function TLabelEditBmpBtn.ReadRO:boolean; begin ReadRO:=LabelEdit.ReadOnly end; procedure TLabelEditBmpBtn.WriteML(s:integer); begin LabelEdit.MaxLength:=s end; function TLabelEditBmpBtn.ReadML:integer; begin ReadML:=LabelEdit.MaxLength end; procedure TLabelEditBmpBtn.Value(sl:TStringList); begin if Assigned(fValueEvent) then fValueEvent(self,sl) else if Data=0 then sl.Add('NULL') else sl.Add(IntToStr(Data)); end; procedure TLabelEditBmpBtn.SetValue(var q:TQuery); begin if Assigned(fSetValueEvent) then fSetValueEvent(self,q) else begin Data:=q.FieldByName(fFieldName).AsInteger; if fInfoField<>'' then LabelEdit.Text:=q.FieldByName(fInfoField).AsString; end end; procedure TLabelEditBmpBtn.Clear; begin LabelEdit.Text:=''; Data:=0 end; procedure TLabelEditBmpBtn.WriteData(s:longint); var q:TQuery; b:boolean; begin b:=s<>Data; if (Table<>'') and (ID<>'') and (Info<>'') and b then begin if s=0 then begin fData:=0; LabelEdit.Text:='' end else begin q:=sql.Select(Table,sql.Keyword(Info)+','+sql.Keyword(ID), sql.CondIntEqu(ID,s),''); if not q.eof then begin fData:=s; LabelEdit.Text:=q.FieldByName(Info).AsString end; q.Free end end else fData:=s; if b and Assigned(fOnChangeData) then OnChangeData(self); end; procedure TLabelEditBmpBtn.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoMove(ofs:integer); var q:TQuery; begin Key:=0; if (Table<>'') and (ID<>'') and (Info<>'') and (CurrentOfs+ofs>=0) then begin q:=sql.Select(Table,sql.Keyword(Info)+','+sql.Keyword(ID), sql.CondLike(Info,sql.MakeStr(substr+'%'),1),sql.Keyword(Info)); if not q.eof then q.MoveBy(CurrentOfs+ofs); if not q.eof then begin CurrentOfs:=CurrentOfs+ofs; Data:=q.FieldByName(ID).AsInteger; LabelEdit.Edit.SelStart:=0; LabelEdit.Edit.SelLength:=length(substr) end; q.Free; end; end; begin if Key=vk_up then DoMove(-1); if Key=vk_Down then DoMove(1); end; procedure TLabelEditBmpBtn.KeyPress(Sender:TObject;var Key:char); var q:TQuery; s:string; begin if (Table<>'') and (ID<>'') and (Info<>'') then begin case Key of #27: begin LabelEdit.Text:=PrevInfo; Data:=PrevData; substr:=''; end; else begin if Key<>#8 then s:=substr+Key else s:=Copy(substr,1,length(substr)-1); if s='' then begin Data:=0; substr:=s; end else begin q:=sql.Select(Table,sql.Keyword(Info)+','+sql.Keyword(ID), sql.CondLike(Info,sql.MakeStr(s+'%'),1),sql.Keyword(Info)); if not q.eof then begin Data:=q.FieldByName(ID).AsInteger; substr:=s; CurrentOfs:=0; end; q.Free; end; Key:=#0 end end; LabelEdit.Edit.SelStart:=0; LabelEdit.Edit.SelLength:=length(substr) end; end; procedure TLabelEditBmpBtn.OnLabelEnter(Sender:TObject); begin PrevInfo:=LabelEdit.Text; PrevData:=Data; end; procedure TLabelEditBmpBtn.OnLabelEditExit(Sender:TObject); begin substr:=''; LabelEdit.Edit.SelStart:=0; LabelEdit.Edit.SelLength:=length(substr) end; procedure TLabelEditBmpBtn.WriteText(s:string); begin LabelEdit.Text:=s end; Function TLabelEditBmpBtn.ReadText:string; begin ReadText:=LabelEdit.Text end; procedure Register; begin RegisterComponents('MyOwn',[TLabelEditBMPBtn]) end; end.
unit TextEditor.Minimap.Indicator; interface uses System.Classes, TextEditor.Types; type TTextEditorMinimapIndicator = class(TPersistent) strict private FAlphaBlending: Byte; FOnChange: TNotifyEvent; FOptions: TTextEditorMinimapIndicatorOptions; procedure DoChange; procedure SetAlphaBlending(const AValue: Byte); public constructor Create; procedure Assign(ASource: TPersistent); override; procedure SetOption(const AOption: TTextEditorMinimapIndicatorOption; const AEnabled: Boolean); property OnChange: TNotifyEvent read FOnChange write FOnChange; published property AlphaBlending: Byte read FAlphaBlending write SetAlphaBlending default 96; property Options: TTextEditorMinimapIndicatorOptions read FOptions write FOptions default []; end; implementation constructor TTextEditorMinimapIndicator.Create; begin inherited; FAlphaBlending := 96; FOptions := []; end; procedure TTextEditorMinimapIndicator.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorMinimapIndicator) then with ASource as TTextEditorMinimapIndicator do begin Self.FAlphaBlending := FAlphaBlending; Self.FOptions := FOptions; Self.DoChange; end else inherited Assign(ASource); end; procedure TTextEditorMinimapIndicator.SetOption(const AOption: TTextEditorMinimapIndicatorOption; const AEnabled: Boolean); begin if AEnabled then Include(FOptions, AOption) else Exclude(FOptions, AOption); end; procedure TTextEditorMinimapIndicator.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TTextEditorMinimapIndicator.SetAlphaBlending(const AValue: Byte); begin if FAlphaBlending <> AValue then begin FAlphaBlending := AValue; DoChange; end; end; end.
unit LogConst; {$mode objfpc}{$H+} interface const logExtension = 'csv'; //< Расширение файла журнала. msgDelimiter = ';'; //< Разделитель параметров в сообщении журнала. msgEOL = #13#10; //< Признак конца строки. defFileLogPrx = 'filelog'; //< Префикс файла лога defFileLogExt = '.log'; //< Расширение файла лога defFileMaxSize = 1048576; //< Максимальный размер лог-файла по умолчанию. implementation end.
unit ManSoy.MsgBox; interface uses Winapi.Windows, System.SysUtils; function InfoMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; function WarnMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; function ErrMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; function AskMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; implementation function InfoMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; var sMsg: string; begin sMsg := System.SysUtils.Format(Format, Args, FormatSettings); Result := MessageBox(hWnd, PWideChar(sMsg), 'Ìáʾ', MB_ICONINFORMATION); end; function WarnMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; var sMsg: string; begin sMsg := System.SysUtils.Format(Format, Args, FormatSettings); Result := MessageBox(hWnd, PWideChar(sMsg), '¾¯¸æ', MB_ICONWARNING); end; function ErrMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; var sMsg: string; begin sMsg := System.SysUtils.Format(Format, Args, FormatSettings); Result := MessageBox(hWnd, PWideChar(sMsg), '´íÎó', MB_ICONERROR); end; function AskMsg(hWnd: HWND; const Format: string; const Args: array of const): Integer; var sMsg: string; begin sMsg := System.SysUtils.Format(Format, Args, FormatSettings); Result := MessageBox(hWnd, PWideChar(sMsg), 'ѯÎÊ', MB_YESNO or MB_ICONQUESTION); end; end.
unit RoutingTestCase1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry; type TTestCase1 = class(TTestCase) published procedure TestAddRectDisjointArea; procedure TestRemoveRectDisjointArea; procedure TestAdjacenceGraph; procedure TestHookUp4; end; implementation uses Types, Routing; const DisjointArea: array[1..3] of TRect = ( (Left: 1; Top: 1; Right: 5; Bottom: 5), (Left: 6; Top: 6; Right: 50; Bottom: 50), (Left: 100; Top: 100; Right: 500; Bottom: 500) ); JointArea: array[1..4] of TRect = ( (Left: 1; Top: 1; Right: 5; Bottom: 5), (Left: 6; Top: 6; Right: 50; Bottom: 50), (Left: 100; Top: 100; Right: 500; Bottom: 500), (Left: 5; Top: 5; Right: 7; Bottom: 50) ); {JointAreaAdjacenceGraph: array[1..3] of TIndex = ( (), (), () );} var B: TArea; function BuildArea(const A: array of TRect): TArea; var i: TIndex; o: Integer; begin SetLength(Result, Length(A)); o := Low(A) - Low(Result); for i := Low(Result) to High(Result) do begin Result[i] := A[i + o]; end; end; procedure TTestCase1.TestAddRectDisjointArea; var i: TIndex; begin AssertNull('Area not empty ' + hexStr(Pointer(B)) + 'h', Pointer(B)); for i := Low(DisjointArea) to High(DisjointArea) do begin AddRect(B, DisjointArea[i]); AssertEquals(i, Length(B)); end; end; procedure TTestCase1.TestRemoveRectDisjointArea; var R: TRect; i: TIndex; begin for i := Low(DisjointArea) to High(DisjointArea) do begin RemoveRect(B, DisjointArea[i]); AssertEquals('Remove [' + IntToStr(i) + ']', Length(DisjointArea) - i, Length(B)); end; AssertNull('Area not empty ' + hexStr(Pointer(B)) + 'h', Pointer(B)); end; procedure TTestCase1.TestAdjacenceGraph; var G: TAdjacenceGraph; A: TArea; i: TIndex; begin A := BuildArea(DisjointArea); G := AdjacenceGraph(A); AssertEquals('Invalid graph length', Length(DisjointArea), Length(G)); for i := Low(G) to High(G) do begin AssertEquals('Invalid adjacent list for [' + IntToStr(i) + '] length', 0, Length(G[i])); end; end; procedure TTestCase1.TestHookUp4; begin end; initialization RegisterTest(TTestCase1); end.
unit uRegistry; interface uses System.Classes, Winapi.Windows, Datasnap.DBClient, Data.DB, System.SysUtils, System.Win.Registry; type TRegistry = class private FRegistry: System.Win.Registry.TRegistry; FProgramList: TClientDataSet; function getListKeys: TStringList; procedure CreateProgramList; procedure DeleteProgramList; function ValidRegistry: Boolean; public constructor Create; destructor Destroy; override; function InstalledPragrams: TClientDataSet; end; const cDisplayName = 'DisplayName'; cDisplayVersion = 'DisplayVersion'; cPublisher = 'Publisher'; implementation const cUninstallPath = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'; { TRegistry } constructor TRegistry.Create; begin Self.FRegistry := System.Win.Registry.TRegistry.Create; Self.CreateProgramList; end; destructor TRegistry.Destroy; begin Self.FProgramList.Free; Self.FRegistry.Free; inherited; end; procedure TRegistry.CreateProgramList; begin Self.FProgramList := TClientDataSet.Create(nil); Self.FProgramList.FieldDefs.Add(cDisplayName, ftString, 500); Self.FProgramList.FieldDefs.Add(cDisplayVersion, ftString, 500); Self.FProgramList.FieldDefs.Add(cPublisher, ftString, 500); Self.FProgramList.CreateDataSet; Self.FProgramList.IndexFieldNames := cDisplayName; end; procedure TRegistry.DeleteProgramList; begin while (Self.FProgramList.RecordCount > 0) do Self.FProgramList.Delete; end; function TRegistry.getListKeys: TStringList; begin Result := TStringList.Create; if (Self.FRegistry.OpenKeyReadOnly(cUninstallPath)) then begin try Self.FRegistry.GetKeyNames(Result); finally Self.FRegistry.CloseKey; end; end; end; function TRegistry.InstalledPragrams: TClientDataSet; var oListKey: TStringList; cKey: string; begin Self.FRegistry.RootKey := HKEY_LOCAL_MACHINE; Self.DeleteProgramList; oListKey := Self.getListKeys; try for cKey in oListKey do begin if (not Self.FRegistry.OpenKeyReadOnly(cUninstallPath+'\'+cKey)) then Continue; if (Self.ValidRegistry) then begin Self.FProgramList.Insert; Self.FProgramList.FieldByName(cDisplayName).AsString := Self.FRegistry.ReadString(cDisplayName).Trim; Self.FProgramList.FieldByName(cDisplayVersion).AsString := Self.FRegistry.ReadString(cDisplayVersion).Trim; Self.FProgramList.FieldByName(cPublisher).AsString := Self.FRegistry.ReadString(cPublisher).Trim; Self.FProgramList.Post; end; Self.FRegistry.CloseKey; end; finally oListKey.Free; end; Result := Self.FProgramList; end; function TRegistry.ValidRegistry: Boolean; begin Result := Self.FRegistry.ReadString(cDisplayName).Trim <> EmptyStr; end; end.
{$include kode.inc} unit syn_perc_env; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type synPerc_Env = class private FCurrent : Single; FTarget : Single; FSpeed : Single; public constructor create; destructor destroy; override; procedure setCurrent(AValue:Single); procedure setTarget(AValue:Single); procedure setSpeed(AValue:Single); procedure trigger(AStart,AEnd,ASpeed:Single); function process : Single; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses kode_math; //---------- constructor synPerc_Env.create; begin inherited; FCurrent := 0; FTarget := 0; FSpeed := 0; end; //---------- destructor synPerc_Env.destroy; begin inherited; end; //---------- procedure synPerc_Env.setCurrent(AValue:Single); begin FCurrent := AValue; end; //---------- procedure synPerc_Env.setTarget(AValue:Single); begin FTarget := AValue; end; //---------- procedure synPerc_Env.setSpeed(AValue:Single); begin FSpeed := AValue; end; //---------- procedure synPerc_Env.trigger(AStart,AEnd,ASpeed:Single); begin FCurrent := AStart; FTarget := AEnd; FSpeed := ASpeed; end; //---------- function synPerc_Env.process : Single; begin FCurrent += ((FTarget - FCurrent) * FSpeed); FCurrent := KKillDenorm(FCurrent); result := FCurrent; end; //---------------------------------------------------------------------- end.
unit Repositorio.Base; interface uses Classes, Repositorio.GenericRepository, Repositorio.Interfaces.Base, DB, Context, EF.Engine.DbSet, EF.Mapping.Base; type {$M+} TRepositoryBase<T:TEntitybase> = Class(TInterfacedPersistent, IRepositoryBase<T>) private FRefCount: integer; protected _RepositoryBase: IRepository<T>; function dbContext: TContext<T>;virtual; public Constructor Create(dbContext:TContext<T>);virtual; procedure RefreshDataSet; virtual; function LoadDataSet(iId:Integer; Fields: string = ''): TDataSet;virtual; function Load(iId: Integer = 0): T;virtual; procedure Delete;virtual; procedure AddOrUpdate( State: TEntityState);virtual; procedure Commit;virtual; function GetEntity: T; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; End; {$M-} implementation uses Winapi.Windows; procedure TRepositoryBase<T>.AddOrUpdate(State: TEntityState); begin _RepositoryBase.AddOrUpdate(State); end; procedure TRepositoryBase<T>.Commit; begin _RepositoryBase.Commit; end; procedure TRepositoryBase<T>.Delete; begin _RepositoryBase.Delete; end; function TRepositoryBase<T>.GetEntity: T; begin result:= dbContext.Entity as T; end; function TRepositoryBase<T>.dbContext: TContext<T>; begin result:= _RepositoryBase.dbContext; end; constructor TRepositoryBase<T>.Create(dbContext: TContext<T>); begin inherited Create; end; function TRepositoryBase<T>.LoadDataSet(iId: Integer; Fields: string = ''): TDataSet; begin result := _RepositoryBase.LoadDataSet(iId, Fields) end; function TRepositoryBase<T>.Load(iId: Integer): T; begin result := _RepositoryBase.Load(iId) end; procedure TRepositoryBase<T>.RefreshDataSet; begin _RepositoryBase.RefreshDataSet; end; function TRepositoryBase<T>._AddRef: Integer; begin Result := inherited _AddRef; InterlockedIncrement(FRefCount); end; function TRepositoryBase<T>._Release: Integer; begin Result := inherited _Release; InterlockedDecrement(FRefCount); if FRefCount <=0 then Free; end; end.
unit DispatcherModbusSlaveConnectionClasses; {$mode objfpc}{$H+} interface uses Classes, SyncObjs, MBDefine, DispatcherModbusItf, DispatcherDictionaryesClasses, DispatcherMBSlavePollingThreadClasses, DispatcherMBSlavePollingItemClasses, LoggerItf; type { Объект соединения с Modbus TCP устройством. Возможные исключения: при добавлении объекта-запроса если запрашивается функция не поддерживаемая на данный момент. } TMBSlaveConnection = class(TComponentLogged,IMBSlaveConnectionItf) private FCSection : TCriticalSection; FPollingItemDictinary : TDictionaryTCPItemObject; FPollingThread : TMBSlavePollingThread; FConnectionParam : TMBTCPSlavePollingParam; procedure StopPollingThread; procedure StartPollingThread; function GetPollingItemCount: Cardinal; protected procedure SetLogger(const Value: IDLogger); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; // управление списком устройств для мониторинга procedure AddPollingItem(ItemProp: TMBTCPSlavePollingItem; CallBack: IMBDispCallBackItf); stdcall; procedure DelPollingItem(ItemProp : TMBTCPSlavePollingItem); stdcall; procedure ClearPollingList; stdcall; // запуск/остановка мониторинга всех устройств procedure StartAll; stdcall; procedure StopAll; stdcall; function GetActive: Boolean; stdcall; // активация/деактивация устройства для мониторинга procedure Activate(ItemProp : TMBTCPSlavePollingItem); stdcall; procedure Deactivate(ItemProp : TMBTCPSlavePollingItem); stdcall; procedure SetConnectionParam(const Value: TMBTCPSlavePollingParam); stdcall; property PollingItemsCount : Cardinal read GetPollingItemCount; property ConnectionParam : TMBTCPSlavePollingParam read FConnectionParam write SetConnectionParam; end; TMBSlaveConnectionsArray = array of TMBSlaveConnection; implementation uses sysutils; { TMBSlaveConnection } constructor TMBSlaveConnection.Create(AOwner : TComponent); begin inherited Create(AOwner); FCSection := TCriticalSection.Create; FPollingItemDictinary := TDictionaryTCPItemObject.Create; FPollingThread := nil; end; destructor TMBSlaveConnection.Destroy; begin if Assigned(FPollingThread) then StopPollingThread; FreeAndNil(FCSection); FreeAndNil(FPollingItemDictinary); inherited; end; procedure TMBSlaveConnection.StopPollingThread; begin if not Assigned(FPollingThread) then Exit; FPollingThread.Terminate; FPollingThread.WaitFor; FreeAndNil(FPollingThread); end; procedure TMBSlaveConnection.StartPollingThread; begin if Assigned(FPollingThread) then Exit; FPollingThread := TMBSlavePollingThread.Create(True);//,65535); FPollingThread.Logger := Logger; FPollingThread.CSection := FCSection; FPollingThread.ItemDictinary := FPollingItemDictinary; FPollingThread.ConnectionParam := FConnectionParam; FPollingThread.Start; end; function TMBSlaveConnection.GetActive: Boolean; stdcall; begin Result := False; FCSection.Enter; try Result := Assigned(FPollingThread); finally FCSection.Leave; end; end; function TMBSlaveConnection.GetPollingItemCount: Cardinal; begin Result := FPollingItemDictinary.Count; end; procedure TMBSlaveConnection.DelPollingItem(ItemProp: TMBTCPSlavePollingItem); stdcall; begin FCSection.Enter; try FPollingItemDictinary.Remove(ItemProp); if FPollingItemDictinary.Count = 0 then begin StopPollingThread; end; finally FCSection.Leave; end; end; procedure TMBSlaveConnection.ClearPollingList; stdcall; begin FCSection.Enter; try StopPollingThread; FPollingItemDictinary.Clear; finally FCSection.Leave; end; end; procedure TMBSlaveConnection.AddPollingItem(ItemProp: TMBTCPSlavePollingItem; CallBack: IMBDispCallBackItf); stdcall; var TempItem : TMBSlavePollingItem; begin FCSection.Enter; try if not FPollingItemDictinary.TryGetValue(ItemProp, TObject(TempItem)) then begin TempItem := TMBSlavePollingItem.Create(ItemProp); FPollingItemDictinary.Add(ItemProp,TempItem); TempItem.AddCallBackItf(CallBack); end; finally FCSection.Leave; end; end; procedure TMBSlaveConnection.SetConnectionParam(const Value: TMBTCPSlavePollingParam); stdcall; begin FConnectionParam := Value; if Assigned(FPollingThread) then FPollingThread.ConnectionParam := FConnectionParam; end; procedure TMBSlaveConnection.SetLogger(const Value: IDLogger); begin inherited SetLogger(Value); FPollingItemDictinary.Logger := Logger; if Assigned(FPollingThread) then FPollingThread.Logger := Logger; end; procedure TMBSlaveConnection.Activate(ItemProp: TMBTCPSlavePollingItem); stdcall; var TempItem : TMBSlavePollingItem; begin FCSection.Enter; try if not FPollingItemDictinary.TryGetValue(ItemProp, TObject(TempItem)) then Exit; TempItem.Active := True; finally FCSection.Leave; end; end; procedure TMBSlaveConnection.Deactivate(ItemProp: TMBTCPSlavePollingItem); stdcall; var TempItem : TMBSlavePollingItem; begin FCSection.Enter; try if not FPollingItemDictinary.TryGetValue(ItemProp, TObject(TempItem)) then Exit; TempItem.Active := False; finally FCSection.Leave; end; end; procedure TMBSlaveConnection.StartAll; stdcall; begin StartPollingThread; end; procedure TMBSlaveConnection.StopAll; stdcall; begin StopPollingThread; end; end.
unit crc32; interface function CalculateCrc32(buf: array of Byte; len: Cardinal): Cardinal; implementation const crc32_tab: array[0..255] of Cardinal =( $00000000, $77073096, $ee0e612c, $990951ba,{0} $076dc419, $706af48f, $e963a535, $9e6495a3,{1} $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988,{2} $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91,{3} $1db71064, $6ab020f2, $f3b97148, $84be41de,{4} $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7,{5} $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec,{6} $14015c4f, $63066cd9, $fa0f3d63, $8d080df5,{7} $3b6e20c8, $4c69105e, $d56041e4, $a2677172,{8} $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b,{9} $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940,{10} $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59,{11} $26d930ac, $51de003a, $c8d75180, $bfd06116,{12} $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f,{13} $2802b89e, $5f058808, $c60cd9b2, $b10be924,{14} $2f6f7c87, $58684c11, $c1611dab, $b6662d3d,{15} $76dc4190, $01db7106, $98d220bc, $efd5102a,{16} $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433,{17} $7807c9a2, $0f00f934, $9609a88e, $e10e9818,{18} $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01,{19} $6b6b51f4, $1c6c6162, $856530d8, $f262004e,{20} $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457,{21} $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c,{22} $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65,{23} $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2,{24} $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb,{25} $4369e96a, $346ed9fc, $ad678846, $da60b8d0,{26} $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9,{27} $5005713c, $270241aa, $be0b1010, $c90c2086,{28} $5768b525, $206f85b3, $b966d409, $ce61e49f,{29} $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4,{30} $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad,{31} $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a,{32} $ead54739, $9dd277af, $04db2615, $73dc1683,{33} $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8,{34} $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1,{35} $f00f9344, $8708a3d2, $1e01f268, $6906c2fe,{36} $f762575d, $806567cb, $196c3671, $6e6b06e7,{37} $fed41b76, $89d32be0, $10da7a5a, $67dd4acc,{38} $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5,{39} $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252,{40} $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b,{41} $d80d2bda, $af0a1b4c, $36034af6, $41047a60,{42} $df60efc3, $a867df55, $316e8eef, $4669be79,{43} $cb61b38c, $bc66831a, $256fd2a0, $5268e236,{44} $cc0c7795, $bb0b4703, $220216b9, $5505262f,{45} $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04,{46} $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d,{47} $9b64c2b0, $ec63f226, $756aa39c, $026d930a,{48} $9c0906a9, $eb0e363f, $72076785, $05005713,{49} $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38,{50} $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21,{51} $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e,{52} $81be16cd, $f6b9265b, $6fb077e1, $18b74777,{53} $88085ae6, $ff0f6a70, $66063bca, $11010b5c,{54} $8f659eff, $f862ae69, $616bffd3, $166ccf45,{55} $a00ae278, $d70dd2ee, $4e048354, $3903b3c2,{56} $a7672661, $d06016f7, $4969474d, $3e6e77db,{57} $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0,{58} $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9,{59} $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6,{60} $bad03605, $cdd70693, $54de5729, $23d967bf,{61} $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94,{62} $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d);{63} function CalculateCrc32(buf: array of Byte; len: Cardinal): Cardinal; var i: Integer; begin Result:=$ffffffff; for i:=0 to len-1 do begin Result := (Result shr 8) xor crc32_tab[(Result and $ff) xor buf[i]]; end; Result:= Result xor $ffffffff; end; end.
unit cmpTwain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, unitCallbackComponent, Twain_Wilson, SyncObjs; {.$DEFINE DEBUG} {.$DEFINE SELECT_FORMAT} // Setting image format is currently not working. type TOnImage = procedure (sender : TObject; bitmap : TBitmap; var release : boolean) of object; // Event: OnScanningDone - Called when scanning finishes TOnScanningDone = procedure (sender : TObject; ImageScanned: Boolean) of object; TTransferFormat = (tfBmp, tfJpg, tfTiff); TcwTwain = class(TCallbackComponent) private fActive: boolean; fOpen : boolean; fEnabled : boolean; fAppID : TW_IDENTITY; fSourceID : TW_IDENTITY; fOnImage: TOnImage; {$IFDEF SELECT_FORMAT} fTransferFormat: TTransferFormat; {$ENDIF} {$IFNDEF FPC} fWindowList : pointer; {$ELSE} fWindowList : TList; {$ENDIF} fActiveWindow : HWND; fPict : TPicture; // jgb here instead of private as a test FOnScanningDone: TOnScanningDone; FImageAvailable: Boolean; procedure SetActive(const Value: boolean); procedure SetOpen (const Value : boolean); procedure SetCapability (capability, value : Integer); // Silence a warning about HasCapability never being used. //function HasCapability (capability, value : Integer) : boolean; procedure SetTransferCount (value : Integer); procedure TransferImage; {$IFDEF SELECT_FORMAT} procedure SetTransferFormat(const Value: TTransferFormat); {$ENDIF} function TwainCheck (code : Integer) : Integer; protected procedure WndProc (var Msg : TMessage); override; public destructor Destroy; override; function SelectSource : boolean; procedure GetSingleImage (parent : TWinControl; pict : TPicture); { Public declarations } published {$IFDEF SELECT_FORMAT} property TransferFormat : TTransferFormat read fTransferFormat write SetTransferFormat; {$ENDIF} property OnImage : TOnImage read fOnImage write fOnImage; property OnScanningDone: TOnScanningDone read FOnScanningDone write FOnScanningDone; end; ETwain = class (Exception) fCode : Integer; fStatus : Integer; constructor Create (ACode, AStatus : Integer); end; var DefaultIdentity: TW_IDENTITY = ( Id: 0; // ID Version: ( MajorNum: 1; MinorNum: 0; Language: TWLG_ENGLISH; Country: TWCY_NETHERLANDS; Info: 'TcwTwain Component'; ); ProtocolMajor: 0; ProtocolMinor: 0; SupportedGroups: 0; Manufacturer: 'TcwTwain'; ProductFamily: ''; ProductName: ''; ); implementation { TcwTwain } destructor TcwTwain.Destroy; begin SetOpen (False); SetActive (False); FinalizeTwain; // jgb inherited; end; procedure TcwTwain.GetSingleImage (parent : TWinControl; pict : TPicture); var twUserInterface : TW_USERINTERFACE; begin InitializeTwain; // jgb FImageAvailable := False; fPict := pict; SetOpen (True); SetTransferCount (1); {$IFDEF SELECT_FORMAT} if TransferFormat = tfJPg then begin SetCapability (ICAP_IMAGEFILEFORMAT, TWFF_JFIF) end; {$ENDIF} twUserInterface.ShowUI := True; twUserInterface.hParent := parent.Handle; twUserInterface.ModalUI := True; fActiveWindow := GetActiveWindow; {$IFNDEF FPC} fWindowList := DisableTaskWindows (0); {$ELSE} fWindowList := Screen.DisableForms(nil); {$ENDIF} try TwainCheck (DSM_Entry (@fAppID, @fSourceID, DG_CONTROL, DAT_USERINTERFACE, MSG_ENABLEDS, @twUserInterface)); fEnabled := True except {$IFNDEF FPC} EnableTaskWindows (fWindowList); {$ELSE} Screen.EnableForms(fWindowList); {$ENDIF} SetActiveWindow (fActiveWindow) end end; // Silence a warning about HasCapability never being used. (* function TcwTwain.HasCapability(capability, value: Integer): boolean; var twCapability : TW_CAPABILITY; pValEnum : pTW_ENUMERATION; pValOneValue : pTW_ONEVALUE; i : Integer; begin result := False; twCapability.Cap := capability; twCapability.ConType := TWON_DONTCARE16; twCapability.hContainer := 0; TwainCheck (DSM_Entry (@fAppId, @fSourceID, DG_CONTROL, DAT_CAPABILITY, MSG_GET, @twCapability)); case twCapability.ConType of TWON_ENUMERATION : begin pValEnum := GlobalLock (twCapability.hContainer); try for i := 0 to pValEnum^.NumItems - 1 do begin if pvalEnum^.ItemType = TWTY_UINT16 then if pValEnum^.ItemList [i * 2] = value then begin result := True; break end end finally GlobalUnlock (twCapability.hContainer) end end; TWON_ONEVALUE: begin pValOneValue := GlobalLock (twCapability.hContainer); try if pValOneValue^.Item = Cardinal (value) then result := True finally GlobalUnlock (twCapability.hContainer) end end end end; *) function TcwTwain.SelectSource: boolean; begin InitializeTwain; // jgb FImageAvailable := False; SetActive (True); fActiveWindow := GetActiveWindow; {$IFNDEF FPC} fWindowList := DisableTaskWindows (0); {$ELSE} fWindowList := Screen.DisableForms(nil); {$ENDIF} try result := TwainCheck (DSM_Entry (@fAppId, Nil, DG_CONTROL, DAT_IDENTITY, MSG_USERSELECT, @fSourceId)) = TWRC_SUCCESS; finally {$IFNDEF FPC} EnableTaskWindows (fWindowList); {$ELSE} Screen.EnableForms(fWindowList); {$ENDIF} SetActiveWindow (fActiveWindow) end end; procedure TcwTwain.SetActive(const Value: boolean); var h : HWND; begin if fActive <> Value then case fActive of False : begin FillChar (fSourceId, SizeOf (fSourceID), 0); h := WindowHandle; fAppId.Version.MajorNum := DefaultIdentity.Version.MajorNum; fAppId.Version.MinorNum := DefaultIdentity.Version.MinorNum; fAppId.Version.Language := DefaultIdentity.Version.Language; fAppId.Version.Country := DefaultIdentity.Version.Country; lstrcpy(fAppId.Version.Info, DefaultIdentity.Version.Info); fAppID.ProtocolMajor := TWON_PROTOCOLMAJOR; fAppID.ProtocolMinor := TWON_PROTOCOLMINOR; fAppID.SupportedGroups := DG_IMAGE or DG_CONTROL; lstrcpy(fAppID.Manufacturer, DefaultIdentity.Manufacturer); lstrcpy(fAppID.ProductFamily, DefaultIdentity.ProductFamily); lstrcpy(fAppID.ProductName, DefaultIdentity.ProductName); TwainCheck (DSM_Entry (@fAppId, Nil, DG_CONTROL, DAT_PARENT, MSG_OPENDSM, @h)); fActive := True end; True : begin h := WindowHandle; TwainCheck (DSM_Entry (@fAppId, Nil, DG_CONTROL, DAT_PARENT, MSG_CLOSEDSM, @h)); fActive := False end end end; procedure TcwTwain.SetCapability(capability, value: Integer); var twCapability : TW_CAPABILITY; pVal : pTW_ONEVALUE; begin twCapability.Cap := capability; twCapability.ConType := TWON_ONEVALUE; twCapability.hContainer := GlobalAlloc (GHND, SizeOf (TW_ONEVALUE)); try pVal := pTW_ONEVALUE (GlobalLock (twCapability.hContainer)); try pVal^.ItemType := TWTY_INT16; pVal^.Item := value; finally GlobalUnlock (twCapability.hContainer) end; TwainCheck (DSM_Entry (@fAppId, @fSourceID, DG_CONTROL, DAT_CAPABILITY, MSG_SET, @twCapability)); finally GlobalFree (twCapability.hContainer) end end; procedure TcwTwain.SetOpen(const Value: boolean); begin if fOpen <> value then case fOpen of False : begin SetActive (True); TwainCheck (DSM_Entry (@fAppId, Nil, DG_CONTROL, DAT_IDENTITY, MSG_OPENDS, @fSourceId)); fOpen := True; end; True : begin TwainCheck (DSM_Entry (@fAppId, Nil, DG_CONTROL, DAT_IDENTITY, MSG_CLOSEDS, @fSourceId)); fEnabled := False; fOpen := False end end end; procedure TcwTwain.SetTransferCount(value: Integer); begin SetCapability (CAP_XFERCOUNT, value); end; {$IFDEF SELECT_FORMAT} procedure TcwTwain.SetTransferFormat(const Value: TTransferFormat); begin fTransferFormat := Value; end; {$ENDIF} {$DEFINE DISABLE_MEM_TRANSFER} // This code is disabled and doesn't seem to be finised. procedure TcwTwain.TransferImage; var h : THandle; twPendingXfers : TW_PENDINGXFERS; {$IFNDEF DISABLE_MEM_TRANSFER} twMemXFer : TW_IMAGEMEMXFER; // NB: This is used below in TwainCheck even if Delphi thinks it isn't! twSetupMemXFer : TW_SETUPMEMXFER; // NB: This is used below in TwainCheck even if Delphi thinks it isn't! twImageInfo : TW_IMAGEINFO; // NB: This is used below in TwainCheck even if Delphi thinks it isn't! {$ENDIF} TwainCode: Integer; function CreateTBitmapFromTwainHandle (h : THandle) : TBitmap; var mem : PBitmapInfo; sz : Integer; bmp : TBitmap; mems : TMemoryStream; Bmf: TBitmapFileHeader; begin sz := GlobalSize (h); mem := GlobalLock (h); bmp := Nil; mems := Nil; try mems := TMemoryStream.Create; bmp := TBitmap.Create; try FillChar (bmf, sizeof (bmf), 0); bmf.bfType := $4d42; mems.Write(bmf, sizeof (bmf)); mems.Write(mem^, sz); mems.Seek(0, soFromBeginning); bmp.LoadFromStream(mems); except FreeAndNil (bmp) end; Result := bmp; FImageAvailable := True; finally GlobalUnlock (h); mems.Free; end end; begin FImageAvailable := False; {$IFNDEF DISABLE_MEM_TRANSFER} if False then // HasCapability (ICAP_XFERMECH, TWSX_MEMORY) then begin SetCapability (ICAP_XFERMECH, TWSX_MEMORY); TwainCheck (DSM_Entry (@fAppId, @fSourceID, DG_CONTROL, DAT_SETUPMEMXFER, MSG_GET, @twSetupMemXFer)); TwainCheck (DSM_Entry (@fAppID, @fSourceID, DG_IMAGE, DAT_IMAGEINFO, MSG_GET, @twImageInfo)); FillChar (twMemXFer, SizeOf (twMemXFer), 0); twMemXFer.Compression := TWON_DONTCARE16; twMemXFer.BytesPerRow := TWON_DONTCARE32; twMemXFer.Columnms := TWON_DONTCARE32; twMemXFer.Rows := TWON_DONTCARE32; twMemXFer.XOffset := TWON_DONTCARE32; twMemXFer.YOffset := TWON_DONTCARE32; twMemXFer.BytesWritten := TWON_DONTCARE32; twMemXFer.Memory.Flags := TWMF_APPOWNS or TWMF_POINTER; twMemXFer.Memory.Length := twSetupMemXFer.MinBufSize; GetMem (twMemXFer.Memory.TheMem, twSetupMemXFer.Preferred); TwainCheck (DSM_Entry (@fAppId, @fSourceId, DG_IMAGE, DAT_IMAGEMEMXFER, MSG_GET, @twMemXFer)); end else {$ENDIF} begin TwainCode := TwainCheck (DSM_Entry (@fAppId, @fSourceId, DG_IMAGE, DAT_IMAGENATIVEXFER, MSG_GET, @h)); // We need to check here if everything went fine. // If an image was scanned we will get a TWRC_XFERDONE here. // If the user canceled scanning we get TWRC_CANCEL. if TwainCode <> TWRC_XFERDONE then Exit; try fPict.Graphic := CreateTBitmapFromTwainHandle (h); //ORIGINAL {$IFDEF DEBUG} {if fPict.Width = 0 then MessageBeep(MB_IconInformation);} {$ENDIF} finally GlobalFree (h) end end; TwainCheck (DSM_Entry (@fAppId, @fSourceId, DG_CONTROL, DAT_PENDINGXFERS, MSG_ENDXFER, @twPendingXfers)); // OnImage (self, bmp, release); end; function TcwTwain.TwainCheck(code: Integer): Integer; var status : TW_STATUS; begin if (code <> TWRC_SUCCESS) and (code <> TWRC_CANCEL) and (code <> TWRC_XFERDONE) then begin if (code = TWRC_FAILURE) or (code = TWRC_CHECKSTATUS) then begin TwainCheck (DSM_ENTRY (@fAppId, @fSourceID, DG_CONTROL, DAT_STATUS, MSG_GET, @status)); raise ETwain.Create (code, status.ConditionCode) end else raise ETwain.Create (code, 0); end; result := code end; procedure TcwTwain.WndProc(var Msg: TMessage); var rc : Integer; twEvent : TW_EVENT; twUserInterface : TW_USERINTERFACE; m : TMsg; begin try rc := TWRC_NOTDSEVENT; if fEnabled then begin m.hwnd := WindowHandle; m.message := Msg.Msg; m.wParam := msg.WParam; m.lParam := msg.LParam; twEvent.pEvent := @m; twEvent.TWMessage := MSG_NULL; rc := DSM_Entry (@fAppId, @fSourceId, DG_CONTROL, DAT_EVENT, MSG_PROCESSEVENT, @twEvent); case twEvent.TWMessage of MSG_XFERREADY : begin TransferImage; {JGB added: (see also ...\Overige\Twain2\Twain.pas) } FillChar (twUserInterface, SizeOf (twUserInterface), 0); TwainCheck (DSM_Entry (@fAppId, @fSourceId, DG_CONTROL, DAT_USERINTERFACE, MSG_DISABLEDS, @twUserInterface)); {$IFNDEF FPC} EnableTaskWindows (fWindowList); {$ELSE} Screen.EnableForms(fWindowList); {$ENDIF} SetActiveWindow (fActiveWindow); SetOpen (False); if Assigned(FOnScanningDone) then FOnScanningDone(Self,FImageAvailable); {end jgb added} end; MSG_CLOSEDSREQ: begin FillChar (twUserInterface, SizeOf (twUserInterface), 0); TwainCheck (DSM_Entry (@fAppId, @fSourceId, DG_CONTROL, DAT_USERINTERFACE, MSG_DISABLEDS, @twUserInterface)); {$IFNDEF FPC} EnableTaskWindows (fWindowList); {$ELSE} Screen.EnableForms(fWindowList); {$ENDIF} SetActiveWindow (fActiveWindow); SetOpen (False) end; MSG_CLOSEDSOK: begin SetOpen (False); end; end end; if rc = TWRC_NOTDSEVENT then Dispatch (Msg) except Application.HandleException (self) end end; { ETwain } constructor ETwain.Create(ACode, AStatus: Integer); begin fCode := ACode; fStatus := AStatus; if AStatus <> 0 then inherited CreateFmt ('Twain error failure %d status %d', [ACode, ASTatus]) else inherited CreateFmt ('Twain error %d', [ACode]); end; end.
unit BuiltinFuncs; {$I mwEdit.inc} interface uses SysUtils, Windows, Messages, Classes, Controls, Graphics, Registry, mwHighlighter, mwExport, mwLocalStr; Type TmoTokenKind = ( moBuiltinFunc); TRangeState = (rsUnknown); TProcTableProc = procedure of Object; PIdentFuncTableFunc = ^TIdentFuncTableFunc; TIdentFuncTableFunc = function: TmoTokenKind of Object; type TmwMOOSyntax = class(TmwCustomHighLighter) private fRange: TRangeState; fLine: PChar; fLineNumber: Integer; fExporter: TmwCustomExport; fProcTable: array[#0..#255] of TProcTableProc; Run: LongInt; fStringLen: Integer; fToIdent: PChar; fTokenPos: Integer; FTokenID: TtkTokenKind; fIdentFuncTable: array[0..126] of TIdentFuncTableFunc; fBuiltinFuncAttri: TmwHighLightAttributes; function KeyHash(ToHash: PChar): Integer; function KeyComp(const aKey: String): Boolean; function Func0: TmoTokenKind; function Func1: TmoTokenKind; function Func2: TmoTokenKind; function Func6: TmoTokenKind; function Func8: TmoTokenKind; function Func10: TmoTokenKind; function Func12: TmoTokenKind; function Func13: TmoTokenKind; function Func16: TmoTokenKind; function Func17: TmoTokenKind; function Func18: TmoTokenKind; function Func22: TmoTokenKind; function Func24: TmoTokenKind; function Func25: TmoTokenKind; function Func26: TmoTokenKind; function Func27: TmoTokenKind; function Func28: TmoTokenKind; function Func29: TmoTokenKind; function Func30: TmoTokenKind; function Func32: TmoTokenKind; function Func33: TmoTokenKind; function Func34: TmoTokenKind; function Func35: TmoTokenKind; function Func36: TmoTokenKind; function Func37: TmoTokenKind; function Func38: TmoTokenKind; function Func40: TmoTokenKind; function Func42: TmoTokenKind; function Func43: TmoTokenKind; function Func45: TmoTokenKind; function Func46: TmoTokenKind; function Func47: TmoTokenKind; function Func48: TmoTokenKind; function Func49: TmoTokenKind; function Func50: TmoTokenKind; function Func51: TmoTokenKind; function Func52: TmoTokenKind; function Func53: TmoTokenKind; function Func55: TmoTokenKind; function Func56: TmoTokenKind; function Func60: TmoTokenKind; function Func62: TmoTokenKind; function Func63: TmoTokenKind; function Func64: TmoTokenKind; function Func65: TmoTokenKind; function Func66: TmoTokenKind; function Func69: TmoTokenKind; function Func70: TmoTokenKind; function Func71: TmoTokenKind; function Func73: TmoTokenKind; function Func74: TmoTokenKind; function Func75: TmoTokenKind; function Func76: TmoTokenKind; function Func78: TmoTokenKind; function Func79: TmoTokenKind; function Func80: TmoTokenKind; function Func81: TmoTokenKind; function Func82: TmoTokenKind; function Func83: TmoTokenKind; function Func85: TmoTokenKind; function Func87: TmoTokenKind; function Func89: TmoTokenKind; function Func92: TmoTokenKind; function Func94: TmoTokenKind; function Func95: TmoTokenKind; function Func96: TmoTokenKind; function Func98: TmoTokenKind; function Func99: TmoTokenKind; function Func100: TmoTokenKind; function Func104: TmoTokenKind; function Func105: TmoTokenKind; function Func108: TmoTokenKind; function Func111: TmoTokenKind; function Func112: TmoTokenKind; function Func114: TmoTokenKind; function Func115: TmoTokenKind; function Func116: TmoTokenKind; function Func121: TmoTokenKind; function Func122: TmoTokenKind; function Func123: TmoTokenKind; function Func124: TmoTokenKind; function Func126: TmoTokenKind; procedure UnknownProc; function AltFunc: TmoTokenKind; procedure InitIdent; function IdentKind(MayBe: PChar): TmoTokenKind; procedure MakeMethodTables; protected function GetIdentChars: TIdentChars; override; function GetLanguageName: string; override; function GetCapability: THighlighterCapability; override; public constructor Create(AOwner: TComponent); override; function GetEOL: Boolean; override; function GetRange: Pointer; override; function GetTokenID: TtkTokenKind; procedure SetLine(NewValue: String; LineNumber: Integer); override; procedure ExportNext; override; procedure SetLineForExport(NewValue: String); override; function GetToken: String; override; function GetTokenAttribute: TmwHighLightAttributes; override; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; procedure Next; override; procedure SetRange(Value: Pointer); override; procedure ReSetRange; override; property IdentChars; published property BuiltinFuncAttri: TmwHighLightAttributes read fBuiltinFuncAttri write fBuiltinFuncAttri; property Exporter:TmwCustomExport read FExporter write FExporter; end; procedure Register; implementation procedure Register; begin RegisterComponents(MWS_HighlightersPage, [TmwMOOSyntax]); end; var Identifiers: array[#0..#255] of ByteBool; mHashTable: array[#0..#255] of Integer; procedure MakeIdentTable; var I, J: Char; begin for I := #0 to #255 do begin Case I of '_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True; else Identifiers[I] := False; end; J := UpCase(I); Case I in ['_', 'A'..'Z', 'a'..'z'] of True: mHashTable[I] := Ord(J) - 64 else mHashTable[I] := 0; end; end; end; procedure TmwMOOSyntax.InitIdent; var I: Integer; pF: PIdentFuncTableFunc; begin pF := PIdentFuncTableFunc(@fIdentFuncTable); for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do begin pF^ := AltFunc; Inc(pF); end; fIdentFuncTable[0] := Func0; fIdentFuncTable[1] := Func1; fIdentFuncTable[2] := Func2; fIdentFuncTable[6] := Func6; fIdentFuncTable[8] := Func8; fIdentFuncTable[10] := Func10; fIdentFuncTable[12] := Func12; fIdentFuncTable[13] := Func13; fIdentFuncTable[16] := Func16; fIdentFuncTable[17] := Func17; fIdentFuncTable[18] := Func18; fIdentFuncTable[22] := Func22; fIdentFuncTable[24] := Func24; fIdentFuncTable[25] := Func25; fIdentFuncTable[26] := Func26; fIdentFuncTable[27] := Func27; fIdentFuncTable[28] := Func28; fIdentFuncTable[29] := Func29; fIdentFuncTable[30] := Func30; fIdentFuncTable[32] := Func32; fIdentFuncTable[33] := Func33; fIdentFuncTable[34] := Func34; fIdentFuncTable[35] := Func35; fIdentFuncTable[36] := Func36; fIdentFuncTable[37] := Func37; fIdentFuncTable[38] := Func38; fIdentFuncTable[40] := Func40; fIdentFuncTable[42] := Func42; fIdentFuncTable[43] := Func43; fIdentFuncTable[45] := Func45; fIdentFuncTable[46] := Func46; fIdentFuncTable[47] := Func47; fIdentFuncTable[48] := Func48; fIdentFuncTable[49] := Func49; fIdentFuncTable[50] := Func50; fIdentFuncTable[51] := Func51; fIdentFuncTable[52] := Func52; fIdentFuncTable[53] := Func53; fIdentFuncTable[55] := Func55; fIdentFuncTable[56] := Func56; fIdentFuncTable[60] := Func60; fIdentFuncTable[62] := Func62; fIdentFuncTable[63] := Func63; fIdentFuncTable[64] := Func64; fIdentFuncTable[65] := Func65; fIdentFuncTable[66] := Func66; fIdentFuncTable[69] := Func69; fIdentFuncTable[70] := Func70; fIdentFuncTable[71] := Func71; fIdentFuncTable[73] := Func73; fIdentFuncTable[74] := Func74; fIdentFuncTable[75] := Func75; fIdentFuncTable[76] := Func76; fIdentFuncTable[78] := Func78; fIdentFuncTable[79] := Func79; fIdentFuncTable[80] := Func80; fIdentFuncTable[81] := Func81; fIdentFuncTable[82] := Func82; fIdentFuncTable[83] := Func83; fIdentFuncTable[85] := Func85; fIdentFuncTable[87] := Func87; fIdentFuncTable[89] := Func89; fIdentFuncTable[92] := Func92; fIdentFuncTable[94] := Func94; fIdentFuncTable[95] := Func95; fIdentFuncTable[96] := Func96; fIdentFuncTable[98] := Func98; fIdentFuncTable[99] := Func99; fIdentFuncTable[100] := Func100; fIdentFuncTable[104] := Func104; fIdentFuncTable[105] := Func105; fIdentFuncTable[108] := Func108; fIdentFuncTable[111] := Func111; fIdentFuncTable[112] := Func112; fIdentFuncTable[114] := Func114; fIdentFuncTable[115] := Func115; fIdentFuncTable[116] := Func116; fIdentFuncTable[121] := Func121; fIdentFuncTable[122] := Func122; fIdentFuncTable[123] := Func123; fIdentFuncTable[124] := Func124; fIdentFuncTable[126] := Func126; end; function TmwMOOSyntax.KeyHash(ToHash: PChar): Integer; begin Result := 0; while ToHash^ in ['_', '0'..'9', 'a'..'z', 'A'..'Z'] do begin inc(Result, mHashTable[ToHash^]); inc(ToHash); end; fStringLen := ToHash - fToIdent; end; function TmwMOOSyntax.KeyComp(const aKey: String): Boolean; var I: Integer; Temp: PChar; begin Temp := fToIdent; if Length(aKey) = fStringLen then begin Result := True; for i := 1 to fStringLen do begin if mHashTable[Temp^] <> mHashTable[aKey[i]] then begin Result := False; break; end; inc(Temp); end; end else Result := False; end; function TmwMOOSyntax.Func0: TmoTokenKind; begin if KeyComp('value_hash') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func1: TmoTokenKind; begin if KeyComp('delete_verb') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func2: TmoTokenKind; begin if KeyComp('output_delimiters') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func6: TmoTokenKind; begin if KeyComp('is_clear_property') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func8: TmoTokenKind; begin if KeyComp('decode_binary') then Result := moBuiltinFunc else if KeyComp('binary_hash') then Result := moBuiltinFunc else if KeyComp('task_stack') then Result := moBuiltinFunc else if KeyComp('ticks_left') then Result := moBuiltinFunc else if KeyComp('is_player') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func10: TmoTokenKind; begin if KeyComp('dump_database') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func12: TmoTokenKind; begin if KeyComp('idle_seconds') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func13: TmoTokenKind; begin if KeyComp('properties') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func16: TmoTokenKind; begin if KeyComp('queue_info') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func17: TmoTokenKind; begin if KeyComp('listinsert') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func18: TmoTokenKind; begin if KeyComp('encode_binary') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func22: TmoTokenKind; begin if KeyComp('abs') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func24: TmoTokenKind; begin if KeyComp('server_log') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func25: TmoTokenKind; begin if KeyComp('caller_perms') then Result := moBuiltinFunc else if KeyComp('seconds_left') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func26: TmoTokenKind; begin if KeyComp('string_hash') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func27: TmoTokenKind; begin if KeyComp('set_property_info') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func28: TmoTokenKind; begin if KeyComp('read') then Result := moBuiltinFunc else if KeyComp('substitute') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func29: TmoTokenKind; begin if KeyComp('object_bytes') then Result := moBuiltinFunc else if KeyComp('ceil') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func30: TmoTokenKind; begin if KeyComp('force_input') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func32: TmoTokenKind; begin if KeyComp('boot_player') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func33: TmoTokenKind; begin if KeyComp('call_function') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func34: TmoTokenKind; begin if KeyComp('log') then Result := moBuiltinFunc else if KeyComp('log10') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func35: TmoTokenKind; begin if KeyComp('value_bytes') then Result := moBuiltinFunc else if KeyComp('tan') then Result := moBuiltinFunc else if KeyComp('notify_ansi') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func36: TmoTokenKind; begin if KeyComp('atan') then Result := moBuiltinFunc else if KeyComp('min') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func37: TmoTokenKind; begin if KeyComp('cos') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func38: TmoTokenKind; begin if KeyComp('max') then Result := moBuiltinFunc else if KeyComp('acos') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func40: TmoTokenKind; begin if KeyComp('eval') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func42: TmoTokenKind; begin if KeyComp('sin') then Result := moBuiltinFunc else if KeyComp('db_disk_size') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func43: TmoTokenKind; begin if KeyComp('asin') then Result := moBuiltinFunc else if KeyComp('tanh') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func45: TmoTokenKind; begin if KeyComp('memory_usage') then Result := moBuiltinFunc else if KeyComp('add_property') then Result := moBuiltinFunc else if KeyComp('exp') then Result := moBuiltinFunc else if KeyComp('cosh') then Result := moBuiltinFunc else if KeyComp('match') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func46: TmoTokenKind; begin if KeyComp('queued_tasks') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func47: TmoTokenKind; begin if KeyComp('time') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func48: TmoTokenKind; begin if KeyComp('valid') then Result := moBuiltinFunc else if KeyComp('connection_name') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func49: TmoTokenKind; begin if KeyComp('function_info') then Result := moBuiltinFunc else if KeyComp('flush_input') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func50: TmoTokenKind; begin if KeyComp('ctime') then Result := moBuiltinFunc else if KeyComp('sinh') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func51: TmoTokenKind; begin if KeyComp('set_connection_option') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func52: TmoTokenKind; begin if KeyComp('buffered_output_length') then Result := moBuiltinFunc else if KeyComp('raise') then Result := moBuiltinFunc else if KeyComp('create') then Result := moBuiltinFunc else if KeyComp('set_verb_code') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func53: TmoTokenKind; begin if KeyComp('setadd') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func55: TmoTokenKind; begin if KeyComp('pass') then Result := moBuiltinFunc else if KeyComp('move') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func56: TmoTokenKind; begin if KeyComp('index') then Result := moBuiltinFunc else if KeyComp('equal') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func60: TmoTokenKind; begin if KeyComp('nis_password') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func62: TmoTokenKind; begin if KeyComp('toobj') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func63: TmoTokenKind; begin if KeyComp('rmatch') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func64: TmoTokenKind; begin if KeyComp('bf-index') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func65: TmoTokenKind; begin if KeyComp('connected_seconds') then Result := moBuiltinFunc else if KeyComp('random') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func66: TmoTokenKind; begin if KeyComp('length') then Result := moBuiltinFunc else if KeyComp('floor') then Result := moBuiltinFunc else if KeyComp('verbs') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func69: TmoTokenKind; begin if KeyComp('set_verb_info') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func70: TmoTokenKind; begin if KeyComp('set_verb_args') then Result := moBuiltinFunc else if KeyComp('callers') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func71: TmoTokenKind; begin if KeyComp('recycle') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func73: TmoTokenKind; begin if KeyComp('children') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func74: TmoTokenKind; begin if KeyComp('sqrt') then Result := moBuiltinFunc else if KeyComp('parent') then Result := moBuiltinFunc else if KeyComp('open_network_connection') then Result := moBuiltinFunc else if KeyComp('rindex') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func75: TmoTokenKind; begin if KeyComp('clear_property') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func76: TmoTokenKind; begin if KeyComp('trunc') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func78: TmoTokenKind; begin if KeyComp('uudecode') then Result := moBuiltinFunc else if KeyComp('toint') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func79: TmoTokenKind; begin if KeyComp('listen') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func80: TmoTokenKind; begin if KeyComp('property_info') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func81: TmoTokenKind; begin if KeyComp('set_player_flag') then Result := moBuiltinFunc else if KeyComp('resume') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func82: TmoTokenKind; begin if KeyComp('connected_players') then Result := moBuiltinFunc else if KeyComp('crypt') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func83: TmoTokenKind; begin if KeyComp('tonum') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func85: TmoTokenKind; begin if KeyComp('chparent') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func87: TmoTokenKind; begin if KeyComp('add_verb') then Result := moBuiltinFunc else if KeyComp('delete_property') then Result := moBuiltinFunc else if KeyComp('typeof') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func89: TmoTokenKind; begin if KeyComp('tofloat') then Result := moBuiltinFunc else if KeyComp('notify') then Result := moBuiltinFunc else if KeyComp('strcmp') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func92: TmoTokenKind; begin if KeyComp('server_version') then Result := moBuiltinFunc else if KeyComp('tostr') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func94: TmoTokenKind; begin if KeyComp('reset_max_object') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func95: TmoTokenKind; begin if KeyComp('task_id') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func96: TmoTokenKind; begin if KeyComp('renumber') then Result := moBuiltinFunc else if KeyComp('players') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func98: TmoTokenKind; begin if KeyComp('suspend') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func99: TmoTokenKind; begin if KeyComp('strsub') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func100: TmoTokenKind; begin if KeyComp('set_task_perms') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func104: TmoTokenKind; begin if KeyComp('listset') then Result := moBuiltinFunc else if KeyComp('connection_option') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func105: TmoTokenKind; begin if KeyComp('verb_code') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func108: TmoTokenKind; begin if KeyComp('disassemble') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func111: TmoTokenKind; begin if KeyComp('floatstr') then Result := moBuiltinFunc else if KeyComp('listdelete') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func112: TmoTokenKind; begin if KeyComp('toliteral') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func114: TmoTokenKind; begin if KeyComp('unlisten') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func115: TmoTokenKind; begin if KeyComp('is_member') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func116: TmoTokenKind; begin if KeyComp('listappend') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func121: TmoTokenKind; begin if KeyComp('listeners') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func122: TmoTokenKind; begin if KeyComp('verb_info') then Result := moBuiltinFunc else if KeyComp('setremove') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func123: TmoTokenKind; begin if KeyComp('verb_args') then Result := moBuiltinFunc else if KeyComp('connection_options') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func124: TmoTokenKind; begin if KeyComp('shutdown') then Result := moBuiltinFunc else if KeyComp('max_object') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.Func126: TmoTokenKind; begin if KeyComp('kill_task') then Result := moBuiltinFunc else Result := moIdentifier; end; function TmwMOOSyntax.AltFunc: TmoTokenKind; begin Result := moIdentifier; end; function TmwMOOSyntax.IdentKind(MayBe: PChar): TmoTokenKind; var HashKey: Integer; begin fToIdent := MayBe; HashKey := KeyHash(MayBe); if HashKey < 127 then Result := fIdentFuncTable[HashKey] else Result := moIdentifier; end; procedure TmwMOOSyntax.MakeMethodTables; var I: Char; begin for I := #0 to #255 do case I of else fProcTable[I] := UnknownProc; end; end; constructor TmwMOOSyntax.Create(AOwner: TComponent); begin fBuiltinFuncAttri := TmwHighLightAttributes.Create(MWS_AttrBuiltinFunc); inherited Create(AOwner); AddAttribute(fBuiltinFuncAttri); SetAttributesOnChange(DefHighlightChange); InitIdent; MakeMethodTables; fDefaultFilter := 'All files (*.*)|*.*'; fRange := rsUnknown; end; procedure TmwMOOSyntax.SetLine(NewValue: String; LineNumber: Integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; Next; end; procedure TmwMOOSyntax.UnknownProc; begin inc(Run); fTokenID := moUnknown; end; procedure TmwMOOSyntax.Next; begin fTokenPos := Run; fProcTable[fLine[Run]]; end; function TmwMOOSyntax.GetEOL: Boolean; begin Result := fTokenID = tkNull; end; function TmwMOOSyntax.GetRange: Pointer; begin Result := Pointer(fRange); end; function TmwMOOSyntax.GetToken: String; var Len: LongInt; begin Len := Run - fTokenPos; SetString(Result, (FLine + fTokenPos), Len); end; function TmwMOOSyntax.GetTokenID: TtkTokenKind; begin Result := fTokenId; end; function TmwMOOSyntax.GetTokenAttribute: TmwHighLightAttributes; begin case GetTokenID of moBuiltinFunc: Result := fBuiltinFuncAttri; moUnknown: Result := fIdentifierAttri; else Result := nil; end; end; function TmwMOOSyntax.GetTokenKind: integer; begin Result := Ord(fTokenId); end; function TmwMOOSyntax.GetTokenPos: Integer; begin Result := fTokenPos; end; procedure TmwMOOSyntax.ReSetRange; begin fRange := rsUnknown; end; procedure TmwMOOSyntax.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; function TmwMOOSyntax.GetIdentChars: TIdentChars; begin Result := ['_', '0'..'9', 'a'..'z', 'A'..'Z']; end; function TmwMOOSyntax.GetLanguageName: string; begin Result := 'moo'; end; function TmwMOOSyntax.GetCapability: THighlighterCapability; begin Result := inherited GetCapability + [hcUserSettings, hcExportable]; end; procedure TmwMOOSyntax.SetLineForExport(NewValue: String); begin fLine := PChar(NewValue); Run := 0; ExportNext; end; procedure TmwMOOSyntax.ExportNext; begin fTokenPos := Run; fProcTable[fLine[Run]]; if Assigned(Exporter) then Case GetTokenID of moBuiltinFunc: TmwCustomExport(Exporter).FormatToken(GetToken, fBuiltinFuncAttri, False, False); end; end; Initialization MakeIdentTable; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.jsonutils.datasnap; interface uses SysUtils, DBXJSON, DBXJSONReflect, {$IFDEF DELPHI15_UP} JSON, {$ENDIF DELPHI15_UP} Generics.Collections, ormbr.rest.json; type TORMBrJSONUtil = class public class function JSONStringToJSONValue(AJson: string): TJSONValue; class function JSONStringToJSONArray(AJson: string): TJSONArray; overload; class function JSONStringToJSONArray<T: class>(AObjectList: TObjectList<T>): TJSONArray; overload; class function JSONStringToJSONObject(AJson: string): TJSONObject; end; implementation { TORMBrJSONUtil } class function TORMBrJSONUtil.JSONStringToJSONArray(AJson: string): TJSONArray; begin Result := TJSONArray.Create; Result.Add(JSONStringToJSONObject(AJson)); end; class function TORMBrJSONUtil.JSONStringToJSONArray<T>( AObjectList: TObjectList<T>): TJSONArray; var LItem: T; begin Result := TJSONArray.Create; for LItem in AObjectList do Result.Add(JSONStringToJSONObject(TORMBrJson.ObjectToJsonString(LItem))); end; class function TORMBrJSONUtil.JSONStringToJSONObject(AJson: string): TJSONObject; begin Result := JSONStringToJSONValue(AJson) as TJSONObject; end; class function TORMBrJSONUtil.JSONStringToJSONValue(AJson: string): TJSONValue; begin Result := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(AJson),0); end; end.
unit FramePriCube; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, PMBuild, ComCtrls, Spin; type TPriCubeFrame = class(TFrame) CubeGroup: TGroupBox; SideTabs: TTabControl; SplitCheck: TCheckBox; OriginLabel: TLabel; SizeLabel: TLabel; OrigU: TSpinEdit; OrigV: TSpinEdit; SizeU: TSpinEdit; SizeV: TSpinEdit; TexCoordsGroup: TGroupBox; function Fill(Pri: TPMBPrimitive): Boolean; procedure Clear; procedure SplitCheckClick(Sender: TObject); procedure GenUVChange(Sender: TObject); procedure SideTabsChange(Sender: TObject); private FPri: TPMBPrimitiveCube; end; implementation {$R *.dfm} function TPriCubeFrame.Fill(Pri: TPMBPrimitive): Boolean; begin Result:=Pri.PriType=PrimitiveCube; if Result then begin FPri:=Pri as TPMBPrimitiveCube; SideTabsChange(nil); end else FPri:=nil; end; procedure TPriCubeFrame.Clear; begin FPri:=nil; end; procedure TPriCubeFrame.SplitCheckClick(Sender: TObject); begin if Assigned(FPri) then FPri.TexSplitSides[SideTabs.TabIndex]:=SplitCheck.Checked; end; procedure TPriCubeFrame.GenUVChange(Sender: TObject); var GenUV: TPMUVRect; begin if not Assigned(FPri) or ((Sender as TSpinEdit).Text='') or ((Sender as TSpinEdit).Text='-') then Exit; GenUV:=FPri.TexUV[SideTabs.TabIndex]; if Sender=OrigU then GenUV.OrigU:=OrigU.Value; if Sender=OrigV then GenUV.OrigV:=OrigV.Value; if Sender=SizeU then GenUV.SizeU:=SizeU.Value; if Sender=SizeV then GenUV.SizeV:=SizeV.Value; FPri.TexUV[SideTabs.TabIndex]:=GenUV; end; procedure TPriCubeFrame.SideTabsChange(Sender: TObject); var GenUV: TPMUVRect; begin if not Assigned(FPri) then Exit; SplitCheck.Checked:=FPri.TexSplitSides[SideTabs.TabIndex]; GenUV:=FPri.TexUV[SideTabs.TabIndex]; OrigU.Value:=GenUV.OrigU; OrigV.Value:=GenUV.OrigV; SizeU.Value:=GenUV.SizeU; SizeV.Value:=GenUV.SizeV; end; end.
unit PessoaContatoDTO; interface uses Atributos, Constantes, Classes, SynCommons, mORMot; type TPessoa_Contato = class(TSQLRecord) private FID_PESSOA: TID; FNOME: RawUTF8; FEMAIL: RawUTF8; FFONE_COMERCIAL: RawUTF8; FFONE_RESIDENCIAL: RawUTF8; FFONE_CELULAR: RawUTF8; //Usado no lado cliente para controlar quais registros serão persistidos FPersiste: String; public [TColumn('PERSISTE', 'Persiste', 60, [], True)] property Persiste: String read FPersiste write FPersiste; published [TColumn('ID_PESSOA', 'Id Pessoa', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id_Pessoa: TID read FID_PESSOA write FID_PESSOA; [TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)] property Nome: RawUTF8 read FNOME write FNOME; [TColumn('EMAIL', 'Email', 450, [ldGrid, ldLookup, ldCombobox], False)] property Email: RawUTF8 read FEMAIL write FEMAIL; [TColumn('FONE_COMERCIAL', 'Fone Comercial', 112, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Fone_Comercial: RawUTF8 read FFONE_COMERCIAL write FFONE_COMERCIAL; [TColumn('FONE_RESIDENCIAL', 'Fone Residencial', 112, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Fone_Residencial: RawUTF8 read FFONE_RESIDENCIAL write FFONE_RESIDENCIAL; [TColumn('FONE_CELULAR', 'Fone Celular', 112, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Fone_Celular: RawUTF8 read FFONE_CELULAR write FFONE_CELULAR; end; implementation end.
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Casbin.Policy; interface uses Casbin.Core.Base.Types, Casbin.Policy.Types, Casbin.Parser.Types, Casbin.Parser.AST.Types, Casbin.Adapter.Policy.Types, System.Rtti, System.Types, System.Classes, Casbin.Model.Sections.Types, System.Generics.Collections, Casbin.Watcher.Types; type TPolicyManager = class(TBaseInterfacedObject, IPolicyManager) private fAdapter: IPolicyAdapter; fParser: IParser; //PALOFF fNodes: TNodeCollection; fPoliciesList: TList<string>; fRolesList: TList<string>; fDomains: TList<string>; fWatchers: TList<IWatcher>; fRolesNodes: TObjectDictionary<string, TRoleNode>; fRolesLinks: TObjectDictionary<string, TStringList>; procedure loadPolicies; function findRolesNode(const aDomain, aValue: string): TRoleNode; function implicitPolicyExists(const aValue, aResource: string): Boolean; procedure loadRoles; private {$REGION 'Interface'} function section (const aSlim: Boolean = true): string; function toOutputString: string; function getAdapter: IPolicyAdapter; // Policies function policies: TList<string>; procedure load (const aFilter: TFilterArray = []); function policy(const aFilter: TFilterArray = []): string; procedure clear; function policyExists(const aFilter: TFilterArray = []): Boolean; procedure removePolicy(const aFilter: TFilterArray = []; const aRoleMode: TRoleMode = rmImplicit); procedure addPolicy (const aSection: TSectionType; const aTag: string; const aAssertion: string); overload; procedure addPolicy (const aSection: TSectionType; const aAssertion: string); overload; // Roles procedure clearRoles; function roles: TList<string>; function domains: TList<string>; function roleExists (const aFilter: TFilterArray = []): Boolean; procedure addLink(const aBottom: string; const aTop: string); overload; procedure addLink(const aBottom: string; const aTopDomain: string; const aTop: string); overload; procedure addLink(const aBottomDomain: string; const aBottom: string; const aTopDomain: string; const aTop: string); overload; procedure removeLink(const aLeft, aRight: string); overload; procedure removeLink(const aLeft: string; const aRightDomain: string; const aRight: string); overload; procedure removeLink(const aLeftDomain, aLeft, aRightDomain, aRight: string); overload; function linkExists(const aLeft: string; const aRight: string): Boolean; overload; function linkExists(const aLeft: string; const aRightDomain: string; const aRight: string):boolean; overload; function linkExists(const aLeftDomain: string; const aLeft: string; const aRightDomain: string; const aRight: string): boolean; overload; function rolesForEntity(const aEntity: string; const aDomain: string = ''; const aRoleMode: TRoleMode = rmNonImplicit): TStringDynArray; function entitiesForRole(const aEntity: string; const aDomain: string =''): TStringDynArray; // Watchers procedure registerWatcher (const aWatcher: IWatcher); procedure unregisterWatcher(const aWatcher: IWatcher); procedure notifyWatchers; //Permissions function permissionsForEntity(const aEntity: string): TStringDynArray; function permissionExists (const aEntity: string; const aPermission: string): Boolean; {$ENDREGION} public constructor Create(const aPolicy: string); overload; constructor Create(const aAdapter: IPolicyAdapter); overload; constructor Create; overload; destructor Destroy; override; end; implementation uses Casbin.Adapter.Filesystem.Policy, Casbin.Exception.Types, Casbin.Parser, Casbin.Core.Utilities, Casbin.Core.Defaults, System.SysUtils, System.StrUtils, Casbin.Model.Sections.Default, Casbin.Adapter.Memory.Policy, Casbin.Parser.AST, ArrayHelper, System.RegularExpressions, Casbin.Functions.IPMatch; { TPolicyManager } constructor TPolicyManager.Create(const aPolicy: string); begin Create(TPolicyFileAdapter.Create(aPolicy)); end; procedure TPolicyManager.addLink(const aBottom, aTop: string); begin addLink(DefaultDomain, aBottom, DefaultDomain, aTop); end; procedure TPolicyManager.addLink(const aBottomDomain, aBottom, aTopDomain, aTop: string); var bottomNode: TRoleNode; topNode: TRoleNode; IDList: TStringList; begin bottomNode:=findRolesNode(aBottomDomain, aBottom); if not Assigned(bottomNode) then begin bottomNode:=TRoleNode.Create(aBottom, aBottomDomain); fRolesNodes.add(bottomNode.ID, bottomNode); end; topNode:=findRolesNode(aTopDomain, aTop); if not Assigned(topNode) then begin topNode:=TRoleNode.Create(aTop, aTopDomain); fRolesNodes.add(topNode.ID, topNode); end; if not fRolesLinks.ContainsKey(bottomNode.ID) then begin IDList:=TStringList.Create; IDList.Sorted:=true; IDList.CaseSensitive:=False; fRolesLinks.add(bottomNode.ID, IDList); end; IDList:=fRolesLinks.Items[bottomNode.ID]; if IDList.IndexOf(topNode.id)=-1 then IDList.add(topNode.ID); end; procedure TPolicyManager.addPolicy(const aSection: TSectionType; const aAssertion: string); var arrStr: TArray<string>; begin if trim(aAssertion)='' then raise ECasbinException.Create('The Assertion is empty'); arrStr:=aAssertion.Split([',']); if Length(arrStr)<=1 then raise ECasbinException.Create('The Assertion '+aAssertion+' is wrong'); addPolicy(aSection, arrStr[0], string.Join(',', arrStr, 1, Length(arrStr)-1)); end; procedure TPolicyManager.addPolicy(const aSection: TSectionType; const aTag, aAssertion: string); begin if trim(aTag)='' then raise ECasbinException.Create('The Tag is empty'); if trim(aAssertion)='' then raise ECasbinException.Create('The Assertion is empty'); if not ((aSection=stDefault) or (aSection=stPolicyRules) or (aSection=stRoleRules)) then raise ECasbinException.Create('Wrong section type'); fAdapter.add(Trim(aTag)+','+trim(aAssertion)); fParser:=TParser.Create(fAdapter.toOutputString, ptPolicy); fParser.parse; if fParser.Status=psError then raise ECasbinException.Create('Parsing error in Model: '+fParser.ErrorMessage); fNodes:=fParser.Nodes; loadRoles; notifyWatchers; end; procedure TPolicyManager.addLink(const aBottom, aTopDomain, aTop: string); begin addLink(DefaultDomain, aBottom, aTopDomain, aTop); end; procedure TPolicyManager.clear; begin fAdapter.clear; end; procedure TPolicyManager.clearRoles; begin fRolesLinks.Clear; fRolesNodes.Clear; end; constructor TPolicyManager.Create(const aAdapter: IPolicyAdapter); begin if not Assigned(aAdapter) then raise ECasbinException.Create('Adapter is nil in '+Self.ClassName); inherited Create; fAdapter:=aAdapter; fPoliciesList:=TList<string>.Create; //PALOFF fRolesList:=TList<string>.Create; //PALOFF fRolesNodes:=TObjectDictionary<string, TRoleNode>.Create([doOwnsValues]); fRolesLinks:=TObjectDictionary<string, TStringList>.Create([doOwnsValues]); fDomains:=TList<string>.Create; //PALOFF fWatchers:=TList<IWatcher>.Create; //PALOFF loadPolicies; loadRoles; end; constructor TPolicyManager.Create; begin Create(TPolicyMemoryAdapter.Create); end; procedure TPolicyManager.registerWatcher(const aWatcher: IWatcher); begin if not fWatchers.Contains(aWatcher) then fWatchers.Add(aWatcher); end; procedure TPolicyManager.removeLink(const aLeftDomain, aLeft, aRightDomain, aRight: string); var leftNode: TRoleNode; rightNode: TRoleNode; index: integer; list: TStringList; begin leftNode:=findRolesNode(aLeftDomain, aLeft); if not Assigned(leftNode) then Exit; rightNode:=findRolesNode(aRightDomain, aRight); if not Assigned(rightNode) then Exit; list:=fRolesLinks.Items[leftNode.ID]; if Assigned(list) then begin index:=list.IndexOf(rightNode.ID); if (index>-1) and (rightNode.Domain=aRightDomain) then list.Delete(index); end; end; procedure TPolicyManager.removePolicy(const aFilter: TFilterArray = []; const aRoleMode: TRoleMode = rmImplicit); var arrString: TArrayRecord<string>; item: string; header: THeaderNode; child: TChildNode; outStr: string; itemString: string; regExp: TRegEx; match: TMatch; key: string; pType: Boolean; begin arrString:=TArrayRecord<string>.Create(aFilter); itemString:=string.Join(',', aFilter); while Pos(#32, itemString, findStartPos)<>0 do Delete(itemString, Pos(#32, itemString, findStartPos), 1); for header in fNodes.Headers do begin for child in header.ChildNodes do begin outStr:=child.toOutputString; pType:=UpperCase(outStr).Contains('P='); outStr:=outStr.Replace('p=',' '); outStr:=outStr.Replace('g=',' '); outStr:=outStr.Replace('g2=',' '); while Pos(#32, outStr, findStartPos)<>0 do Delete(outStr, Pos(#32, outStr, findStartPos), 1); if arrString.Contains('*') then begin key:='^'; for item in arrString do begin if item<>'*' then key:=key+'(?=.*\b'+Trim(item)+'\b)'; end; key:=key+'.*$'; regExp:=TRegEx.Create(key); match:=regExp.Match(outStr); if match.Success then begin if (aRoleMode=rmImplicit) or ((aRoleMode=rmNonImplicit) and (not pType)) then begin fAdapter.remove(child.toOutputString.Replace('=',',')); header.ChildNodes.Remove(child); end; end; end else if Trim(UpperCase(outStr)) = Trim(UpperCase(itemString)) then begin if (aRoleMode=rmImplicit) or ((aRoleMode=rmNonImplicit) and (not pType)) then begin fAdapter.remove(child.toOutputString.Replace('=',',')); header.ChildNodes.Remove(child); end; end; end; end; loadRoles; notifyWatchers; end; procedure TPolicyManager.removeLink(const aLeft, aRightDomain, aRight: string); begin removeLink(DefaultDomain, aLeft, aRightDomain, aRight); end; procedure TPolicyManager.removeLink(const aLeft, aRight: string); begin removeLink(DefaultDomain, aLeft, DefaultDomain, aRight); end; destructor TPolicyManager.Destroy; begin fPoliciesList.Free; fRolesList.Free; fRolesLinks.Free; fRolesNodes.Free; fDomains.Free; fWatchers.Free; inherited; end; function TPolicyManager.domains: TList<string>; begin Result:=fDomains; end; function TPolicyManager.entitiesForRole(const aEntity: string; const aDomain: string =''): TStringDynArray; var domain: string; entity: TRoleNode; id: string; linkID: string; begin SetLength(Result, 0); if Trim(aDomain)='' then domain:=DefaultDomain else domain:=Trim(aDomain); for id in fRolesLinks.Keys do begin for linkID in fRolesLinks.Items[id] do begin if fRolesNodes.ContainsKey(linkID) then begin entity:=fRolesNodes.Items[linkID]; if SameText(Trim(UpperCase(entity.Domain)), Trim(UpperCase(domain))) and SameText(Trim(UpperCase(entity.Value)), Trim(UpperCase(aEntity))) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1]:=fRolesNodes.items[id].Value; end; end; end; end; TArray.Sort<string>(Result); end; function TPolicyManager.findRolesNode(const aDomain, aValue: string): TRoleNode; var node: TRoleNode; itemNode: TRoleNode; begin node:=nil; for itemNode in fRolesNodes.Values do begin if SameText(UpperCase(itemNode.Domain), UpperCase(Trim(aDomain))) and SameText(UpperCase(itemNode.Value), UpperCase(Trim(aValue))) then begin node:=itemNode; Break; end; end; Result := node; end; function TPolicyManager.getAdapter: IPolicyAdapter; begin result:=fAdapter; end; function TPolicyManager.implicitPolicyExists(const aValue, aResource: string): Boolean; var policyStr: string; begin Result:=False; for policyStr in policies do begin if UpperCase(policyStr).Contains(Trim(UpperCase(aValue))) and UpperCase(policyStr).Contains(Trim(UpperCase(aResource))) then begin Result:=True; Break; end; end; end; function TPolicyManager.linkExists(const aLeft: string; const aRight: string): Boolean; begin Result:=linkExists(DefaultDomain, aLeft, DefaultDomain, aRight); end; function TPolicyManager.linkExists(const aLeftDomain: string; const aLeft: string; const aRightDomain: string; const aRight: string): boolean; var leftNode: TRoleNode; rightNode: TRoleNode; item: string; lDomain, rDomain, lItem, rItem: string; begin lDomain:=Trim(aLeftDomain); rDomain:=Trim(aRightDomain); lItem:=Trim(aLeft); rItem:=Trim(aRight); {$IFDEF DEBUG} fAdapter.Logger.log(' Roles for Left: '+lItem); fAdapter.Logger.log(' Roles: '); if Length(rolesForEntity(aLeft))=0 then fAdapter.Logger.log(' No Roles found') else for item in rolesForEntity(lItem) do fAdapter.Logger.log(' '+item); fAdapter.Logger.log(' Roles for Right: '+rItem); fAdapter.Logger.log(' Roles: '); if Length(rolesForEntity(rItem))=0 then fAdapter.Logger.log(' No Roles found') else for item in rolesForEntity(rItem) do fAdapter.Logger.log(' '+item); {$ENDIF} Result:=False; if SameText(lDomain, rDomain) and (SameText(lItem, rItem) or IPmatch(lItem, rItem, False)) or (IndexStr(lItem, builtinAccounts)>-1) then begin Result:=True; exit; end; leftNode:=findRolesNode(lDomain, lItem); if not Assigned(leftNode) then Exit; rightNode:=findRolesNode(rDomain, rItem); if not Assigned(rightNode) then Exit; if fRolesLinks.ContainsKey(leftNode.ID) then begin if fRolesLinks.Items[leftNode.ID].IndexOf(rightNode.ID)>-1 then begin Result:=True; Exit; end else begin for item in fRolesLinks.Items[leftNode.ID] do begin leftNode:=fRolesNodes.Items[item]; Result:=linkExists(leftNode.Domain, leftNode.Value, rightNode.Domain, rightNode.Value); end; end; end; end; function TPolicyManager.linkExists(const aLeft, aRightDomain, aRight: string): boolean; begin Result:=linkExists(DefaultDomain, aLeft, aRightDomain, aRight); end; procedure TPolicyManager.load(const aFilter: TFilterArray); begin fAdapter.clear; fAdapter.load(aFilter); loadPolicies; loadRoles; end; procedure TPolicyManager.loadPolicies; begin fPoliciesList.Clear; // fAdapter.clear; fAdapter.load(fAdapter.Filter); // Forces the default tags fParser:=TParser.Create(fAdapter.toOutputString, ptPolicy); fParser.parse; if fParser.Status=psError then raise ECasbinException.Create('Parsing error in Model: '+fParser.ErrorMessage); fNodes:=fParser.Nodes; end; procedure TPolicyManager.loadRoles; var role: string; policyItem: string; roleList: TList<string>; sectionItem: TSection; useDomains: Boolean; tagArrayRec: TArrayRecord<string>; policyList: TList<string>; begin useDomains:=False; clearRoles; // Domains fDomains.Clear; // We get the Role Rules sectionItem:=createDefaultSection(stRoleDefinition); for role in roles do begin roleList:=TList<string>.Create; roleList.AddRange(role.Split([','])); if roleList.Count>=3 then begin tagArrayRec:=TArrayRecord<string>.Create(sectionItem.Tag); if tagArrayRec.Contains(roleList[0]) then begin if roleList.Count=3 then //No Domains addLink(roleList[1], roleList[2]) else if roleList.Count=4 then //Domains begin addLink(roleList[1], roleList[3], roleList[2]); if (trim(roleList[3])<>DefaultDomain) then fDomains.Add(trim(roleList[3])); useDomains:=true; end else raise ECasbinException.Create('The Role Rules are not correct.'); end else raise ECasbinException.Create('The Role Rules are not correct.'); end; roleList.Free; end; sectionItem.Free; fDomains.Sort; // We now need to transverse the other policy rules to build the links for policyItem in policies do begin tagArrayRec:=TArrayRecord<string>.Create(fDomains.ToArray); policyList:=TList<string>.Create; policyList.AddRange(policyItem.Split([','])); if useDomains then begin tagArrayRec.ForEach(procedure(var Value: string; Index: integer) var domIndex: integer; begin if policyItem.Contains(Value) then begin domIndex:=IndexStr(Value, policyList.ToArray); if (domIndex-1>=0) and (domIndex+1<=policyList.Count-1) then addLink(policyList[domIndex-1], Value, policyList[domIndex+1]); end; end); end else addLink(policyList[1], policyList[2]); policyList.Free; end; end; procedure TPolicyManager.notifyWatchers; var watcher: IWatcher; begin for watcher in fWatchers do watcher.update; end; function TPolicyManager.permissionExists(const aEntity, aPermission: string): Boolean; var permArray: TStringDynArray; permArrRec: TArrayRecord<string>; begin permArray:=permissionsForEntity(aEntity); permArrRec:=TArrayRecord<string>.Create(permArray); permArrRec.ForEach(procedure(var Value: string; Index: Integer) begin value:=trim(UpperCase(value)); end); Result:=permArrRec.Contains(UpperCase(aPermission)); end; function TPolicyManager.permissionsForEntity(const aEntity: string): TStringDynArray; var policyItem: string; polArray: TArrayRecord<string>; tmpArray: TArrayRecord<string>; begin SetLength(Result, 0); if Trim(aEntity)<>'' then begin for policyItem in policies do begin polArray:=TArrayRecord<string>.Create(UpperCase(policyItem).Split([','])); polArray.ForEach(procedure(var Value: string; Index: Integer) begin value:=trim(value); end); tmpArray:=TArrayRecord<string>.Create(policyItem.Split([','])); tmpArray.ForEach(procedure(var Value: string; Index: Integer) begin value:=trim(value); end); if polArray.Contains(UpperCase(aEntity)) then begin SetLength(Result, Length(Result)+1); result[Length(Result)-1]:=tmpArray[tmpArray.Count-1]; end; end; end; end; function TPolicyManager.policies: TList<string>; var node: TChildNode; headerNode: THeaderNode; sectionItem: TSection; tag: string; foundTag: Boolean; begin foundTag:=False; fPoliciesList.Clear; fRolesList.Clear; sectionItem:=createDefaultSection(stPolicyDefinition); for headerNode in fNodes.Headers do if (headerNode.SectionType=stPolicyRules) then begin for node in headerNode.ChildNodes do begin for tag in sectionItem.Tag do begin if node.Key <> tag then foundTag:=false else begin foundTag:=True; Break; end end; if foundTag then fPoliciesList.add(node.Key+AssignmentCharForPolicies+node.Value) end; end; sectionItem.Free; Result:=fPoliciesList; end; function TPolicyManager.policy(const aFilter: TFilterArray = []): string; var i: Integer; policyItem: string; test: string; testPolicy: string; strArray: TFilterArray; begin Result:='undefined'; //Clean aFilter strArray:=aFilter; for i:=0 to Length(strArray)-1 do begin strArray[i]:=trim(strArray[i]); end; testPolicy:=String.Join(',', strArray); for policyItem in policies do begin strArray:=TFilterArray(policyItem.Split([','])); //PALOFF for i:=0 to Length(strArray)-1 do begin strArray[i]:=trim(strArray[i]); end; if Length(strArray)>=1 then begin test:=String.Join(',', strArray); if UpperCase(Copy(Trim(test), findStartPos, findEndPos(testPolicy)))=UpperCase(Trim(testPolicy)) then begin Result:=Trim(strArray[Length(strArray)-1]); exit; end; end; end; end; function TPolicyManager.policyExists(const aFilter: TFilterArray): Boolean; var policyItem: string; filterRec: TArrayRecord<string>; policyRec: TArrayRecord<string>; outcome: Boolean; policyStr: string; begin Result:=False; if Length(aFilter)=0 then Exit; filterRec:=TArrayRecord<string>.Create(aFilter); filterRec.Remove('p'); filterRec.Remove('P'); filterRec.Remove('g'); filterRec.Remove('G'); filterRec.Remove('g2'); filterRec.Remove('G2'); filterRec.ForEach(procedure(var Value: string; Index: Integer) begin value:=Trim(value); end); for policyItem in policies do begin policyRec:=TArrayRecord<string>.Create(policyItem.Split([','])); policyRec.Remove('p'); policyRec.Remove('P'); policyRec.Remove('g'); policyRec.Remove('G'); policyRec.Remove('g2'); policyRec.Remove('G2'); policyRec.ForEach(procedure(var Value: string; Index: Integer) begin value:=trim(value); end); policyStr:=string.Join(',', policyRec.Items); outcome:=true; filterRec.ForEach(procedure(var Value: string; Index: Integer) begin outcome:= outcome and UpperCase(policyStr).Contains(UpperCase(Value)); end); Result:=outcome; if Result then Break; end; if not Result then Result:=roleExists(aFilter); end; function TPolicyManager.roleExists(const aFilter: TFilterArray): Boolean; var i: Integer; ruleItem: string; test: string; testRule: string; begin Result:=False; if Length(aFilter)=0 then Exit; testRule:=string.Join(',', aFilter); while Pos(#32, testRule, findStartPos)<>0 do Delete(testRule, Pos(#32, testRule, findStartPos), 1); if UpperCase(testRule).StartsWith('P,') or UpperCase(testRule).StartsWith('G,') or UpperCase(testRule).StartsWith('G2,') then begin i:=Pos(',', testRule, findStartPos); Delete(testRule, findStartPos, i); end; for ruleItem in roles do begin test:=ruleItem; while Pos(#32, test, findStartPos)<>0 do Delete(test, Pos(#32, test, findStartPos), 1); if UpperCase(test).StartsWith('P,') or UpperCase(test).StartsWith('G,') or UpperCase(test).StartsWith('G2,') then begin i:=Pos(',', test, findStartPos); Delete(test, findStartPos, i); end; Result:=string.Compare(test, testRule, [coIgnoreCase]) = 0; if Result then Break; end; end; function TPolicyManager.roles: TList<string>; var node: TChildNode; headerNode: THeaderNode; sectionItem: TSection; tag: string; foundTag: Boolean; begin foundTag:=False; fRolesList.Clear; sectionItem:=createDefaultSection(stRoleDefinition); for headerNode in fNodes.Headers do if (headerNode.SectionType=stPolicyRules) then begin for node in headerNode.ChildNodes do begin for tag in sectionItem.Tag do if node.Key=tag then begin foundTag:=True; Break; end else foundTag:=False; if foundTag then fRolesList.add(node.Key+AssignmentCharForRoles+node.Value) end; end; sectionItem.Free; Result:=fRolesList; end; function TPolicyManager.rolesForEntity(const aEntity: string; const aDomain: string = ''; const aRoleMode: TRoleMode = rmNonImplicit): TStringDynArray; var nodeEntity: TRoleNode; entity: TRoleNode; domain: string; //PALOFF id: string; begin if Trim(aDomain)='' then domain:=DefaultDomain else domain:=Trim(aDomain); nodeEntity:=findRolesNode(domain, aEntity); if Assigned(nodeEntity) then begin if fRolesLinks.ContainsKey(nodeEntity.ID) then begin for id in fRolesLinks.Items[nodeEntity.ID] do begin entity:=fRolesNodes.Items[id]; if (aRoleMode=rmImplicit) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1]:=entity.Value; end else if not implicitPolicyExists(aEntity, entity.Value) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1]:=entity.Value; end; end; end; end; TArray.Sort<string>(Result); end; function TPolicyManager.section(const aSlim: Boolean): string; var headerNode: THeaderNode; strList: TStringList; policyItem: string; begin Result:=''; for headerNode in fNodes.Headers do if headerNode.SectionType=stPolicyRules then begin Result:=headerNode.toOutputString; strList:=TStringList.Create; strList.Text:=Result; if (strList.Count>1) then begin Result:=''; if aSlim and (strList.Strings[0][findStartPos]='[') then strList.Delete(0); for policyItem in strList do Result:=Result+policyItem+sLineBreak; end; strList.Free; Exit; end; end; function TPolicyManager.toOutputString: string; begin Result:=section; end; procedure TPolicyManager.unregisterWatcher(const aWatcher: IWatcher); begin if fWatchers.Contains(aWatcher) then fWatchers.Remove(aWatcher); end; end.
unit Marvin.Desktop.GUI.Item.Cliente; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, Marvin.AulaMulticamada.Classes.Cliente, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Effects, FMX.Objects; type TfraItemListaCliente = class(TFrame) lblCliente: TLabel; lblTipoCliente: TLabel; sdw1: TShadowEffect; retFundo: TRectangle; sdw2: TShadowEffect; crcImagem: TCircle; private FNomeCliente: string; FTipoCliente: string; FCliente: TMRVCliente; procedure SetNomeCliente(const Value: string); procedure SetTipoCliente(const Value: string); procedure SetCliente(const Value: TMRVCliente); { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; { Public declarations } property NomeCliente: string read FNomeCliente write SetNomeCliente; property TipoCliente: string read FTipoCliente write SetTipoCliente; property Cliente: TMRVCliente read FCliente write SetCliente; end; implementation {$R *.fmx} { TfraItemListaCliente } constructor TfraItemListaCliente.Create(AOwner: TComponent); begin inherited; FCliente := TMRVCliente.Create; end; destructor TfraItemListaCliente.Destroy; begin FCliente.DisposeOf; FCliente := nil; inherited; end; procedure TfraItemListaCliente.Init; begin end; procedure TfraItemListaCliente.SetCliente(const Value: TMRVCliente); begin FCliente.Assign(Value); Self.NomeCliente := FCliente.Nome; Self.TipoCliente := FCliente.TipoClienteId.ToString; end; procedure TfraItemListaCliente.SetNomeCliente(const Value: string); begin FNomeCliente := Value; lblCliente.Text := FNomeCliente; end; procedure TfraItemListaCliente.SetTipoCliente(const Value: string); begin FTipoCliente := Value; lblTipoCliente.Text := FTipoCliente; end; end.
unit ReasonChangePoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, ReasonChange, Employee; type // для причины изменений TReasonChangeDataPoster = class(TImplementedDataPoster) private FAllEmployee: TEmployees; procedure SetAllEmployee(const Value: TEmployees); public property AllEmployee: TEmployees read FAllEmployee write SetAllEmployee; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils; { TReasonChangeDataPoster } constructor TReasonChangeDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_REASON_CHANGE'; KeyFieldNames := 'REASON_CHANGE_ID'; FieldNames := 'REASON_CHANGE_ID, VCH_REASON_CHANGE_NAME, EMPLOYEE_ID, DTM_CHANGE'; AccessoryFieldNames := 'REASON_CHANGE_ID, VCH_REASON_CHANGE_NAME, EMPLOYEE_ID, DTM_CHANGE'; AutoFillDates := false; Sort := 'REASON_CHANGE_ID'; end; function TReasonChangeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TReasonChangeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TReasonChange; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TReasonChange; o.ID := ds.FieldByName('REASON_CHANGE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_REASON_CHANGE_NAME').AsString); if (ds.FieldByName('EMPLOYEE_ID').AsInteger > 0) and (Assigned(FAllEmployee)) then o.Employee := FAllEmployee.ItemsByID[ds.FieldByName('EMPLOYEE_ID').AsInteger] as TEmployee; o.DtmChange := ds.FieldByName('DTM_CHANGE').AsDateTime; ds.Next; end; ds.First; end; end; function TReasonChangeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TReasonChange; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := AObject as TReasonChange; ds.FieldByName('REASON_CHANGE_ID').AsInteger := o.ID; ds.FieldByName('VCH_REASON_CHANGE_NAME').AsString := o.Name; if Assigned (o.Employee) then ds.FieldByName('EMPLOYEE_ID').AsInteger := o.Employee.ID; ds.FieldByName('DTM_CHANGE').AsDateTime := o.DtmChange; ds.Post; if o.ID = 0 then o.ID := ds.FieldByName('REASON_CHANGE_ID').Value; end; procedure TReasonChangeDataPoster.SetAllEmployee(const Value: TEmployees); begin if FAllEmployee <> Value then FAllEmployee := Value; end; end.
unit TestObj; interface uses Classes, SysUtils, TestIntf, Forms, MDIForm, SvcInfoIntf; type TtestObj = class(TInterfacedObject, ITest, ISvcInfo) private protected {ITest} procedure Test; {ISvrInfo} function GetModuleName: String; function GetTitle: String; function GetVersion: String; function GetComments: String; public destructor Destroy; override; end; implementation uses SysFactory, SysFactoryEx, MainFormIntf, SysSvc; //_Sys { TtestObj } destructor TtestObj.Destroy; begin inherited; end; function TtestObj.GetComments: String; begin Result := '测试接口,测试用的,在test.bpl包里实现。具体请看test包的TestObj单元'; end; function TtestObj.GetModuleName: String; begin Result := ExtractFileName(SysUtils.GetModuleName(HInstance)); end; function TtestObj.GetTitle: String; begin Result := '测试接口(ITest)'; end; function TtestObj.GetVersion: String; begin Result := '20100421.001'; end; procedure TtestObj.Test; begin // sys.Form.CreateForm(TfrmMDI); (SysService as IFormMgr).CreateForm(TfrmMDI); end; function CreateTestObject(param: Integer): TObject; begin Result := TtestObj.Create; end; initialization //TIntfFactory TSingletonFactory.Create(ITest, @CreateTestObject); finalization end.
unit m_conn; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ZConnection, ZDataset, IniFiles, BCrypt; type { Tdmconn } Tdmconn = class(TDataModule) Conn: TZConnection; GetRoles: TZQuery; ZQFirmasReport: TZQuery; ZQs: TZQuery; procedure DataModuleCreate(Sender: TObject); function AuthUser(username, passwd: string): Boolean; private public Empresa: string; Autoriza: string; Entrega: string; FormatoCodigo: string; DirEmpresa: string; MostrarFechaResg: string; ImgEmpresa: string; Theme: string; CPrinter: string; IPrinter: integer; // Datos del usuario Nombre: string; Apellido: string; UserId: integer; RoleId: integer; end; var dmconn: Tdmconn; implementation {$R *.lfm} { Tdmconn } function Tdmconn.AuthUser(username, passwd: string) : Boolean; var Cifrar : TBCryptHash; Verify : Boolean; begin Verify:=false; // Obtener datos del usuario ZQs.Close; ZQs.SQL.Text:='SELECT id, name, surname, username, passwd FROM user_users'+ ' WHERE username LIKE :user'; ZQs.Params.ParamByName('user').AsString:=username; ZQs.Open; if ZQs.RecordCount > 0 then begin Cifrar := TBCryptHash.Create; Verify := Cifrar.VerifyHash(passwd, ZQs.FieldByName('passwd').AsString); Cifrar.Free; if Verify then begin Nombre:=ZQs.FieldByName('name').AsString; Apellido:=ZQs.FieldByName('surname').AsString; UserId:=ZQs.FieldByName('id').AsInteger; // RoleId:=ZQs.FieldByName('role_id').AsInteger; // Obtener permisos del usuario end; end; Result:=Verify; end; procedure Tdmconn.DataModuleCreate(Sender: TObject); var INI: TIniFile; begin if FileExists('config.ini') then begin INI:=TIniFile.Create('config.ini'); Conn.Connect; // GetRoles.Open; Theme:=INI.ReadString('config', 'theme_app', ''); CPrinter:=INI.ReadString('config', 'cprinter', ''); IPrinter:=StrToInt(INI.ReadString('config', 'iprinter', '')); // Obtener configuración de base de datos ZQs.SQL.Text:='SELECT id, skey, svalue FROM general_config WHERE '+ 'applications_id = 4 and status = 1'; ZQs.Open; ZQs.First; while not ZQs.EOF do begin case ZQs.FieldByName('skey').AsString of 'inventory_entrega': Entrega:=ZQs.FieldByName('svalue').AsString; 'inventory_autoriza': Autoriza:=ZQs.FieldByName('svalue').AsString; 'inventory_dir_empresa': DirEmpresa:=ZQs.FieldByName('svalue').AsString; 'inventory_empresa': Empresa:=ZQs.FieldByName('svalue').AsString; 'inventory_show_report_entrega': MostrarFechaResg:=ZQs.FieldByName('svalue').AsString; end; ZQs.Next; end; ZQs.Close; end else begin Conn.Connect; end; end; end.
unit Material; (* Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the gl3ds main unit. * * The Initial Developer of the Original Code is * Noeska Software. * Portions created by the Initial Developer are Copyright (C) 2002-2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * M van der Honing * Sascha Willems * Jan Michalowsky * *) interface uses classes; type TBaseMaterial = class; TBaseMaterialClass = class of TBaseMaterial; TBaseMaterial = class(TComponent) protected FId: Integer; FAmbB: Single; FAmbG: Single; FAmbR: Single; FDifB: Single; FDifG: Single; FDifR: Single; FSpcB: Single; FSpcG: Single; FSpcR: Single; FEmiB: Single; FEmiG: Single; FEmiR: Single; FShininess: Single; FTransparency: Single; FIsAmbient: Boolean; FIsDiffuse: Boolean; FIsSpecular: Boolean; FIsEmissive: Boolean; FBumpMapFilename: string; FBumpmapstrength: Single; FFileName: string; FHasBumpmap: Boolean; FHasMaterial: Boolean; FHasOpacmap: Boolean; FHasTexturemap: Boolean; FName: string; FOpacMapFilename: string; FRot: Single; FTexId: Integer; FTwoSided: Boolean; FUoff: Single; FUs: Single; FVoff: Single; FVs: Single; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; property Id: Integer read FId write FId; property AmbientBlue: Single read FAmbB write FAmbB; property AmbientGreen: Single read FAmbG write FAmbG; property AmbientRed: Single read FAmbR write FAmbR; property DiffuseBlue: Single read FDifB write FDifB; property DiffuseGreen: Single read FDifG write FDifG; property DiffuseRed: Single read FDifR write FDifR; property SpecularBlue: Single read FSpcB write FSpcB; property SpecularGreen: Single read FSpcG write FSpcG; property SpecularRed: Single read FSpcR write FSpcR; property EmissiveBlue: Single read FEmiB write FEmiB; property EmissiveGreen: Single read FEmiG write FEmiG; property EmissiveRed: Single read FEmiR write FEmiR; property Shininess: Single read FShininess write FShininess; property Transparency: Single read FTransparency write FTransparency; property IsAmbient: Boolean read FIsAmbient write FIsAmbient; property IsDiffuse: Boolean read FIsDiffuse write FIsDiffuse; property IsSpecular: Boolean read FIsSpecular write FIsSpecular; property IsEmissive: Boolean read FIsEmissive write FIsEmissive; property BumpMapFilename: string read FBumpMapFilename write FBumpMapFilename; property Bumpmapstrength: Single read FBumpmapstrength write FBumpmapstrength; property HasBumpmap: Boolean read FHasBumpmap write FHasBumpmap; property HasMaterial: Boolean read FHasMaterial write FHasMaterial; property HasOpacmap: Boolean read FHasOpacmap write FHasOpacmap; property HasTexturemap: Boolean read FHasTexturemap write FHasTexturemap; property Name: string read FName write FName; property FileName: string read FFileName write FFileName; property OpacMapFilename: string read FOpacMapFilename write FOpacMapFilename; property Rotate: Single read FRot write FRot; property TexID: Integer read FTexId write FTexID; property TextureFilename: string read FFileName write FFileName; property TextureID: Integer read FTexId; property TwoSided: Boolean read FTwoSided write FTwoSided; property Uoff: Single read FUoff write FUoff; property Us: Single read FUs write FUs; property Voff: Single read FVoff write FVoff; property Vs: Single read FVs write FVs; procedure Apply; virtual; abstract; procedure UpdateTexture; virtual; abstract; end; implementation uses SysUtils; procedure TBaseMaterial.Assign(Source: TPersistent); begin if Source is TBaseMaterial then begin With TBaseMaterial(source) do begin self.FAmbB := FAmbB; self.FAmbG := FAmbG; self.FAmbR := FAmbR; self.FBumpMapFilename := FBumpMapFilename; self.FBumpmapstrength := FBumpmapstrength; self.FDifB := FDifB; self.FDifG := FDifG; self.FDifR := FDifR; self.FFileName := FFileName; self.FHasBumpmap := FHasBumpmap; self.FHasMaterial := FHasMaterial; self.FHasOpacmap := FHasOpacmap; self.FHasTexturemap := FHasTexturemap; self.FIsAmbient := FIsAmbient; self.FIsDiffuse := FIsDiffuse; self.FIsSpecular := FIsSpecular; self.FName := FName; self.FOpacMapFilename := FOpacMapFilename; self.FRot := FRot; self.FSpcB := FSpcB; self.FSpcG := FSpcG; self.FSpcR := FSpcR; self.FTexId := FTexId; self.FTransparency := FTransparency; self.FTwoSided := FTwoSided; self.FUoff := FUoff; self.FUs := FUs; self.FVoff := FVoff; self.FVs := FVs; self.FShininess := FShininess; end; end else inherited; end; constructor TBaseMaterial.Create(AOwner: TComponent); begin inherited Create(AOwner); FDifR := 1.0; FDifG := 1.0; FDifB := 1.0; FIsDiffuse := False; FAmbR := 0.0; FAmbG := 0.0; FAmbB := 0.0; FIsAmbient := False; FSpcR := 0.0; FSpcG := 0.0; FSpcB := 0.0; FIsSpecular := False; FShininess:=0.0; FHasTextureMap := False; FTransparency := 1.0; end; end.
(* Contient un objet TBZParallelThread qui permet d'exécuter des opérations en parallele facilement grâce au multithreading. ------------------------------------------------------------------------------------------------------------- @created(24/02/2019) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(Creation : 24/06/2019) @item(Mise à jour : ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes :)@br Lazarus dispose de cette possibilité nativement, mais est un peu plus compliqué à mettre en place. cf : https://wiki.freepascal.org/Parallel_procedures/fr Inspirer du code source de Paul Toth pour Delphi http://lookinside.free.fr/delphi.php?Multithreading) ------------------------------------------------------------------------------------------------------------- @bold(Dependances) : Aucune ------------------------------------------------------------------------------------------------------------- @bold(Credits :)@br @unorderedList( @item(J.Delauney (BeanzMaster)) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) unit BZParallelThread; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils; Type { Type de procedure simple d'execution du tratement à effectuer dans les threads } TBZParallelProc = procedure(Index: Integer; Data : Pointer); { Type de procedure objet d'execution du tratement à effectuer dans les threads } TBZParallelProcEvent = procedure(Sender: TObject; Index: Integer ; Data : Pointer) of object; { Type de procedure objet pour la progression de l'execution } TBZParallelProgressEvent = procedure(Sender: TObject; Index: Integer) of object; { Direction de traitement des données. @br Vers l'avant (Incrementation de l'index) ou vers l'arrière (Décrementation de l'index). } TBZParallelProgressMode = (ppmForward, ppmBackward); { Objet servant à l'initialisation du code à paralleliser dans des threads en mode objet } TBZParallelThread = class private FThreadCount : Integer; FSystemThreadCount : Integer; FTaskCount : Integer; FCurrentIndex : Integer; FExecuteMode : TBZParallelProgressMode; //FFromIndex, FToIndex : Int64; FCount : Integer; FData : Pointer; FOnExecute : TBZParallelProcEvent; FOnProgress : TBZParallelProgressEvent; procedure SetThreadCount(const AValue : Integer); protected procedure ExecuteProgressProc; virtual; procedure ExecuteProgressProcWithData; virtual; public { Creation } constructor Create; overload; { Destruction } constructor Create(DataPtr : Pointer); { Renvoie un pointeur sur les données secondaire } function GetData : Pointer; { Lancement du traitement à affectuer. Le paramètre "Count" désigne le nombre de donnée totale à traiter } procedure Run(Count: Int64); overload; { Lancement du traitement à affectuer à partir de l'index "FromIndex" jusqu'à "ToIndex". @br Si FromIndex est plus grand que ToIndex alors l'avancer du traitement se fera vers l'arrière (de ToIndex jusqu'à FromIndex) } procedure Run(FromIndex, ToIndex : Int64); overload; { Retourne le nombre de threads maximum que le processeur peux gérer } property SystemThreadCount : Integer read FSystemThreadCount; { Nombre de threads à allouer au traitement. Note : il est préférable de ne pas dépasser SystemThreadCount } property ThreadCount : Integer Read FThreadCount write SetThreadCount; { Evenement déclencher pour le traitement de chaque données } property OnExecute: TBZParallelProcEvent read FOnExecute write FOnExecute; { Evenement pour controler la progression de la tâche } property OnProgress: TBZParallelProgressEvent read FOnProgress write FOnProgress; end; { Procedure de lancement d'un traitement paralléliser simple. @br "Data" est un pointer permettant d'acceder à des paramètres ou valeurs nécessaire au traitement } procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProc;Const DataPtr : Pointer = nil; Const ThreadCount : Byte = 4); overload; { Procedure de lancement d'un traitement paralléliser objet } procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; const ThreadCount : Byte = 4); overload; { Procedure de lancement d'un traitement paralléliser objet avec data } procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; Const DataPtr : Pointer; const ThreadCount : Byte = 4); overload; { Procedure de lancement d'un traitement paralléliser objet avec data et évènement pour controler la progression de la tâche } procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; ProgressEvent : TBZParallelProgressEvent; Const DataPtr : Pointer; const ThreadCount : Byte = 4); overload; threadvar { Variable globale servant à contenir le thread en cours d'execution. @br Utile dans le cas de synchronisation. Vous pouvez la définir dans vos propres descendants TThread } BZCurrentParallelThread : TThread; implementation uses BZSystem, BZLogger; type // Thread pour la parallelisation en mode objet { TBZParallelTask } TBZParallelTask = class(TThread) private FData : Pointer; FID : Integer; FParallelThread : TBZParallelThread; protected procedure Execute; override; procedure DoTerminate; override; public constructor Create(AParallelThread : TBZParallelThread; anID : Integer); overload; end; type // Thread pour la parallelisation en mode simple TBZDirectParallelTask = Class; { TBZDirectParallelRunner : Gestionnaire de threads pour la parallelisation en mode simple} TBZDirectParallelRunner = Class private FData : Pointer; FThreadCount : Byte; FWorkers : array of TBZDirectParallelTask; public MaxIndex, CurrentIndex : Integer; Constructor Create(Count : Integer; Const Data : Pointer = nil; Const ThreadCount : Byte = 4); Destructor Destroy; override; procedure Run(FromIndex : Integer; aParallelProc : TBZParallelProc); property Data : Pointer read FData write FData; end; { TBZDirectParallelTask } TBZDirectParallelTask = class(TThread) private FID : Integer; FRunner : TBZDirectParallelRunner; FParallelProc : TBZParallelProc; protected procedure Execute; override; public constructor Create(Runner : TBZDirectParallelRunner; AParallelProc : TBZParallelProc; anID : Integer); end; {%region=====[ TBZDirectParallelRunner ]================================================} constructor TBZDirectParallelRunner.Create(Count : Integer; const Data : Pointer; const ThreadCount : Byte); begin MaxIndex := Count; FData := Data; FThreadCount := ThreadCount; SetLength(FWorkers, ThreadCount); end; destructor TBZDirectParallelRunner.Destroy; Var i : Byte; begin SetLength(FWorkers, 0); FWorkers := nil; inherited Destroy; end; procedure TBZDirectParallelRunner.Run(FromIndex : Integer; aParallelProc : TBZParallelProc); Var I: integer; begin CurrentIndex := FromIndex; for I := 0 to FThreadCount - 1 do FWorkers[I] := TBZDirectParallelTask.Create(Self, aParallelProc, I+1); while CurrentIndex < MaxIndex do sleep(0); //sleep(100); end; {%endregion%} {%region=====[ TBZDirectParallelTask ===================================================} constructor TBZDirectParallelTask.Create(Runner : TBZDirectParallelRunner; AParallelProc : TBZParallelProc; anID : Integer); begin inherited Create(false); FParallelProc := AParallelProc; FRunner := Runner; FID := anID; FreeOnTerminate := True; end; procedure TBZDirectParallelTask.Execute; var Index: integer; begin BZCurrentParallelThread := Self; while not Terminated do begin Index := InterlockedIncrement(FRunner.CurrentIndex); if Index > FRunner.MaxIndex then break; FParallelProc(Index, FRunner.Data); end; end; {%endregion%} {%region=====[ TBZParallelTask =========================================================} constructor TBZParallelTask.Create(AParallelThread : TBZParallelThread; anID : Integer); begin inherited Create(False); FParallelThread := AParallelThread; FID := anID; FData := FParallelThread.GetData; FreeOnTerminate := True; end; procedure TBZParallelTask.Execute; begin BZCurrentParallelThread := Self; if FData = nil then FParallelThread.ExecuteProgressProc else FParallelThread.ExecuteProgressProcWithData; end; procedure TBZParallelTask.DoTerminate; begin inherited DoTerminate; // BZCurrentParallelThread := nil; end; {%endregion%} {%region=====[ TBZParallelThread ]======================================================} constructor TBZParallelThread.Create; begin inherited; FSystemThreadCount := GetProcessorCount; FThreadCount := FSystemThreadCount; FData := nil; end; constructor TBZParallelThread.Create(DataPtr : Pointer); begin Create; FData := DataPtr; end; function TBZParallelThread.GetData : Pointer; begin Result := FData; end; procedure TBZParallelThread.SetThreadCount(const AValue : Integer); begin if FThreadCount = AValue then Exit; Assert((AValue < FSystemThreadCount),'It is not recommended to have more threads than your cpu can support'); FThreadCount := AValue; if FThreadCount < 1 then FThreadCount := 1; //FSystemThreadCount; end; procedure TBZParallelThread.Run(FromIndex, ToIndex : Int64); var I: Word; begin if not Assigned(FOnExecute) then Exit; FTaskCount := FThreadCount; if ToIndex > FromIndex then begin FExecuteMode := ppmForward; FCurrentIndex := FromIndex-1; FCount := Abs(ToIndex - FromIndex)+1; // 319 - 0 = 320 ; 20 - 10 = 11 end else begin FExecuteMode := ppmBackward; FCurrentIndex := ToIndex+1; FCount := FromIndex+1; end; for I := 1 to FThreadCount - 1 do begin TBZParallelTask.Create(Self, I+1); end; if FData = nil then ExecuteProgressProc else ExecuteProgressProcWithData; while FTaskCount > 0 do Sleep(0); end; procedure TBZParallelThread.Run(Count: Int64); var I: Word; begin if not Assigned(FOnExecute) then Exit; FTaskCount := FThreadCount; FCurrentIndex := -1; FCount := Count; FExecuteMode := ppmForward; for I := 1 to FThreadCount - 1 do begin TBZParallelTask.Create(Self,i+1); end; if FData = nil then ExecuteProgressProc else ExecuteProgressProcWithData; while FTaskCount > 0 do Sleep(0); end; procedure TBZParallelThread.ExecuteProgressProc; var Index: Integer; begin try if FExecuteMode = ppmForward then begin Index := InterlockedIncrement(FCurrentIndex); while Index < FCount do begin If Index > FCount then Break; if FOnProgress<>nil then FOnProgress(Self, Index); //TThread.Synchronize(BZCurrentParallelThread,@FOnProgress); FOnExecute(Self, Index,nil); Index := InterlockedIncrement(FCurrentIndex); end; end else Begin Index := InterlockedDecrement(FCurrentIndex); while Index > FCount do begin If Index < FCount then Break; if FOnProgress<>nil then FOnProgress(Self, FCount-Index); FOnExecute(Self, Index,nil); Index := InterlockedDecrement(FCurrentIndex); end; end; finally InterlockedDecrement(FTaskCount); end; end; procedure TBZParallelThread.ExecuteProgressProcWithData; var Index: Integer; begin try if FExecuteMode = ppmForward then begin Index := InterlockedIncrement(FCurrentIndex); while Index < FCount do begin If Index > FCount then Break; if FOnProgress<>nil then FOnProgress(Self, Index); FOnExecute(Self, Index,FData); Index := InterlockedIncrement(FCurrentIndex); end; end else Begin Index := InterlockedDecrement(FCurrentIndex); while Index > FCount do begin If Index < FCount then Break; if FOnProgress<>nil then FOnProgress(Self, FCount-Index); FOnExecute(Self, Index,FData); Index := InterlockedDecrement(FCurrentIndex); end; end; finally InterlockedDecrement(FTaskCount); end; end; {%endregion%} procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProc; const DataPtr : Pointer; const ThreadCount : Byte); Var ThreadRunner : TBZDirectParallelRunner; begin ThreadRunner := TBZDirectParallelRunner.Create(ToIndex,DataPtr,ThreadCount); Try ThreadRunner.Run(FromIndex, ParallelProc); finally FreeAndNil(ThreadRunner); end; end; procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; const ThreadCount : Byte); Var Parallelizer : TBZParallelThread; begin Parallelizer := TBZParallelThread.Create; try Parallelizer.ThreadCount := ThreadCount; Parallelizer.OnExecute := ParallelProc; Parallelizer.Run(FromIndex, ToIndex); finally Parallelizer.Free; end; end; procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; const DataPtr : Pointer; const ThreadCount : Byte); Var Parallelizer : TBZParallelThread; begin Parallelizer := TBZParallelThread.Create(DataPtr); try Parallelizer.ThreadCount := ThreadCount; Parallelizer.OnExecute := ParallelProc; Parallelizer.Run(FromIndex, ToIndex); finally Parallelizer.Free; end; end; procedure ParallelFor(FromIndex, ToIndex : Int64; ParallelProc : TBZParallelProcEvent; ProgressEvent : TBZParallelProgressEvent; Const DataPtr : Pointer; const ThreadCount : Byte); Var Parallelizer : TBZParallelThread; begin Parallelizer := TBZParallelThread.Create(DataPtr); try Parallelizer.ThreadCount := ThreadCount; Parallelizer.OnExecute := ParallelProc; Parallelizer.OnProgress := ProgressEvent; Parallelizer.Run(FromIndex, ToIndex); finally Parallelizer.Free; end; end; //====================================================================================== initialization BZCurrentParallelThread:=nil; finalization end.
{ Subroutine STRING_CMLINE_SET (ARGC, ARGV, PGNAME) * * This routine is used to register information about the call arguments that * is passed to top level programs. The call to this routine is automatically * inserted at the start of every top level program by SST. It must not be * declared in any inlude file since SST always writes the declaration as * if the routine was not already declared. * * ARGC is the number of command line arguments, and ARGV is an array of pointers * to null-terminated strings which are the command line arguments. * * This version is for the Microsoft Win32 API. ARGC and ARGV are ignored, * since we use GetCommandLine to read the command line. } module string_cmline_set; define string_cmline_set; %include 'string2.ins.pas'; %include 'string_sys.ins.pas'; procedure sys_init; {init SYS library} extern; procedure util_init; {init UTIL library} extern; procedure string_cmline_set ( val argc: sys_int_machine_t; {number of command line arguments} val argv: univ_ptr; {pointer to array of pointers} in pgname: string); {null-terminated program name string} var str_p: ^string; {pointer to NULL terminated command line str} vstr: string_var4_t; {scratch var string} stat: sys_err_t; begin sys_init; {one-time initialization of SYS library} util_init; {one-time initialization of UTIL library} vstr.max := size_char(vstr.str); {init local var string} cmline_token_last.max := size_char(cmline_token_last.str); {init com block var str} cmline_token_last.len := 0; prog_name.max := size_char(prog_name.str); prog_name.len := 0; nodename.max := size_char(nodename.str); nodename.len := 0; vcmline.max := size_char(vcmline.str); vcmline.len := 0; string_vstring (prog_name, pgname, -1); {save program name in common block} progname_set := true; {indicate PROG_NAME all set} str_p := GetCommandLineA; {get pointer to raw command line string} if str_p <> nil then begin string_vstring (vcmline, str_p^, -1); {save var string copy of command line} end; vcmline_parse := 1; {init parse index to start of command line} string_token ( {move past first token which is program name} vcmline, vcmline_parse, vstr, stat); vcmline_parse_start := vcmline_parse; {save parse index for first argument} cmline_next_n := 1; {next token will be first argument} cmline_reuse := false; {init to not re-use previous token} end;
// ################################## // ###### IT PAT 2017 ####### // ###### PHASE 3 ####### // ###### Tiaan van der Riel ####### // ################################## unit frmLogIn_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfrmLogIn = class(TForm) lblLogInHeading: TLabel; edtUsername: TEdit; edtPassword: TEdit; lblUsername: TLabel; lblPassword: TLabel; btnLogIntoAccount: TButton; btnBack: TButton; btnHelp: TButton; procedure btnBackClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnHelpClick(Sender: TObject); procedure btnLogIntoAccountClick(Sender: TObject); private { Private declarations } sEnteredUsername: string; sEnteredPassword: string; { } procedure GoToUserHomePage; { This procedure will execute when the user has succesfully logged in. It will set the variable sLoggedInUser to the user, which will be used by frmUserHomePage. It will also show the home page form. } public { public declarations } end; var frmLogIn: TfrmLogIn; implementation Uses frmLansLandia_u, dmAccounts_u, frmUserHomePage_u; {$R *.dfm} /// ============================= Back Button ============================== procedure TfrmLogIn.btnBackClick(Sender: TObject); begin frmLogIn.Close; lblUsername.Font.Color := clWhite; lblPassword.Font.Color := clWhite; edtUsername.Text := ''; edtPassword.Text := ''; lblUsername.Caption := 'Username:'; lblPassword.Caption := 'Password:'; end; /// ============================= Help Button ============================== procedure TfrmLogIn.btnHelpClick(Sender: TObject); var tHelp: TextFile; sLine: string; sMessage: string; begin sMessage := '========================================'; AssignFile(tHelp, 'Help_LogIn.txt'); try { Code that checks to see if the file about the sponsors can be opened - displays error if not } reset(tHelp); Except ShowMessage('ERROR: The help file could not be opened.'); Exit; end; while NOT EOF(tHelp) do begin Readln(tHelp, sLine); sMessage := sMessage + #13 + sLine; end; sMessage := sMessage + #13 + '========================================'; CloseFile(tHelp); ShowMessage(sMessage); end; /// ============================= Log Into Account ========================= procedure TfrmLogIn.btnLogIntoAccountClick(Sender: TObject); var bUsernameFound: boolean; begin sEnteredUsername := edtUsername.Text; sEnteredPassword := edtPassword.Text; if sEnteredUsername = '' then begin ShowMessage('Please enter your Username'); lblUsername.Font.Color := clred; lblUsername.Caption := '***Username:'; Exit; end; if sEnteredPassword = '' then begin ShowMessage('Please enter your Password'); lblPassword.Font.Color := clred; lblPassword.Caption := '***Password:'; Exit; end; bUsernameFound := false; dmAccounts.tblAccounts.First; while (NOT dmAccounts.tblAccounts.EOF) AND (bUsernameFound = false) do Begin if sEnteredUsername = dmAccounts.tblAccounts['Username'] then Begin bUsernameFound := true; // ShowMessage('Username Found'); End else Begin dmAccounts.tblAccounts.Next; End; End; // End of searching for username (EOF) if bUsernameFound = false then // Username was not found Begin ShowMessage('Username or Password incorrect'); End; { If the Username was found the code has to check that the password that the user entered matches the password for the account } if bUsernameFound = true then Begin if sEnteredPassword = dmAccounts.tblAccounts['Password'] then Begin ShowMessage('Log In Successful.'); ShowMessage('Welcome to Lans-Landia ' + dmAccounts.tblAccounts['Name'] + ' ' + dmAccounts.tblAccounts['Surname'] + '.'); GoToUserHomePage; // procedure End // End of correct password Else Begin ShowMessage('Password or Username incorrect'); Exit; End; // End of else End; // End of username Found end; /// =========================== Form Close ================================= procedure TfrmLogIn.FormClose(Sender: TObject; var Action: TCloseAction); begin frmWelcome.Show; end; /// ======================== Procedure GoToUserHomePage ===================== procedure TfrmLogIn.GoToUserHomePage; begin /// { The function of this piece of code is to set the variable sLoggedInUser to the username of the user that has successfully logged in. The variable is one of the form frmUserHomePage } frmUserHomePage.sLoggedInUser := edtUsername.Text; /// lblUsername.Font.Color := clWhite; lblPassword.Font.Color := clWhite; edtUsername.Text := ''; edtPassword.Text := ''; lblUsername.Caption := 'Username:'; lblPassword.Caption := 'Password:'; frmLogIn.Hide; frmLogIn.Close; frmUserHomePage.ShowModal; end; end.
(* Category: SWAG Title: DATA TYPE & COMPARE ROUTINES Original name: 0015.PAS Description: Double Words Author: MARK OUELLET Date: 01-27-94 11:59 *) { > I'm trying to read a record from a file of byte. One of the variables in > read is the record is a 4 byte unsigned integer (DWORD). Since the > filetype doesn't allow me to read a dword at once I have to construct it > myself. > Could somebody please tell me how to construct my dword? Type DWORD = record case byte of 0 : (Full : longint); 1 : (HiWord, LoWord : word); 2 : (Hw_HiByte, Hw_LoByte, Lw_HiByte, Lw_LoByte : byte); 3 : (FourBytes : array[0..3] of byte); end; Here is an example: } uses crt; Type DWord = record case byte of 0 : (Full : longint); 1 : (HiWord, LoWord : word); 2 : (Hw_HiByte, Hw_LoByte, Lw_HiByte, Lw_LoByte : byte); 3 : (FourBytes : array[0..3] of byte); 4 : (TwoWords : array[0..1] of word); end; var F : file of longint; B : file of byte; MyDword : Dword; MyLong : longint; MyWord : word; MyByte, Index : byte; begin clrscr; assign(F, 'MyLong.dat'); rewrite(F); MyLong := $12345678; write(F, MyLong); MyLong := 0; Close(F); assign(B, 'MyLong.dat'); reset(B); Seek(B, 0); { Go back to first record in file} for Index := 0 to 3 do read(B, MyDword.Fourbytes[Index]); writeln($12345678); writeln(MyDword.Full); writeln; writeln(MyDword.HiWord); writeln(MyDword.LoWord); writeln; writeln(MyDword.Hw_HiByte); writeln(MyDword.Hw_LoByte); writeln(MyDword.Lw_HiByte); writeln(MyDword.Lw_LoByte); writeln; for Index := 0 to 3 do writeln(MyDword.FourBytes[Index]); writeln; for Index := 0 to 1 do writeln(MyDword.TwoWords[Index]); Close(B); reset(F); while keypressed do readkey; readkey; Seek(F, 0); { Go back to first record in file} read(F, MyDword.Full); ClrScr; writeln($12345678); writeln(MyDword.Full); writeln; writeln(MyDword.HiWord); writeln(MyDword.LoWord); writeln; writeln(MyDword.Hw_HiByte); writeln(MyDword.Hw_LoByte); writeln(MyDword.Lw_HiByte); writeln(MyDword.Lw_LoByte); writeln; for Index := 0 to 3 do writeln(MyDword.FourBytes[Index]); writeln; for Index := 0 to 1 do writeln(MyDword.TwoWords[Index]); close(F); while keypressed do readkey; readkey; end. { Compiled and Tested with BP 7.x It will, write a file of Longint, write 12345678 Hex to it, read it as a file of byte, display most representation of it, then close it and reopen it as a file of LongInt again read one longint and again display the representations of it. PS. There is a pause after the first display (Read as a file of bytes), any key presents the second display (Read as a file of bytes), and another pause to allow you to see that it does display the same thing. Any key then terminates the program. }
unit Kartoteka; interface uses sysutils; const losowosc=19; imiona: array [0..losowosc] of string[25] = ('Maria', 'Krystyna', 'Anna', 'Barbara', 'Teresa', 'Elzbieta', 'Janina', 'Zofia', 'Jadwiga', 'Danuta', 'Halina', 'Irena', 'Ewa', 'Malgorzata', 'Helena', 'Grazyna', 'Bozena', 'Stanislawa', 'Jolanta', 'Marianna'); nazwiska: array [0..losowosc] of string[25] = ('Nowak', 'Kowalski', 'Wisniewski', 'Wojcik', 'Kowalczyk', 'Kaminski', 'Lewandowski', 'Zielinski', 'Szymanski', 'Wozniak', 'Dobrowski', 'Kozlowski', 'Jankowski', 'Mazur', 'Wojciechowski', 'Kwiatkowski', 'Krawczyk', 'Kaczmarek', 'Piotrowski', 'Grabowski'); pesele: array [0..losowosc] of string[11] = ('04230903737', '00213019310', '43012703831', '22031407450', '37042004415', '84052016538', '80071304652', '45040605330', '61010817930', '73610201478', '18081203030', '59031817259', '51033014252', '00301313951', '76021318176', '40061901951', '40313009703', '42853109169', '55120119561', '82091804509'); type TPesel=string[11]; TOsoba = record imie: string[25]; nazwisko: string[25]; pesel: TPesel; urodziny:TDateTime; end; Pelem = ^Elem; Elem = record Dane: TOsoba; Next: PElem; end; procedure push(var glowa: Pelem); procedure push_bck(var glowa: Pelem); procedure push_sort(var glowa: Pelem; const nowy: Pelem); procedure pop(var glowa: Pelem); procedure pop_bck(var glowa: PElem); procedure usun(var glowa:PElem; const Pesel:TPesel); procedure print(const glowa: Pelem); function CreateOsoba(): TOsoba; implementation function ZwrocDate(const tmp:PElem):TDateTime; var miesiac, rok, dzien:Word; begin dzien:=StrToInt(tmp^.dane.pesel[5..6]); miesiac:=StrToInt(tmp^.dane.pesel[3..4]); rok:=StrToInt(tmp^.dane.pesel[1..2]); Case tmp^.dane.pesel[3] of '0','1' : begin rok:=rok+1900; end; '2','3' : begin miesiac:=miesiac mod 20; rok:=rok+2000; end; '4','5' : begin miesiac:=miesiac mod 40; rok:=rok+2100; end; '6','7' : begin miesiac:=miesiac mod 60; rok:=rok+2200; end; '8','9' : begin miesiac:=miesiac mod 80; rok:=rok+1800; end; end; ZwrocDate:=EncodeDate(rok,miesiac,dzien); end; function CreateOsoba(): TOsoba; var tmp: TOsoba; begin tmp.imie := (imiona[random(losowosc) + 1]); tmp.nazwisko := nazwiska[random(losowosc) + 1]; tmp.pesel := pesele[random(losowosc) + 1]; CreateOsoba := tmp; end; function CzyPrawyStarszy(const prawy, lewy : PElem): Boolean; begin if (ZwrocDate(lewy) > ZwrocDate(prawy) )then CzyPrawyStarszy:=True else CzyPrawyStarszy:=False; end; procedure push(var glowa: Pelem); var nowy: PElem; begin new(nowy); nowy^.dane := CreateOsoba(); nowy^.Next := glowa; glowa := nowy; end; procedure push_bck(var glowa: Pelem); var tmp: Pelem; begin if (glowa = nil) then begin new(glowa); glowa^.dane := CreateOsoba(); glowa^.Next := nil; end else begin tmp := glowa; while (tmp^.Next <> nil) do tmp := tmp^.Next; new(tmp^.Next); tmp^.Next^.dane := CreateOsoba(); tmp^.Next^.Next := nil; end; end; procedure push_sort(var glowa: Pelem; const nowy:PElem); begin if (glowa = nil) then begin glowa:=nowy end else if ( CzyPrawyStarszy(glowa,nowy) ) then begin nowy^.Next:=glowa; glowa:=nowy; end else begin if ( ( glowa<>nil ) and (CzyPrawyStarszy(glowa,nowy)=False) ) then begin push_sort(glowa^.Next,nowy); end; end; end; procedure pop(var glowa: Pelem); var tmp: Pelem; begin if (glowa <> nil) then begin tmp := glowa; glowa := glowa^.Next; dispose(tmp); end else WriteLn('Lista jest pusta'); end; procedure pop_bck(var glowa: Pelem); var tmp: Pelem; begin if (glowa=nil) then WriteLn('Lista jest pusta') else if (glowa^.next=nil) then begin dispose(glowa); glowa:=nil; end else begin tmp:=glowa; while(tmp^.next^.next<>nil) do tmp:=tmp^.next; dispose(tmp^.next); tmp^.next:=nil; end; end; procedure usun(var glowa: PElem; const Pesel: TPesel); var tmp:PElem; begin if ( glowa = nil ) then begin WriteLn('Podany PESEL nie istnieje'); end else if ( glowa^.Dane.Pesel = Pesel ) then begin tmp:=glowa; glowa:=glowa^.Next; dispose(tmp); end else if ( glowa^.next = nil ) then begin WriteLn('Podany PESEL nie istnieje'); end else if ( glowa^.Next^.Dane.Pesel = Pesel ) then begin tmp:=glowa^.Next; glowa^.Next:=glowa^.Next^.Next; dispose(tmp); end else usun(glowa^.Next, Pesel); end; procedure print(const glowa: Pelem); var tmp: Pelem; rec_a: integer; begin tmp := glowa; rec_a := 1; while (tmp <> nil) do begin WriteLn(rec_a: 3, tmp^.dane.imie: 26, tmp^.dane.nazwisko: 26, tmp^.dane.pesel: 20); Inc(rec_a); tmp := tmp^.Next; end; end; end.
(* MIT License Copyright (c) 2018 Ondrej Kelle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) unit Test_ChakraCore; interface {$include ..\src\common.inc} uses Classes, SysUtils, {$ifdef FPC} {$ifndef WINDOWS} cwstring, {$endif} fpcunit, testutils, testregistry, {$else} TestFramework, {$endif} Compat, ChakraCoreVersion, ChakraCommon, ChakraCore, ChakraCoreUtils; type TChakraCoreTestCase = class(TTestCase) private FContext: JsContextRef; FRuntime: JsRuntimeHandle; protected procedure SetUp; override; procedure TearDown; override; public {$ifdef DELPHI} // work around Delphi 2007 and earlier compiler error "Ambiguous overloaded call to 'CheckEquals'" procedure CheckEquals(expected, actual: Integer; msg: string = ''); override; // DUnit needs a delta when comparing float values procedure CheckEquals(expected, actual: extended; msg: string = ''); reintroduce; overload; {$endif} procedure CheckEquals(expected, actual: JsValueType; const msg: string = ''); overload; procedure CheckEquals(expected, actual: JsTypedArrayType; const msg: string = ''); overload; procedure CheckValueType(expected: JsValueType; value: JsValueRef; const msg: string = ''); end; TChakraCoreUtilsScripting = class(TChakraCoreTestCase) published procedure TestVersion; procedure TestUndefined; procedure TestNull; procedure TestInt; procedure TestDouble; procedure TestInfinity; procedure TestNaN; procedure TestString; procedure TestStringUnicode; procedure TestBoolean; procedure TestObject; procedure TestFunction; procedure TestError; procedure TestArray; procedure TestSymbol; procedure TestArrayBuffer; procedure TestTypedArray; procedure TestDataView; procedure TestThrowBoolean; procedure TestThrowInt; procedure TestThrowString; procedure TestThrowObject; procedure TestThrowError; procedure TestThrowHostError; procedure TestCallFunction01; procedure TestCallFunction02; procedure TestCallFunctions; end; implementation uses Math; procedure TChakraCoreTestCase.SetUp; begin FRuntime := nil; FContext := nil; ChakraCoreCheck(JsCreateRuntime(JsRuntimeAttributeNone, nil, FRuntime)); ChakraCoreCheck(JsCreateContext(FRuntime, FContext)); ChakraCoreCheck(JsSetCurrentContext(FContext)); end; procedure TChakraCoreTestCase.TearDown; begin ChakraCoreCheck(JsSetCurrentContext(JS_INVALID_REFERENCE)); if Assigned(FRuntime) then ChakraCoreCheck(JsDisposeRuntime(FRuntime)); end; {$ifdef DELPHI} procedure TChakraCoreTestCase.CheckEquals(expected, actual: Integer; msg: string); begin inherited CheckEquals(expected, actual, msg); end; procedure TChakraCoreTestCase.CheckEquals(expected, actual: extended; msg: string); const DefaultDelta = 0.0000001; begin inherited CheckEquals(expected, actual, DefaultDelta, msg); end; {$endif} procedure TChakraCoreTestCase.CheckEquals(expected, actual: JsValueType; const msg: string); begin inherited CheckEquals(Ord(expected), Ord(actual), msg); end; procedure TChakraCoreTestCase.CheckEquals(expected, actual: JsTypedArrayType; const msg: string); begin inherited CheckEquals(Ord(expected), Ord(actual), msg); end; procedure TChakraCoreTestCase.CheckValueType(expected: JsValueType; value: JsValueRef; const msg: string); begin CheckEquals(expected, JsGetValueType(Value), msg); end; procedure TChakraCoreUtilsScripting.TestVersion; begin CheckEquals(Integer(1), CHAKRA_CORE_MAJOR_VERSION, 'major version number'); CheckEquals(Integer(7), CHAKRA_CORE_MINOR_VERSION, 'minor version number'); CheckEquals(Integer(6), CHAKRA_CORE_PATCH_VERSION, 'patch version number'); end; procedure TChakraCoreUtilsScripting.TestUndefined; const SScript = 'this.result = undefined'; SName = 'TestUndefined.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsUndefined, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestNull; const SScript = 'this.result = null'; SName = 'TestNull.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsNull, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestInt; const IntValue = 42; SScript = 'this.result = %d'; SName = 'TestInt.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(Format(SScript, [IntValue])), UnicodeString(SName)) else Result := JsRunScript(UTF8String(Format(SScript, [IntValue])), UTF8String(SName)); CheckValueType(JsNumber, Result, 'result type'); CheckEquals(IntValue, JsNumberToInt(Result), 'result value'); end; end; procedure TChakraCoreUtilsScripting.TestDouble; const DoubleValue: Double = 3.14; SScript = 'this.result = %f'; SName = 'TestDouble.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False To True do begin if Unicode then Result := JsRunScript(UnicodeString(Format(SScript, [DoubleValue], DefaultFormatSettings)), UnicodeString(SName)) else Result := JsRunScript(UTF8String(Format(SScript, [DoubleValue], DefaultFormatSettings)), UTF8String(SName)); CheckValueType(JsNumber, Result, 'result type'); CheckEquals(DoubleValue, JsNumberToDouble(Result), 'result value'); end; end; procedure TChakraCoreUtilsScripting.TestInfinity; const SScript = 'this.result = Infinity'; SName = 'TestInfinity.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsNumber, Result, 'result type'); Check(IsInfinite(JsNumberToDouble(Result)), 'INF'); end; end; procedure TChakraCoreUtilsScripting.TestNaN; const SScript = 'this.result = NaN'; SName = 'TestNaN.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsNumber, Result, 'result type'); Check(IsNan(JsNumberToDouble(Result)), 'NaN'); end; end; procedure TChakraCoreUtilsScripting.TestString; const StringValue: UnicodeString = 'Hello, world!'; SScript = 'this.result = "%s"'; SName = 'TestString.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(Format(SScript, [StringValue])), UnicodeString(SName)) else Result := JsRunScript(UTF8String(Format(SScript, [StringValue])), UTF8String(SName)); CheckValueType(JsString, Result, 'result type'); CheckEquals(StringValue, JsStringToUnicodeString(Result), 'result value'); end; end; procedure TChakraCoreUtilsScripting.TestStringUnicode; const StringValue: array [0..6] of AnsiChar = (#$E4, #$BD, #$A0, #$E5, #$A5, #$BD, #$00); SScript = 'this.result = "%s"'; SName = 'TestString.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(WideFormat(SScript, [UTF8ToString(StringValue)]), UnicodeString(SName)) else Result := JsRunScript(Format(SScript, [UTF8String(StringValue)]), UTF8String(SName)); CheckValueType(JsString, Result, 'result type'); {$ifdef SUPPORTS_UNICODE} CheckEquals(UTF8ToString(StringValue), JsStringToUnicodeString(Result), 'result value'); {$else} CheckEquals(UTF8String(StringValue), JsStringToUTF8String(Result), 'result value'); {$endif} end; end; procedure TChakraCoreUtilsScripting.TestBoolean; const SScripts: array[Boolean] of string = ( 'this.result = false', 'this.result = true' ); SName = 'TestBoolean.js'; var Unicode, BooleanValue: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin for BooleanValue := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScripts[BooleanValue]), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScripts[BooleanValue]), UTF8String(SName)); CheckValueType(JsBoolean, Result, 'result type'); CheckEquals(BooleanValue, JsBooleanToBoolean(Result), 'result value'); end; end; end; procedure TChakraCoreUtilsScripting.TestObject; const SScript = 'this.result = this'; SName = 'TestObject.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsObject, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestFunction; const SScript = 'this.result = function() { return 42; }'; SName = 'TestFunction.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsFunction, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestError; const SScript = 'this.result = new Error("Test Error")'; SName = 'TestError.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsError, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestArray; const IntElementValue = 42; DoubleElementValue = 3.14; StringElementValue: UnicodeString = 'Hello, world!'; SScript = 'this.result = [undefined, null, %d, %f, "%s", true, false, this, function() { return 42; }, new Error("Test Error")]'; SName = 'TestArray.js'; var Unicode: Boolean; Result, Element: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(Format(SScript, [IntElementValue, DoubleElementValue, StringElementValue], DefaultFormatSettings)), UnicodeString(SName)) else Result := JsRunScript(UTF8String(Format(SScript, [IntElementValue, DoubleElementValue, StringElementValue], DefaultFormatSettings)), UTF8String(SName)); CheckValueType(JsArray, Result, 'result type'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(0), Element)); CheckValueType(JsUndefined, Element, 'element 0 type'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(1), Element)); CheckValueType(JsNull, Element, 'element 1 type'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(2), Element)); CheckValueType(JsNumber, Element, 'element 2 type'); CheckEquals(IntElementValue, JsNumberToInt(Element), 'element 2 value'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(3), Element)); CheckValueType(JsNumber, Element, 'element 3 type'); CheckEquals(DoubleElementValue, JsNumberToDouble(Element), 'element 3 value'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(4), Element)); CheckValueType(JsString, Element, 'element 4 type'); CheckEquals(StringElementValue, JsStringToUnicodeString(Element), 'element 4 value'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(5), Element)); CheckValueType(JsBoolean, Element, 'element 5 type'); CheckEquals(True, JsBooleanToBoolean(Element), 'element 5 value'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(6), Element)); CheckValueType(JsBoolean, Element, 'element 6 type'); CheckEquals(False, JsBooleanToBoolean(Element), 'element 6 value'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(7), Element)); CheckValueType(JsObject, Element, 'element 7 type'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(8), Element)); CheckValueType(JsFunction, Element, 'element 8 type'); ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(9), Element)); CheckValueType(JsError, Element, 'element 9 type'); end; end; procedure TChakraCoreUtilsScripting.TestSymbol; const SScript = 'this.result = Symbol(''foo'')'; SName = 'TestSymbol.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsSymbol, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestArrayBuffer; const SScript = 'this.result = new ArrayBuffer(1024)'; SName = 'TestArrayBuffer.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsArrayBuffer, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestTypedArray; const SScripts: array[JsTypedArrayType] of string = ( 'this.result = new Int8Array(16)', 'this.result = new Uint8Array(16)', 'this.result = new Uint8ClampedArray(16)', 'this.result = new Int16Array(16)', 'this.result = new Uint16Array(16)', 'this.result = new Int32Array(16)', 'this.result = new Uint32Array(16)', 'this.result = new Float32Array(16)', 'this.result = new Float64Array(16)' ); SName = 'TesTypedtArray.js'; var Unicode: Boolean; I: JsTypedArrayType; Result: JsValueRef; begin for Unicode := False to True do begin for I := Low(JsTypedArraytype) to High(JsTypedArraytype) do begin if Unicode then Result := JsRunScript(UnicodeString(SScripts[I]), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScripts[I]), UTF8String(SName)); CheckValueType(JsTypedArray, Result, 'result type'); CheckEquals(I, JsGetTypedArrayType(Result), 'element type'); end; end; end; procedure TChakraCoreUtilsScripting.TestDataView; const SScript = 'this.result = new DataView(new ArrayBuffer(1024), 0, 1024)'; SName = 'TestArrayBuffer.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else Result := JsRunScript(UTF8String(SScript), UTF8String(SName)); CheckValueType(JsDataView, Result, 'result type'); end; end; procedure TChakraCoreUtilsScripting.TestThrowBoolean; const SScript = 'throw true;'; SName = 'TestThrowBoolean.js'; var Unicode: Boolean; begin for Unicode := False to True do begin try if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValueType(JsBoolean, E.Error, 'error type'); CheckEquals(True, JsBooleanToBoolean(E.Error), 'error value'); end; end; end; end; procedure TChakraCoreUtilsScripting.TestThrowInt; const IntValue = 42; SScript = 'throw %d;'; SName = 'TestThrowInt.js'; var Unicode: Boolean; begin for Unicode := False to True do begin try if Unicode then JsRunScript(UnicodeString(Format(SScript, [IntValue])), UnicodeString(SName)) else JsRunScript(UTF8String(Format(SScript, [IntValue])), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValuetype(JsNumber, E.Error, 'error type'); CheckEquals(IntValue, JsNumberToInt(E.Error), 'error value'); end; end; end; end; procedure TChakraCoreUtilsScripting.TestThrowString; const StringValue: UnicodeString = 'Error'; SScript = 'throw "%s";'; SName = 'TestThrowString.js'; var Unicode: Boolean; begin for Unicode := False to True do begin try if Unicode then JsRunScript(UnicodeString(Format(SScript, [StringValue])), UnicodeString(SName)) else JsRunScript(UTF8String(Format(SScript, [StringValue])), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValueType(JsString, E.Error, 'error type'); CheckEquals(StringValue, JsStringToUnicodeString(E.Error)); end; end; end; end; procedure TChakraCoreUtilsScripting.TestThrowObject; const SScript = 'throw this;'; SName = 'TestThrowObject.js'; var Unicode: Boolean; begin for Unicode := False to True do begin try if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValueType(JsObject, E.Error, 'error type'); end; end; end; end; procedure TChakraCoreUtilsScripting.TestThrowError; const SScript = 'syntax error?'; SName = 'TestThrowError.js'; var Unicode: Boolean; Name, Message: JsValueRef; begin for Unicode := False to True do begin try if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValueType(JsError, E.Error, 'error type'); Name := JsGetProperty(E.Error, 'name'); Message := JsGetProperty(E.Error, 'message'); CheckEquals('SyntaxError', JsStringToUnicodeString(Name)); CheckEquals('Expected '';''', JsStringToUnicodeString(Message)); end; end; end; end; const ErrorTypeNames: array[TErrorType] of string = ('Error', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'); type PErrorType = ^TErrorType; function TestErrorCallback(Callee: JsValueRef; IsConstructCall: bool; Arguments: PJsValueRef; ArgumentCount: Word; CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif} var ErrorType: PErrorType absolute CallbackState; begin ChakraCoreCheck(JsGetUndefinedValue(Result)); JsThrowError(Format('Test %s error', [ErrorTypeNames[ErrorType^]]), ErrorType^); end; procedure TChakraCoreUtilsScripting.TestThrowHostError; const SScript = 'this.testerror();'; SName = 'TestThrowHostError.js'; var Global: JsValueRef; Unicode: Boolean; EType: TErrorType; Name, Message: JsValueRef; begin ChakraCoreCheck(JsGetGlobalObject(Global)); JsSetCallback(Global, 'testerror', @TestErrorCallback, @EType); for Unicode := False to True do begin for EType := Low(TErrorType) to High(TErrorType) do begin try if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); Check(False, 'Expected error'); except on E: EChakraCore do begin CheckValueType(JsError, E.Error, 'error type'); Name := JsGetProperty(E.Error, 'name'); Message := JsGetProperty(E.Error, 'message'); CheckEquals(ErrorTypeNames[EType], JsStringToUnicodeString(Name)); CheckEquals(Format('Test %s error', [ErrorTypeNames[EType]]), JsStringToUnicodeString(Message)); end; end; end; end; end; procedure TChakraCoreUtilsScripting.TestCallFunction01; const SScript = 'function square(number) { return number * number; }'; SName = 'TestCallFunction01.js'; var Unicode: Boolean; Result: JsValueRef; Global, SquareFunc: JsValueRef; begin for Unicode := False to True do begin if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); ChakraCoreCheck(JsGetGlobalObject(Global)); SquareFunc := JsGetProperty(Global, 'square'); Result := JsCallFunction(SquareFunc, [Global, IntToJsNumber(3)]); CheckValueType(JsNumber, Result, 'result type'); CheckEquals(9, JsNumberToInt(Result), 'result value'); end; end; procedure TChakraCoreUtilsScripting.TestCallFunction02; const SScript = 'function square(number) { return number * number; }'; SName = 'TestCallFunction02.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then JsRunScript(UnicodeString(SScript), UnicodeString(SName)) else JsRunScript(UTF8String(SScript), UTF8String(SName)); Result := JsCallFunction('square', [IntToJsNumber(3)]); CheckValueType(JsNumber, Result, 'result type'); CheckEquals(9, JsNumberToInt(Result), 'result value'); end; end; procedure TChakraCoreUtilsScripting.TestCallFunctions; const SScript1 = 'function square(number) { return number * number; }'; SScript2 = 'function fact(number) { if (number == 0) { return 1; } else { return number * fact(number - 1); } }'; SName = 'TestCallFunctions.js'; var Unicode: Boolean; Result: JsValueRef; begin for Unicode := False to True do begin if Unicode then begin Result := JsRunScript(UnicodeString(SScript1), UnicodeString(SName)); CheckValueType(JsUndefined, Result, 'result type'); Result := JsRunScript(UnicodeString(SScript2), UnicodeString(SName)); CheckValueType(JsUndefined, Result, 'result type'); end else begin Result := JsRunScript(UTF8String(SScript1), UTF8String(SName)); CheckValueType(JsUndefined, Result, 'result type'); Result := JsRunScript(UTF8String(SScript2), UTF8String(SName)); CheckValueType(JsUndefined, Result, 'result type'); end; Result := JsCallFunction('square', [IntToJsNumber(3)]); CheckValuetype(JsNumber, Result, 'result type'); CheckEquals(9, JsNumberToInt(Result), 'result value'); Result := JsCallFunction('fact', [IntToJsNumber(5)]); CheckValueType(JsNumber, Result, 'result type'); CheckEquals(120, JsNumberToInt(Result), 'result value'); end; end; initialization {$ifdef FPC} RegisterTest(TChakraCoreUtilsScripting); {$else} RegisterTest(TChakraCoreUtilsScripting.Suite); {$endif} end.
unit fAppointmentList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Data.DB, Aurelius.Criteria.Base, Entities.Scheduling, Entidades.Cadastro, Aurelius.Bind.Dataset; type TfrmAppointmentList = class(TFrame) dsAppointments: TDataSource; adsAppointments: TAureliusDataset; adsAppointmentsSelf: TAureliusEntityField; adsAppointmentsId: TIntegerField; adsAppointmentsAppointmentDate: TDateTimeField; adsAppointmentsAnimal: TAureliusEntityField; adsAppointmentsService: TAureliusEntityField; adsAppointmentsListPrice: TCurrencyField; adsAppointmentsFinalPrice: TCurrencyField; adsAppointmentsDurationMinutes: TIntegerField; adsAppointmentsEmployee: TAureliusEntityField; adsAppointmentsStatus: TIntegerField; adsAppointmentsAnimalName: TStringField; adsAppointmentsServiceDescricao: TStringField; adsAppointmentsAnimalProprietarioNome: TStringField; adsAppointmentsStatusDesc: TStringField; DBGrid1: TDBGrid; adsAppointmentsAreaDesc: TStringField; procedure adsAppointmentsCalcFields(DataSet: TDataSet); private public procedure SetSourceCriteria(Criteria: TCriteria); end; implementation {$R *.dfm} { TfrmAppointmentList } procedure TfrmAppointmentList.adsAppointmentsCalcFields(DataSet: TDataSet); const StatusNames: array[TAppointmentStatus] of string = ('pendente', 'concuído', 'cancelado', 'pago'); AreaNames: array[TArea] of string = ('loja', 'banho/tosa', 'veterinária', 'creche/hotel'); begin adsAppointmentsStatusDesc.AsString := StatusNames[adsAppointments.Current<TAppointment>.Status]; adsAppointmentsAreaDesc.AsString := AreaNames[adsAppointments.Current<TAppointment>.Service.Area]; end; procedure TfrmAppointmentList.SetSourceCriteria(Criteria: TCriteria); begin adsAppointments.Close; adsAppointments.SetSourceCursor(Criteria.Open); adsAppointments.Open; end; end.
(* * Copyright (c) 2008-2010, Lucian Bentea * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$I ../DeHL.Defines.inc} unit DeHL.Collections.SortedList; interface uses SysUtils, DeHL.Base, DeHL.Types, DeHL.Exceptions, DeHL.Arrays, DeHL.StrConsts, DeHL.Serialization, DeHL.Collections.Base; type /// <summary>The generic <c>sorted list</c> collection.</summary> /// <remarks>This type uses an internal array to store its values.</remarks> TSortedList<T> = class(TEnexCollection<T>, IEnexIndexedCollection<T>, IList<T>, IOrderedList<T>, IDynamic) private type {$REGION 'Internal Types'} TEnumerator = class(TEnumerator<T>) private FVer: NativeUInt; FList: TSortedList<T>; FCurrentIndex: NativeUInt; public { Constructor } constructor Create(const AList: TSortedList<T>); { Destructor } destructor Destroy(); override; function GetCurrent(): T; override; function MoveNext(): Boolean; override; end; {$ENDREGION} private var FArray: TArray<T>; FLength: NativeUInt; FVer: NativeUInt; FAscending: Boolean; { Internal insertion } procedure Insert(const AIndex: NativeUInt; const AValue: T); protected /// <summary>Called when the serialization process is about to begin.</summary> /// <param name="AData">The serialization data exposing the context and other serialization options.</param> procedure StartSerializing(const AData: TSerializationData); override; /// <summary>Called when the deserialization process is about to begin.</summary> /// <param name="AData">The deserialization data exposing the context and other deserialization options.</param> /// <exception cref="DeHL.Exceptions|ESerializationException">Default implementation.</exception> procedure StartDeserializing(const AData: TDeserializationData); override; /// <summary>Called when an element has been deserialized and needs to be inserted into the list.</summary> /// <param name="AElement">The element that was deserialized.</param> /// <remarks>This method simply adds the element to the list.</remarks> procedure DeserializeElement(const AElement: T); override; /// <summary>Returns the item from a given index.</summary> /// <param name="AIndex">The index in the list.</param> /// <returns>The element at the specified position.</returns> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AIndex"/> is out of bounds.</exception> function GetItem(const AIndex: NativeUInt): T; /// <summary>Returns the number of elements in the list.</summary> /// <returns>A positive value specifying the number of elements in the list.</returns> function GetCount(): NativeUInt; override; /// <summary>Returns the current capacity.</summary> /// <returns>A positive number that specifies the number of elements that the list can hold before it /// needs to grow again.</returns> /// <remarks>The value of this method is greater or equal to the amount of elements in the list. If this value /// is greater then the number of elements, it means that the list has some extra capacity to operate upon.</remarks> function GetCapacity(): NativeUInt; public /// <summary>Creates a new instance of this class.</summary> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <remarks>The default type object is requested.</remarks> constructor Create(const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <param name="AInitialiCapacity">Specifies the initial capacity of the list.</param> /// <remarks>The default type object is requested.</remarks> constructor Create(const AInitialCapacity: NativeUInt; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="ACollection">A collection to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="ACollection"/> is <c>nil</c>.</exception> /// <remarks>The default type object is requested.</remarks> constructor Create(const ACollection: IEnumerable<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <remarks>The default type object is requested.</remarks> constructor Create(const AArray: array of T; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <remarks>The default type object is requested.</remarks> constructor Create(const AArray: TDynamicArray<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <remarks>The default type object is requested.</remarks> constructor Create(const AArray: TFixedArray<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <param name="AInitialiCapacity">Specifies the initial capacity of the list.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const AInitialCapacity: NativeUInt; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="ACollection">A collection to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="ACollection"/> is <c>nil</c>.</exception> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const ACollection: IEnumerable<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const AArray: array of T; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const AArray: TDynamicArray<T>; const AAscending: Boolean = true); overload; /// <summary>Creates a new instance of this class.</summary> /// <param name="AType">A type object decribing the elements in the list.</param> /// <param name="AArray">An array to copy elements from.</param> /// <param name="AAscending">Specifies whether the elements are kept sorted in ascending order. Default is <c>True</c>.</param> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> constructor Create(const AType: IType<T>; const AArray: TFixedArray<T>; const AAscending: Boolean = true); overload; /// <summary>Destroys this instance.</summary> /// <remarks>Do not call this method directly, call <c>Free</c> instead.</remarks> destructor Destroy(); override; /// <summary>Clears the contents of the list.</summary> /// <remarks>This method clears the list and invokes type object's cleaning routines for each element.</remarks> procedure Clear(); /// <summary>Adds an element to the list.</summary> /// <param name="AValue">The value to add.</param> /// <remarks>The added value is not appended. The list tries to figure out whre to insert it to keep its elements /// ordered at all times.</remarks> procedure Add(const AValue: T); overload; /// <summary>Add the elements from a collection to the list.</summary> /// <param name="ACollection">The values to add.</param> /// <remarks>The added values are not appended. The list tries to figure out where to insert the new values /// to keep its elements ordered at all times.</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="ACollection"/> is <c>nil</c>.</exception> procedure Add(const ACollection: IEnumerable<T>); overload; /// <summary>Removes a given value from the list.</summary> /// <param name="AValue">The value to remove.</param> /// <remarks>If the list does not contain the given value, nothing happens.</remarks> procedure Remove(const AValue: T); /// <summary>Removes an element from the list at a given index.</summary> /// <param name="AIndex">The index from which to remove the element.</param> /// <remarks>This method removes the specified element and moves all following elements to the left by one.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AIndex"/> is out of bounds.</exception> procedure RemoveAt(const AIndex: NativeUInt); /// <summary>Checks whether the list contains a given value.</summary> /// <param name="AValue">The value to check.</param> /// <returns><c>True</c> if the value was found in the list; <c>False</c> otherwise.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> function Contains(const AValue: T): Boolean; /// <summary>Searches for the first appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <param name="AStartIndex">The index to from which the search starts.</param> /// <param name="ACount">The number of elements after the starting one to check against.</param> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException">Parameter combination is incorrect.</exception> function IndexOf(const AValue: T; const AStartIndex, ACount: NativeUInt): NativeInt; overload; /// <summary>Searches for the first appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <param name="AStartIndex">The index to from which the search starts.</param> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception> function IndexOf(const AValue: T; const AStartIndex: NativeUInt): NativeInt; overload; /// <summary>Searches for the first appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> function IndexOf(const AValue: T): NativeInt; overload; /// <summary>Searches for the last appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <param name="AStartIndex">The index to from which the search starts.</param> /// <param name="ACount">The number of elements after the starting one to check against.</param> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException">Parameter combination is incorrect.</exception> function LastIndexOf(const AValue: T; const AStartIndex, ACount: NativeUInt): NativeInt; overload; /// <summary>Searches for the last appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <param name="AStartIndex">The index to from which the search starts.</param> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception> function LastIndexOf(const AValue: T; const AStartIndex: NativeUInt): NativeInt; overload; /// <summary>Searches for the last appearance of a given element in this list.</summary> /// <param name="AValue">The value to search for.</param> /// <returns><c>-1</c> if the value was not found; otherwise a positive value indicating the index of the value.</returns> /// <remarks>This method uses binary search beacause the list is always sorted.</remarks> function LastIndexOf(const AValue: T): NativeInt; overload; /// <summary>Specifies the number of elements in the list.</summary> /// <returns>A positive value specifying the number of elements in the list.</returns> property Count: NativeUInt read FLength; /// <summary>Specifies the current capacity.</summary> /// <returns>A positive number that specifies the number of elements that the list can hold before it /// needs to grow again.</returns> /// <remarks>The value of this property is greater or equal to the amount of elements in the list. If this value /// if greater then the number of elements, it means that the list has some extra capacity to operate upon.</remarks> property Capacity: NativeUInt read GetCapacity; /// <summary>Returns the item from a given index.</summary> /// <param name="AIndex">The index in the collection.</param> /// <returns>The element at the specified position.</returns> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AIndex"/> is out of bounds.</exception> property Items[const AIndex: NativeUInt]: T read GetItem; default; /// <summary>Returns a new enumerator object used to enumerate this list.</summary> /// <remarks>This method is usually called by compiler generated code. Its purpose is to create an enumerator /// object that is used to actually traverse the list.</remarks> /// <returns>An enumerator object.</returns> function GetEnumerator(): IEnumerator<T>; override; /// <summary>Removes the excess capacity from the list.</summary> /// <remarks>This method can be called manually to force the list to drop the extra capacity it might hold. For example, /// after performing some massive operations of a big list, call this method to ensure that all extra memory held by the /// list is released.</remarks> procedure Shrink(); /// <summary>Forces the list to increase its capacity.</summary> /// <remarks>Call this method to force the list to increase its capacity ahead of time. Manually adjusting the capacity /// can be useful in certain situations.</remarks> procedure Grow(); /// <summary>Copies the specified elements into a new list.</summary> /// <param name="AStartIndex">The index to from which the copy starts.</param> /// <param name="ACount">The number of elements to copy.</param> /// <returns>A new list containing the copied elements.</returns> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException">Parameter combination is invalid.</exception> function Copy(const AStartIndex: NativeUInt; const ACount: NativeUInt): TSortedList<T>; overload; /// <summary>Copies the specified elements into a new list.</summary> /// <param name="AStartIndex">The index to from which the copy starts.</param> /// <returns>A new list containing the copied elements.</returns> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception> function Copy(const AStartIndex: NativeUInt): TSortedList<T>; overload; /// <summary>Creates a copy of this list.</summary> /// <returns>A new list containing the copied elements.</returns> function Copy(): TSortedList<T>; overload; /// <summary>Copies the values stored in the list to a given array.</summary> /// <param name="AArray">An array where to copy the contents of the list.</param> /// <param name="AStartIndex">The index into the array at which the copying begins.</param> /// <remarks>This method assumes that <paramref name="AArray"/> has enough space to hold the contents of the list.</remarks> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception> /// <exception cref="DeHL.Exceptions|EArgumentOutOfSpaceException">There array is not long enough.</exception> procedure CopyTo(var AArray: array of T; const AStartIndex: NativeUInt); overload; override; /// <summary>Checks whether the list is empty.</summary> /// <returns><c>True</c> if the list is empty; <c>False</c> otherwise.</returns> /// <remarks>This method is the recommended way of detecting if the list is empty.</remarks> function Empty(): Boolean; override; /// <summary>Returns the biggest element.</summary> /// <returns>An element from the list considered to have the biggest value.</returns> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> function Max(): T; override; /// <summary>Returns the smallest element.</summary> /// <returns>An element from the list considered to have the smallest value.</returns> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> function Min(): T; override; /// <summary>Returns the first element.</summary> /// <returns>The first element in the list.</returns> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> function First(): T; override; /// <summary>Returns the first element or a default if the list is empty.</summary> /// <param name="ADefault">The default value returned if the list is empty.</param> /// <returns>The first element in list if the list is not empty; otherwise <paramref name="ADefault"/> is returned.</returns> function FirstOrDefault(const ADefault: T): T; override; /// <summary>Returns the last element.</summary> /// <returns>The last element in the list.</returns> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> function Last(): T; override; /// <summary>Returns the last element or a default if the list is empty.</summary> /// <param name="ADefault">The default value returned if the list is empty.</param> /// <returns>The last element in list if the list is not empty; otherwise <paramref name="ADefault"/> is returned.</returns> function LastOrDefault(const ADefault: T): T; override; /// <summary>Returns the single element stored in the list.</summary> /// <returns>The element in list.</returns> /// <remarks>This method checks if the list contains just one element, in which case it is returned.</remarks> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> /// <exception cref="DeHL.Exceptions|ECollectionNotOneException">There is more than one element in the list.</exception> function Single(): T; override; /// <summary>Returns the single element stored in the list, or a default value.</summary> /// <param name="ADefault">The default value returned if there is less or more elements in the list.</param> /// <returns>The element in the list if the condition is satisfied; <paramref name="ADefault"/> is returned otherwise.</returns> /// <remarks>This method checks if the list contains just one element, in which case it is returned. Otherwise /// the value in <paramref name="ADefault"/> is returned.</remarks> function SingleOrDefault(const ADefault: T): T; override; /// <summary>Aggregates a value based on the list's elements.</summary> /// <param name="AAggregator">The aggregator method.</param> /// <returns>A value that contains the list's aggregated value.</returns> /// <remarks>This method returns the first element if the list only has one element. Otherwise, /// <paramref name="AAggregator"/> is invoked for each two elements (first and second; then the result of the first two /// and the third, and so on). The simples example of aggregation is the "sum" operation where you can obtain the sum of all /// elements in the value.</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AAggregator"/> is <c>nil</c>.</exception> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> function Aggregate(const AAggregator: TFunc<T, T, T>): T; override; /// <summary>Aggregates a value based on the list's elements.</summary> /// <param name="AAggregator">The aggregator method.</param> /// <param name="ADefault">The default value returned if the list is empty.</param> /// <returns>A value that contains the list's aggregated value. If the list is empty, <paramref name="ADefault"/> is returned.</returns> /// <remarks>This method returns the first element if the list only has one element. Otherwise, /// <paramref name="AAggregator"/> is invoked for each two elements (first and second; then the result of the first two /// and the third, and so on). The simples example of aggregation is the "sum" operation where you can obtain the sum of all /// elements in the value.</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AAggregator"/> is <c>nil</c>.</exception> function AggregateOrDefault(const AAggregator: TFunc<T, T, T>; const ADefault: T): T; override; /// <summary>Returns the element at a given position.</summary> /// <param name="AIndex">The index from which to return the element.</param> /// <returns>The element from the specified position.</returns> /// <exception cref="DeHL.Exceptions|ECollectionEmptyException">The list is empty.</exception> /// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AIndex"/> is out of bounds.</exception> function ElementAt(const AIndex: NativeUInt): T; override; /// <summary>Returns the element at a given position.</summary> /// <param name="AIndex">The index from which to return the element.</param> /// <param name="ADefault">The default value returned if the list is empty.</param> /// <returns>The element from the specified position if the list is not empty and the position is not out of bounds; otherwise /// the value of <paramref name="ADefault"/> is returned.</returns> function ElementAtOrDefault(const AIndex: NativeUInt; const ADefault: T): T; override; /// <summary>Check whether at least one element in the list satisfies a given predicate.</summary> /// <param name="APredicate">The predicate to check for each element.</param> /// <returns><c>True</c> if the at least one element satisfies a given predicate; <c>False</c> otherwise.</returns> /// <remarks>This method traverses the whole list and checks the value of the predicate for each element. This method /// stops on the first element for which the predicate returns <c>True</c>. The logical equivalent of this operation is "OR".</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="APredicate"/> is <c>nil</c>.</exception> function Any(const APredicate: TFunc<T, Boolean>): Boolean; override; /// <summary>Checks that all elements in the list satisfy a given predicate.</summary> /// <param name="APredicate">The predicate to check for each element.</param> /// <returns><c>True</c> if all elements satisfy a given predicate; <c>False</c> otherwise.</returns> /// <remarks>This method traverses the whole list and checks the value of the predicate for each element. This method /// stops on the first element for which the predicate returns <c>False</c>. The logical equivalent of this operation is "AND".</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="APredicate"/> is <c>nil</c>.</exception> function All(const APredicate: TFunc<T, Boolean>): Boolean; override; /// <summary>Checks whether the elements in this list are equal to the elements in another collection.</summary> /// <param name="ACollection">The collection to compare to.</param> /// <returns><c>True</c> if the collections are equal; <c>False</c> if the collections are different.</returns> /// <remarks>This methods checks that each element at position X in this list is equal to an element at position X in /// the provided collection. If the number of elements in both collections are different, then the collections are considered different. /// Note that comparison of element is done using the type object used by this list. This means that comparing this collection /// to another one might yeild a different result than comparing the other collection to this one.</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="ACollection"/> is <c>nil</c>.</exception> function EqualsTo(const ACollection: IEnumerable<T>): Boolean; override; end; /// <summary>The generic <c>sorted list</c> collection designed to store objects.</summary> /// <remarks>This type uses an internal array to store its objects.</remarks> TObjectSortedList<T: class> = class(TSortedList<T>) private FWrapperType: TObjectWrapperType<T>; { Getters/Setters for OwnsObjects } function GetOwnsObjects: Boolean; procedure SetOwnsObjects(const Value: Boolean); protected /// <summary>Installs the type object.</summary> /// <param name="AType">The type object to install.</param> /// <remarks>This method installs a custom wrapper designed to suppress the cleanup of objects on request. /// Make sure to call this method in descendant classes.</remarks> /// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception> procedure InstallType(const AType: IType<T>); override; public /// <summary>Specifies whether this list owns the objects stored in it.</summary> /// <returns><c>True</c> if the list owns its objects; <c>False</c> otherwise.</returns> /// <remarks>This property controls the way the list controls the life-time of the stored objects.</remarks> property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects; end; implementation const DefaultArrayLength = 32; { TSortedList<T> } procedure TSortedList<T>.Insert(const AIndex: NativeUInt; const AValue: T); var I : NativeInt; Cap: NativeUInt; begin if AIndex > FLength then ExceptionHelper.Throw_ArgumentOutOfRangeError('AIndex'); if FLength = NativeUInt(Length(FArray)) then Grow(); { Move the array to the right } if AIndex < FLength then for I := FLength downto (AIndex + 1) do FArray[I] := FArray[I - 1]; Inc(FLength); { Put the element into the new position } FArray[AIndex] := AValue; Inc(FVer); end; procedure TSortedList<T>.Add(const ACollection: IEnumerable<T>); var V: T; begin if (ACollection = nil) then ExceptionHelper.Throw_ArgumentNilError('ACollection'); { Enumerate and add, preserving order} for V in ACollection do Add(V); end; function TSortedList<T>.Aggregate(const AAggregator: TFunc<T, T, T>): T; var I: NativeUInt; begin { Check arguments } if not Assigned(AAggregator) then ExceptionHelper.Throw_ArgumentNilError('AAggregator'); if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError(); { Select the first element as comparison base } Result := FArray[0]; { Iterate over the last N - 1 elements } for I := 1 to FLength - 1 do begin { Aggregate a value } Result := AAggregator(Result, FArray[I]); end; end; function TSortedList<T>.AggregateOrDefault(const AAggregator: TFunc<T, T, T>; const ADefault: T): T; var I: NativeUInt; begin { Check arguments } if not Assigned(AAggregator) then ExceptionHelper.Throw_ArgumentNilError('AAggregator'); if FLength = 0 then Exit(ADefault); { Select the first element as comparison base } Result := FArray[0]; { Iterate over the last N - 1 elements } for I := 1 to FLength - 1 do begin { Aggregate a value } Result := AAggregator(Result, FArray[I]); end; end; function TSortedList<T>.All(const APredicate: TFunc<T, Boolean>): Boolean; var I: NativeUInt; begin if not Assigned(APredicate) then ExceptionHelper.Throw_ArgumentNilError('APredicate'); if FLength > 0 then for I := 0 to FLength - 1 do if not APredicate(FArray[I]) then Exit(false); Result := true; end; function TSortedList<T>.Any(const APredicate: TFunc<T, Boolean>): Boolean; var I: NativeUInt; begin if not Assigned(APredicate) then ExceptionHelper.Throw_ArgumentNilError('APredicate'); if FLength > 0 then for I := 0 to FLength - 1 do if APredicate(FArray[I]) then Exit(true); Result := false; end; procedure TSortedList<T>.Add(const AValue: T); var I: NativeUInt; Sign: NativeInt; begin if FAscending then Sign := 1 else Sign := -1; I := 0; while I < FLength do begin if ((ElementType.Compare(AValue, FArray[I]) * Sign) < 0) then Break; Inc(I); end; Insert(I, AValue); end; procedure TSortedList<T>.Clear; var I: NativeInt; begin if (ElementType <> nil) and (ElementType.Management() = tmManual) and (FLength > 0) then begin { Should cleanup each element individually } for I := 0 to FLength - 1 do ElementType.Cleanup(FArray[I]); end; { Reset the length } FLength := 0; end; function TSortedList<T>.Contains(const AValue: T): Boolean; begin { Pass the call to AIndex of } Result := (IndexOf(AValue) > -1); end; function TSortedList<T>.Copy(const AStartIndex: NativeUInt): TSortedList<T>; begin { Pass the call down to the more generic function } Copy(AStartIndex, (FLength - AStartIndex)); end; function TSortedList<T>.Copy(const AStartIndex, ACount: NativeUInt): TSortedList<T>; var NewList: TSortedList<T>; begin { Check for zero elements } if (FLength = 0) then begin Result := TSortedList<T>.Create(ElementType); Exit; end; { Check for indexes } if (AStartIndex >= FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('AStartIndex'); { Check for indexes } if ((AStartIndex + ACount) > FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('ACount'); { Create a new list } NewList := TSortedList<T>.Create(ElementType, ACount); { Copy all elements safely } &Array<T>.SafeMove(FArray, NewList.FArray, AStartIndex, 0, ACount, ElementType); { Set new count } NewList.FLength := ACount; Result := NewList; end; procedure TSortedList<T>.CopyTo(var AArray: array of T; const AStartIndex: NativeUInt); begin { Check for indexes } if AStartIndex >= NativeUInt(Length(AArray)) then ExceptionHelper.Throw_ArgumentOutOfRangeError('AStartIndex'); if (NativeUInt(Length(AArray)) - AStartIndex) < FLength then ExceptionHelper.Throw_ArgumentOutOfSpaceError('AArray'); { Copy all elements safely } &Array<T>.SafeMove(FArray, AArray, 0, AStartIndex, FLength, ElementType); end; constructor TSortedList<T>.Create(const AType: IType<T>; const AAscending: Boolean); begin { Call upper constructor } Create(AType, DefaultArrayLength, AAscending); end; constructor TSortedList<T>.Create(const AType: IType<T>; const ACollection: IEnumerable<T>; const AAscending: Boolean); var V: T; begin { Call upper constructor } Create(AType, DefaultArrayLength, AAscending); { Initialize instance } if (ACollection = nil) then ExceptionHelper.Throw_ArgumentNilError('ACollection'); { Try to copy the given Enumerable } for V in ACollection do begin { Perform a simple push } Add(V); end; end; constructor TSortedList<T>.Create(const AAscending: Boolean); begin Create(TType<T>.Default, AAscending); end; constructor TSortedList<T>.Create(const AInitialCapacity: NativeUInt; const AAscending: Boolean); begin Create(TType<T>.Default, AInitialCapacity, AAscending); end; constructor TSortedList<T>.Create(const ACollection: IEnumerable<T>; const AAscending: Boolean); begin Create(TType<T>.Default, ACollection, AAscending); end; constructor TSortedList<T>.Create(const AType: IType<T>; const AInitialCapacity: NativeUInt; const AAscending: Boolean); begin { Initialize instance } if (AType = nil) then ExceptionHelper.Throw_ArgumentNilError('AType'); InstallType(AType); FLength := 0; FVer := 0; FAscending := AAscending; SetLength(FArray, AInitialCapacity); end; procedure TSortedList<T>.DeserializeElement(const AElement: T); begin { Simple as hell ... } Add(AElement); end; destructor TSortedList<T>.Destroy; begin { Clear list first } Clear(); inherited; end; function TSortedList<T>.ElementAt(const AIndex: NativeUInt): T; begin { Simply use the getter } Result := GetItem(AIndex); end; function TSortedList<T>.ElementAtOrDefault(const AIndex: NativeUInt; const ADefault: T): T; begin { Check range } if (AIndex >= FLength) then Result := ADefault else Result := FArray[AIndex]; end; function TSortedList<T>.Empty: Boolean; begin Result := (FLength = 0); end; function TSortedList<T>.EqualsTo(const ACollection: IEnumerable<T>): Boolean; var V: T; I: NativeUInt; begin I := 0; for V in ACollection do begin if I >= FLength then Exit(false); if not ElementType.AreEqual(FArray[I], V) then Exit(false); Inc(I); end; if I < FLength then Exit(false); Result := true; end; function TSortedList<T>.First: T; begin { Check length } if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError(); Result := FArray[0]; end; function TSortedList<T>.FirstOrDefault(const ADefault: T): T; begin { Check length } if FLength = 0 then Result := ADefault else Result := FArray[0]; end; function TSortedList<T>.GetCapacity: NativeUInt; begin Result := Length(FArray); end; function TSortedList<T>.GetCount: NativeUInt; begin Result := FLength; end; function TSortedList<T>.GetEnumerator: IEnumerator<T>; begin { Create an enumerator } Result := TEnumerator.Create(Self); end; function TSortedList<T>.GetItem(const AIndex: NativeUInt): T; begin { Check range } if (AIndex >= FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('AIndex'); { Get value } Result := FArray[AIndex]; end; procedure TSortedList<T>.Grow; begin { Grow the array } if FLength < DefaultArrayLength then SetLength(FArray, FLength + DefaultArrayLength) else SetLength(FArray, FLength * 2); end; function TSortedList<T>.IndexOf(const AValue: T): NativeInt; begin { Call more generic function } Result := IndexOf(AValue, 0, FLength); end; function TSortedList<T>.IndexOf(const AValue: T; const AStartIndex: NativeUInt): NativeInt; begin { Call more generic function } Result := IndexOf(AValue, AStartIndex, (FLength - AStartIndex)); end; function TSortedList<T>.IndexOf(const AValue: T; const AStartIndex, ACount: NativeUInt): NativeInt; var I, J: NativeInt; begin Result := -1; if FLength = 0 then Exit; { Check for indexes } if (AStartIndex >= FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('AStartIndex'); { Check for indexes } if ((AStartIndex + ACount) > FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('ACount'); { Search for the value } J := &Array<T>.BinarySearch(FArray, AValue, AStartIndex, ACount, ElementType, FAscending); if J = -1 then Exit(-1) else Inc(J, AStartIndex); for I := J - 1 downto AStartIndex do if not ElementType.AreEqual(AValue, FArray[I]) then begin Result := I + 1; Exit; end; Result := J; end; function TSortedList<T>.LastIndexOf(const AValue: T; const AStartIndex: NativeUInt): NativeInt; begin { Call more generic function } Result := LastIndexOf(AValue, AStartIndex, (FLength - AStartIndex)); end; function TSortedList<T>.Last: T; begin { Check length } if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError(); Result := FArray[FLength - 1]; end; function TSortedList<T>.LastIndexOf(const AValue: T): NativeInt; begin { Call more generic function } Result := LastIndexOf(AValue, 0, FLength); end; function TSortedList<T>.LastOrDefault(const ADefault: T): T; begin { Check length } if FLength = 0 then Result := ADefault else Result := FArray[FLength - 1]; end; function TSortedList<T>.Max: T; var I: NativeUInt; begin { Check length } if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError(); { Default one } Result := FArray[0]; for I := 1 to FLength - 1 do if ElementType.Compare(FArray[I], Result) > 0 then Result := FArray[I]; end; function TSortedList<T>.Min: T; var I: NativeUInt; begin { Check length } if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError(); { Default one } Result := FArray[0]; for I := 1 to FLength - 1 do if ElementType.Compare(FArray[I], Result) < 0 then Result := FArray[I]; end; function TSortedList<T>.LastIndexOf(const AValue: T; const AStartIndex, ACount: NativeUInt): NativeInt; var I, J: NativeInt; begin Result := -1; if FLength = 0 then Exit; { Check for indexes } if (AStartIndex >= FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('AStartIndex'); { Check for indexes } if ((AStartIndex + ACount) > FLength) then ExceptionHelper.Throw_ArgumentOutOfRangeError('ACount'); { Search for the value } J := &Array<T>.BinarySearch(FArray, AValue, AStartIndex, ACount, ElementType, FAscending); if J = -1 then Exit(-1) else Inc(J, AStartIndex); for I := J + 1 to AStartIndex + ACount - 1 do if not ElementType.AreEqual(AValue, FArray[I]) then begin Result := I - 1; Exit; end; Result := J; end; procedure TSortedList<T>.Remove(const AValue: T); var I, FoundIndex: NativeInt; begin { Defaults } if (FLength = 0) then Exit; FoundIndex := -1; for I := 0 to FLength - 1 do begin if ElementType.AreEqual(FArray[I], AValue) then begin FoundIndex := I; Break; end; end; if FoundIndex > -1 then begin { Move the list } if FLength > 1 then for I := FoundIndex to FLength - 2 do FArray[I] := FArray[I + 1]; Dec(FLength); Inc(FVer); end; end; procedure TSortedList<T>.RemoveAt(const AIndex: NativeUInt); var I: NativeInt; begin if AIndex >= FLength then ExceptionHelper.Throw_ArgumentOutOfRangeError('AIndex'); if (FLength = 0) then Exit; { Clanup the element at the specified AIndex if required } if ElementType.Management() = tmManual then ElementType.Cleanup(FArray[AIndex]); { Move the list } if FLength > 1 then for I := AIndex to FLength - 2 do FArray[I] := FArray[I + 1]; Dec(FLength); Inc(FVer); end; procedure TSortedList<T>.Shrink; begin { Cut the capacity if required } if FLength < Capacity then begin SetLength(FArray, FLength); end; end; function TSortedList<T>.Single: T; begin { Check length } if FLength = 0 then ExceptionHelper.Throw_CollectionEmptyError() else if FLength > 1 then ExceptionHelper.Throw_CollectionHasMoreThanOneElement() else Result := FArray[0]; end; function TSortedList<T>.SingleOrDefault(const ADefault: T): T; begin { Check length } if FLength = 0 then Result := ADefault else if FLength > 1 then ExceptionHelper.Throw_CollectionHasMoreThanOneElement() else Result := FArray[0]; end; procedure TSortedList<T>.StartDeserializing(const AData: TDeserializationData); var LAsc: Boolean; begin AData.GetValue(SSerAscendingKeys, LAsc); { Call the constructor in this instance to initialize myself first } Create(LAsc); end; procedure TSortedList<T>.StartSerializing(const AData: TSerializationData); begin { Write the AAscending sign } AData.AddValue(SSerAscendingKeys, FAscending); end; function TSortedList<T>.Copy: TSortedList<T>; begin { Call a more generic function } Result := Copy(0, FLength); end; constructor TSortedList<T>.Create(const AArray: array of T; const AAscending: Boolean); begin Create(TType<T>.Default, AArray, AAscending); end; constructor TSortedList<T>.Create(const AType: IType<T>; const AArray: array of T; const AAscending: Boolean); var I: NativeInt; begin { Call upper constructor } Create(AType, DefaultArrayLength, AAscending); { Copy from array } for I := 0 to Length(AArray) - 1 do begin Add(AArray[I]); end; end; constructor TSortedList<T>.Create(const AArray: TFixedArray<T>; const AAscending: Boolean); begin Create(TType<T>.Default, AArray, AAscending); end; constructor TSortedList<T>.Create(const AArray: TDynamicArray<T>; const AAscending: Boolean); begin Create(TType<T>.Default, AArray, AAscending); end; constructor TSortedList<T>.Create(const AType: IType<T>; const AArray: TFixedArray<T>; const AAscending: Boolean); var I: NativeUInt; begin { Call upper constructor } Create(AType, DefaultArrayLength, AAscending); { Copy from array } if AArray.Length > 0 then for I := 0 to AArray.Length - 1 do begin Add(AArray[I]); end; end; constructor TSortedList<T>.Create(const AType: IType<T>; const AArray: TDynamicArray<T>; const AAscending: Boolean); var I: NativeUInt; begin { Call upper constructor } Create(AType, DefaultArrayLength, AAscending); { Copy from array } if AArray.Length > 0 then for I := 0 to AArray.Length - 1 do begin Add(AArray[I]); end; end; { TSortedList<T>.TEnumerator } constructor TSortedList<T>.TEnumerator.Create(const AList: TSortedList<T>); begin { Initialize } FList := AList; KeepObjectAlive(FList); FCurrentIndex := 0; FVer := FList.FVer; end; destructor TSortedList<T>.TEnumerator.Destroy; begin ReleaseObject(FList); inherited; end; function TSortedList<T>.TEnumerator.GetCurrent: T; begin if FVer <> FList.FVer then ExceptionHelper.Throw_CollectionChangedError(); if FCurrentIndex > 0 then Result := FList.FArray[FCurrentIndex - 1] else Result := default(T); end; function TSortedList<T>.TEnumerator.MoveNext: Boolean; begin if FVer <> FList.FVer then ExceptionHelper.Throw_CollectionChangedError(); Result := FCurrentIndex < FList.FLength; Inc(FCurrentIndex); end; { TObjectSortedList<T> } procedure TObjectSortedList<T>.InstallType(const AType: IType<T>); begin { Create a wrapper over the real type class and switch it } FWrapperType := TObjectWrapperType<T>.Create(AType); { Install overridden type } inherited InstallType(FWrapperType); end; function TObjectSortedList<T>.GetOwnsObjects: Boolean; begin Result := FWrapperType.AllowCleanup; end; procedure TObjectSortedList<T>.SetOwnsObjects(const Value: Boolean); begin FWrapperType.AllowCleanup := Value; end; end.
object SetVarFrm: TSetVarFrm Left = 448 Top = 288 BorderStyle = bsDialog Caption = 'Set Variable' ClientHeight = 68 ClientWidth = 151 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'System' Font.Style = [] OldCreateOrder = True PixelsPerInch = 96 TextHeight = 16 object cbVariable: TComboBox Left = 8 Top = 8 Width = 137 Height = 23 Style = csDropDownList Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 0 end object cbChannel: TComboBox Left = 8 Top = 40 Width = 81 Height = 23 Style = csDropDownList Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 1 end object bOK: TButton Left = 96 Top = 40 Width = 41 Height = 17 Caption = 'OK' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'Arial' Font.Style = [fsBold] ModalResult = 1 ParentFont = False TabOrder = 2 OnClick = bOKClick end end
unit UnitSoko; interface uses WinTypes, Classes, Dialogs, Grids, Graphics, Forms; type TMap = array of string; TDxMove = (dxLeft = -1, dxRigth = 1, dxNone = 0); TDyMove = (dyDown = 1, dyUp = -1, dyNone = 0); TMove = packed record PlayerDX: TDxMove; PlayerDY: TDyMove; Char1, Char2, Char3: Char; PoolChange: Integer; IsPushedBox: Boolean; end; PMoveStack = ^TMoveStack; TMoveStack = record Move: TMove; pNext: PMoveStack; pPrev: PMoveStack; end; TMoveStackClass = class pHead: PMoveStack; pTop: PMoveStack; Count: Integer; MaxCount: Integer; constructor Create(const aMaxCount: Integer); function Pop: TMove; procedure Push(const aMove: TMove); end; TRecord = record Moves: Integer; Pushes: Integer; Time: string[8]; end; const CWallChar = '#'; CWallPath = 'wall.bmp'; CPlayerChar = '!'; CPlayerPath = 'player.bmp'; CPoolChar = '+'; CPoolPath = 'pool.bmp'; CBoxChar = '%'; CBoxPath = 'box.bmp'; CDrawChar = '.'; CDrawPath = 'draw.bmp'; CNullChar = '/'; CPlayerInPoolChar = '?'; CBoxInPoolChar = '@'; CBoxInPoolPath = 'boxinpool.bmp'; // animation player CPlayerDownPath = 'playerdown.bmp'; CPlayerUpPath = 'playerup.bmp'; CPlayerLeftPath = 'playerleft.bmp'; CPlayerRightPath = 'playerright.bmp'; CDefTexturesPath = 'Textures/'; var PropSize: Integer = 64; StackSize: Integer = 70; function GetMapInFile(aPath: string; var aMap: TMap): Boolean; function GetInPath(var aPath: string; aParrent: TComponent): Boolean; procedure MakeBorder(aMap: TMap; aGrid: TDrawGrid; aForm: TForm); procedure DrawGrid(aGrid: TDrawGrid; aMap: TMap); function InitilizeInput(Key: Word; var dx: TDxMove; var dy: TDyMove): Boolean; procedure GetVariables(Map: TMap; var x,y: Integer; var PoolCount: Integer); procedure DrawCell(aGrid: TDrawGrid; aXCoord, aYCoord: Integer; aChar: char); procedure DrawPlayer(aGrid: TDrawGrid; aXCoord, aYCoord: Integer; aDx: TDxMove; aDy: TDyMove); function GetPathFromChar(const aChar: Char): string; function GetRecord(aPath: string; var aRec: TRecord): Boolean; function SaveRecord(aPath: string; const aRec: TRecord): Boolean; function GetPropSize(aXProp, aYProp: Integer): Boolean; implementation uses SysUtils; const CAllowArr: array[0..7] of Char = (CWallChar, CPlayerChar, CPoolChar, CBoxChar, CDrawChar, CNullChar, CPlayerInPoolChar, CBoxInPoolChar); constructor TMoveStackClass.Create(const aMaxCount: Integer); begin MaxCount := aMaxCount; end; function TMoveStackClass.Pop: TMove; var Temp: PMoveStack; begin Temp := pHead; Result := pHead^.Move; pHead := pHead^.pNext; Dispose(Temp); Dec(Count); end; procedure TMoveStackClass.Push(const aMove: TMove); var Temp: PMoveStack; Temp2: PMoveStack; begin New(Temp); Temp^.Move := aMove; Temp^.pNext := pHead; Temp^.pPrev := nil; if Count > 0 then pHead^.pPrev := Temp; pHead := Temp; if Count = MaxCount then begin Temp2 := pTop; pTop := pTop^.pPrev; pTop^.pNext := nil; Dispose(Temp2) end else begin Inc(Count); if Count = 1 then pTop := pHead else if Count = 2 then pTop^.pPrev := pHead; end; end; function IsCorrectField(aMap: TMap): Boolean; var IsCorrect: Boolean; const CVisited = 'v'; procedure TryMove(aX, aY: Integer); begin if not (IsCorrect) or (aMap[aY, aX] = CVisited) then Exit; if not (aMap[aY, aX] = CWallChar) then begin if (aX = 1) or (aY = 0) or (aX = Length(aMap[aY])) or (aY = High(aMap)) then IsCorrect := False; aMap[aY, aX] := CVisited; TryMove(aX + 1, aY); TryMove(aX, aY - 1); TryMove(aX - 1, aY); TryMove(aX, aY + 1); end; end; label ExitLoop; var PlayerX, PlayerY: Integer; i,j: Integer; begin IsCorrect := True; for i := 0 to High(aMap) do for j := 0 to Length(aMap[i]) do if (aMap[i][j] = CPlayerChar) or (aMap[i][j] = CplayerInPoolChar) then begin TryMove(j, i); goto ExitLoop; end; ExitLoop: Result := IsCorrect; end; function GetMapInFile(aPath: string; var aMap: TMap) : Boolean; var InFile: TextFile; i,j,k: Integer; IsCorrect: Boolean; Temp: string; PlayerPosCount: Integer; begin AssignFile(InFile, aPath); Reset(InFile); i := 0; IsCorrect := True; PlayerPosCount := 0; while (not EOF(InFile)) and (IsCorrect) do begin try Readln(InFile, Temp); for j := 1 to Length(Temp) do begin if (Temp[j] = CPlayerChar) or (Temp[j] = CPlayerInPoolChar) then Inc(PlayerPosCount); IsCorrect := False; for k := 0 to High(CAllowArr) do begin if Temp[j] = CAllowArr[k] then begin IsCorrect := True; break; end; end; if not IsCorrect then break; end; Inc(i); except IsCorrect := False; end; end; Close(InFile); if (i = 0) or (PlayerPosCount <> 1) then IsCorrect := False; if IsCorrect then begin SetLength(aMap, i); Reset(InFile); i := 0; while not EOF(InFile) do begin Readln(InFile, aMap[i]); Inc(i); end; Close(InFile); end; if not IsCorrectField(Copy(aMap)) then IsCorrect := False; GeTMapInFile := IsCorrect; end; function GetInPath(var aPath: string; aParrent: TComponent): Boolean; var openFile: TOpenDialog; begin openFile := TOpenDialog.Create(aParrent); openFile.Filter := 'Уровни sokoban (*.skb)|*.skb'; if openFile.Execute then begin aPath := openFile.FileName; Result := True; end else Result := False; openFile.Destroy; end; procedure MakeBorder(aMap: TMap; aGrid: TDrawGrid; aForm: TForm); var MaxColCount: Integer; i: Integer; begin MaxColCount := 0; for i := 0 to High(aMap) do begin if Length(aMap[i]) > MaxColCount then MaxColCount := Length(aMap[i]); end; if GetPropSize(Screen.WorkAreaWidth div MaxColCount, Screen.WorkAreaHeight div Length(aMap)) then begin aGrid.DefaultColWidth := PropSize; aGrid.DefaultRowHeight := PropSize; aGrid.RowCount := Length(aMap); aGrid.Height := Trunc((aGrid.RowCount) * (2 + PropSize)); aForm.Height := aGrid.Height + 50; aGrid.ColCount := MaxColCount; aGrid.Width := Trunc((aGrid.ColCount) * (2 + PropSize)); aForm.Width := aGrid.Width; aForm.Left := (Screen.WorkAreaWidth - aForm.Width) div 2; aForm.Top := (Screen.WorkAreaHeight - aForm.Height) div 2; end else begin // TODO: To function end; end; procedure DrawGrid(aGrid: TDrawGrid; aMap: TMap); var i,j: Integer; Img: TBitmap; begin SetCurrentDir(ExtractFilePath(Application.ExeName)); Img := TBitmap.Create; for i := 0 to High(aMap) do begin for j := 1 to Length(aMap[i]) do begin if aMap[i,j] = CNullChar then begin aGrid.Canvas.Brush.Color := aGrid.Color; aGrid.Canvas.FillRect(aGrid.CellRect(j-1, i)); end else begin Img.LoadFromFile(GetPathFromChar(aMap[i,j])); aGrid.Canvas.CopyRect(aGrid.CellRect(j-1,i), Img.Canvas, Rect(0,0,Img.Height,Img.Width)) end; end; end; Img.Free; end; function InitilizeInput(Key: Word; var dx: TDxMove; var dy: TDyMove): Boolean; begin Result := True; case Key of VK_UP, Ord('K'): begin dx := dxNone; dy := dyUp; end; VK_DOWN, Ord('J'): begin dx := dxNone; dy := dyDown; end; VK_LEFT, Ord('H'): begin dx := dxLeft; dy := dyNone; end; VK_RIGHT, Ord('L'): begin dx := dxRigth; dy := dyNone; end; else Result := False; end; end; procedure GetVariables(Map: TMap; var x,y: Integer; var PoolCount: Integer); var i,j: Integer; begin x := 0; y := 0; PoolCount := 0; for i := 0 to High(Map) do for j := 1 to Length(Map[i]) do begin if (Map[i,j] = CPlayerChar) or (Map[i,j] = CPlayerInPoolChar) then begin y := i; x := j; end; if Map[i,j] = CPoolChar then Inc(PoolCount); end; end; procedure DrawCell(aGrid: TDrawGrid; aXCoord, aYCoord: Integer; aChar: char); var Img: TBitmap; begin SetCurrentDir(ExtractFilePath(Application.ExeName)); if aChar = CNullChar then begin aGrid.Canvas.Brush.Color := aGrid.Color; aGrid.Canvas.FillRect(aGrid.CellRect(aXCoord-1, aYCoord)); end else begin Img := TBitmap.Create; Img.LoadFromFile(GetPathFromChar(aChar)); aGrid.Canvas.CopyRect(aGrid.CellRect(aXCoord - 1, aYCoord), Img.Canvas, Rect(0,0,Img.Height,Img.Width)); Img.Free; end; end; procedure DrawPlayer(aGrid: TDrawGrid; aXCoord, aYCoord: Integer; aDx: TDxMove; aDy: TDyMove); var Img: TBitmap; Path: string; begin Img := TBitmap.Create; Path := CDefTexturesPath + IntToStr(PropSize) + '/'; case aDx of dxLeft: Path := Path + CPlayerLeftPath; dxRigth: Path := Path + CPlayerRightPath; dxNone: case aDy of dyDown: Path := Path + CPlayerDownPath; dyUp: Path := Path + CPlayerUpPath; end; end; Img.LoadFromFile(Path); aGrid.Canvas.CopyRect(aGrid.CellRect(aXCoord - 1, aYCoord), Img.Canvas, Rect(0,0,Img.Height,Img.Width)); Img.Free; end; function GetPathFromChar(const aChar: Char): string; //TODO: to UnitSoko and review code begin Result := CDefTexturesPath + IntToStr(PropSize) + '/'; case aChar of CWallChar: Result := Result + CWallPath; CPlayerChar: Result := Result + CPlayerPath; CPlayerInPoolChar: Result := Result + CPlayerPath; CPoolChar: Result := Result + CPoolPath; CBoxChar: Result := Result + CBoxPath; CDrawChar: Result := Result + CDrawPath; CBoxInPoolChar: Result := Result + CBoxInPoolPath; end; end; function GetRecord(aPath: string; var aRec: TRecord): Boolean; var InFile: file of TRecord; begin AssignFile(InFile, aPath); try Reset(InFile); Read(InFile, aRec); Result := True; except Result := False; end; Close(InFile); end; function SaveRecord(aPath: string; const aRec: TRecord): Boolean; var OutFile: file of TRecord; begin AssignFile(OutFile, aPath); try Rewrite(OutFile); Write(OutFile, aRec); Close(OutFile); Result := True; except Result := False; end; end; function GetPropSize(aXProp, aYProp: Integer): Boolean; const CMaxSize = 64; CMinSize = 16; var i: Integer; Min: Integer; begin if aXProp < aYProp then Min := aXProp else Min := aYProp; i := CMaxSize; while (i >= CMinSize) and (Min div i = 0) do Dec(i, 16); if i > 0 then PropSize := i; if Min < CMinSize then GetPropSize := False else GetPropSize := True; end; end.
unit Aurelius.Drivers.mORMot; {$I Aurelius.inc} interface uses Classes, DB, Variants, Generics.Collections, gmORMot, mORMotInterface, gSynCommons, Aurelius.Drivers.Base, Aurelius.Drivers.Interfaces; type { TProjectSettings = class(TPersistent) private fHOST: RawUTF8; fPORT: RawUTF8; fDatabaseName: RawUTF8; fPassword: RawUTF8; fUserID: RawUTF8; fServerName: RawUTF8; fEngine: TRemoteSQLEngine; function GetPort: RawUTF8; published property HOST: RawUTF8 read fHOST write fHOST; property PORT: RawUTF8 read GetPort write fPORT; property Engine: TRemoteSQLEngine read fEngine write fEngine; property ServerName: RawUTF8 read fServerName write fServerName; property DatabaseName: RawUTF8 read fDatabaseName write fDatabaseName; property UserID: RawUTF8 read fUserID write fUserID; property PassWord: RawUTF8 read fPassword write fPassword; end; } TProjectSettings = class(TPersistent) private fHOST: String; fPORT: String; fDatabaseName: String; fPassword: String; fUserID: String; fServerName: String; fEngine: TRemoteSQLEngine; function GetPort: String; published property HOST: String read fHOST write fHOST; property PORT: String read GetPort write fPORT; property Engine: TRemoteSQLEngine read fEngine write fEngine; property ServerName: String read fServerName write fServerName; property DatabaseName: String read fDatabaseName write fDatabaseName; property UserID: String read fUserID write fUserID; property PassWord: String read fPassword write fPassword; end; TmORMotStatement = RawUTF8; TmORMotResultSetAdapter = class(TInterfacedObject, IDBResultSet) private FRow: integer; FStatement: TSQLTableJSON; public // constructor Create(AStatement: RawUTF8); constructor Create(AStatement: TSQLTableJSON); destructor Destroy; override; function Next: boolean; function GetFieldValue(FieldIndex: Integer): Variant; overload; function GetFieldValue(FieldName: string): Variant; overload; function GetFieldValue(FieldIndex: Integer; ClassFieldType: TFieldType): Variant; overload; function GetFieldValue(FieldName: string; ClassFieldType: TFieldType): Variant; overload; end; TmORMotConnectionAdapter = class(TInterfacedObject, IDBConnection) strict private fSettings: TProjectSettings; // fSettingsFileName: TFileName; fModel: TSQLModel; fClient: TSQLRestClientURI; // fTableJSON: RawUTF8; fService: IRemoteSQL; FConnected: boolean; // procedure Execute(const SQL: string); public constructor Create( pSettings: TProjectSettings ); destructor Destroy; override; // procedure EnableForeignKeys; // procedure DisableForeignKeys; procedure Connect; procedure Disconnect; function IsConnected: Boolean; function CreateStatement: IDBStatement; function BeginTransaction: IDBTransaction; function SqlDialect: string; property Service: IRemoteSQL read fService; end; TmORMotStatementAdapter = class(TInterfacedObject, IDBStatement) private FConnAdapter: TmORMotConnectionAdapter; // FSQL: RawUTF8; FSQL: string; FParams: TObjectList<TDBParam>; function PrepareStatement: TmORMotStatement; function FormatSQL(Format: PUTF8Char; const Args, Params: array of const): RawUTF8; function FindVariables(const SQL: string; IncludeDuplicates: Boolean): TStringList; function FindVariable(var AName: string): Integer; // function GetVariable(AName: string): Variant; procedure ReplaceSubstVariables(var s: string); public constructor Create(ConnAdapter: TmORMotConnectionAdapter); destructor Destroy; override; procedure SetSQLCommand(SQLCommand: string); procedure SetParams(Params: TEnumerable<TDBParam>); procedure Execute; function ExecuteQuery: IDBResultSet; end; TmORMotTransactionAdapter = class(TInterfacedObject, IDBTransaction) private // FDatabase: TSQLiteDatabase; public constructor Create; //(ADatabase: TSQLiteDatabase); procedure Commit; procedure Rollback; end; implementation uses SysUtils, gmORMotHttpClient, // JsonToDataSetConverter, Aurelius.Drivers.Exceptions, Aurelius.Global.Utils; type TConstArray = array of TVarRec; { function TProjectSettings.GetPort: RawUTF8; begin if fPORT='' then result := StringToUTF8('888') else result := fPORT; end; } function TProjectSettings.GetPort: String; begin if fPORT='' then result := '888' else result := fPORT; end; { TmORMotConnectionAdapter } constructor TmORMotConnectionAdapter.Create( pSettings: TProjectSettings ); begin fSettings := TProjectSettings.Create; fSettings.fHOST := pSettings.fHOST; fSettings.fPORT := pSettings.fPORT; fSettings.fDatabaseName := pSettings.fDatabaseName; fSettings.fPassword := pSettings.fPassword; fSettings.fUserID := pSettings.fUserID; fSettings.fServerName := pSettings.fServerName; fSettings.fEngine := pSettings.fEngine; // riattivare !!! fModel := TSQLModel.Create([],ROOT_NAME); fClient := TSQLHttpClient.Create(fSettings.HOST,fSettings.PORT,fModel); FConnected := false; end; destructor TmORMotConnectionAdapter.Destroy; begin fSettings.Free; inherited; end; procedure TmORMotConnectionAdapter.Disconnect; begin if FConnected then begin FConnected := False; end; end; function TmORMotConnectionAdapter.SqlDialect: string; begin case fSettings.fEngine of rseOleDB, rseODBC: Result := 'MSSQL'; rseOracle: Result := 'Oracle'; rseSQlite3: Result := 'SQlite'; rseJet, rseMSSQL: Result := 'MSSQL'; else Result := 'MSSQL'; end; end; function TmORMotConnectionAdapter.IsConnected: Boolean; begin Result := FConnected; end; function TmORMotConnectionAdapter.CreateStatement: IDBStatement; begin if not IsConnected then Connect; Result := TmORMotStatementAdapter.Create(self); end; procedure TmORMotConnectionAdapter.Connect; begin if not fClient.ServerTimeStampSynchronize then begin // ShowLastClientError(fClient,'Please run Project16ServerHttp.exe'); Exception.Create('Server non attivo'); // Close; exit; end; if (not fClient.SetUser('User','synopse')) or (not fClient.ServiceRegisterClientDriven(TypeInfo(IRemoteSQL),fService)) then begin // ShowLastClientError(fClient,'Remote service not available on server'); Exception.Create('Servizio remoto non disponibile sul server'); // Close; // exit; end; with fSettings do fService.Connect(Engine,ServerName,DatabaseName,UserID,PassWord); FConnected := true; end; function TmORMotConnectionAdapter.BeginTransaction: IDBTransaction; begin { if Connection = nil then Exit(nil); } if not IsConnected then Connect; { if not FDatabase.InTransaction then begin FDatabase.BeginTransaction; Result := TSQLiteNativeTransactionAdapter.Create(FDatabase); end else Result := TmORMotTransactionAdapter.Create(nil); } Result := TmORMotTransactionAdapter.Create; end; { TmORMotStatementAdapter } constructor TmORMotStatementAdapter.Create(ConnAdapter: TmORMotConnectionAdapter); begin FConnAdapter := ConnAdapter; FParams := TObjectList<TDBParam>.Create(true); // FLobs := TObjectList<TLobLocator>.Create(true); end; destructor TmORMotStatementAdapter.Destroy; begin FParams.Free; // FLobs.Free; inherited; end; function TmORMotStatementAdapter.FormatSQL(Format: PUTF8Char; const Args, Params: array of const): RawUTF8; // support both : and ? tokens var i, tmpN, L, A, P, len: PtrInt; isParam: AnsiChar; tmp: TRawUTF8DynArray; inlin: set of 0..255; PDeb: PUTF8Char; label Txt; begin if (Format='') or ((high(Args)<0)and(high(Params)<0)) then begin result := Format; // no formatting to process exit; end; result := ''; tmpN := 0; FillChar(inlin,SizeOf(inlin),0); L := 0; A := 0; P := 0; while Format^<>#0 do begin if Format^<>':' then begin PDeb := Format; while not (Format^ in [#0,':','?']) do inc(Format); Txt: len := Format-PDeb; if len>0 then begin inc(L,len); if tmpN=length(tmp) then SetLength(tmp,tmpN+8); SetString(tmp[tmpN],PDeb,len); // add inbetween text inc(tmpN); end; end; if Format^=#0 then break; isParam := Format^; inc(Format); // jump '%' or '?' if (isParam=':') and (A<=high(Args)) then begin if tmpN=length(tmp) then SetLength(tmp,tmpN+8); VarRecToUTF8(Args[A],tmp[tmpN]); inc(A); if tmp[tmpN]<>'' then begin inc(L,length(tmp[tmpN])); inc(tmpN); end; end else if (isParam='?') and (P<=high(Params)) then begin // add inlined :(...): if tmpN=length(tmp) then SetLength(tmp,tmpN+8); VarRecToUTF8(Params[P],tmp[tmpN]); if not (Params[P].VType in [vtBoolean,vtInteger,vtInt64,vtCurrency,vtExtended]) then tmp[tmpN] := QuotedStr(pointer(tmp[tmpN]),''''); inc(L,4); // space for :(): include(inlin,tmpN); inc(P); inc(L,length(tmp[tmpN])); inc(tmpN); end else if Format^<>#0 then begin // no more available Args -> add all remaining text PDeb := Format; repeat inc(Format) until (Format^=#0); goto Txt; end; end; if L=0 then exit; if tmpN>SizeOf(inlin)shl 3 then raise ESynException.Create('Too many parameters for FormatUTF8'); SetLength(result,L); Format := pointer(result); for i := 0 to tmpN-1 do if tmp[i]<>'' then if i in inlin then begin PWord(Format)^ := ord(':')+ord('(')shl 8; inc(Format,2); L := PInteger(PtrInt(tmp[i])-sizeof(integer))^; move(pointer(tmp[i])^,Format^,L); inc(Format,L); PWord(Format)^ := ord(')')+ord(':')shl 8; inc(Format,2); end else begin L := PInteger(PtrInt(tmp[i])-sizeof(integer))^; move(pointer(tmp[i])^,Format^,L); inc(Format,L); end; end; function TmORMotStatementAdapter.FindVariables(const SQL: string; IncludeDuplicates: Boolean): TStringList; var s: widestring; i: Integer; Mode: char; VarName, EndC, x: widestring; VarPos: Integer; begin Result := TStringList.Create; s := SQL + #13#10; Mode := 'S'; EndC := ''; VarPos := 0; for i := 1 to Length(s) do begin case Mode of 'S' : begin if s[i] = ':' then begin Mode := 'V'; VarName := ''; VarPos := i; end; if (S[i] = '''') then begin Mode := 'Q'; EndC := ''''; end; if (S[i] = '/') and (S[i + 1] = '*') then begin Mode := 'C'; EndC := '*/'; end; if (S[i] = '-') and (S[i + 1] ='-') then begin Mode := 'C'; EndC := #13#10; end; end; 'V' : begin if (s[i] <= #255) and not (AnsiChar(s[i]) in ['a'..'z', 'A'..'Z', '0'..'9', '_', '#', '$', #128..#255]) then begin // VarName := AnsiUpperCase(VarName); pily: perchè ??? if (VarName <> '') and (IncludeDuplicates or (Result.IndexOf(VarName) < 0)) then Result.AddObject(VarName, TObject(VarPos)); Mode := 'S'; end else begin x := s[i]; VarName := VarName + x; end; end; 'C' : if (S[i] = EndC[1]) and (S[i + 1] = EndC[2]) then mode := 'S'; 'Q' : if (S[i] = EndC[1]) then mode := 'S'; end; end; end; // Find the index of a variable by name function TmORMotStatementAdapter.FindVariable(var AName: string): Integer; var i: Integer; Param: TDBParam; begin { if (AName <> '') and (Copy(AName,1,1) <> ':') then AName := ':' + AnsiUpperCase(AName) else AName := AnsiUpperCase(AName); } i := -1; for Param in FParams do begin inc(i); if Param.ParamName = AName then begin Result := i; Exit; end; end; Result := -1; end; (* function TmORMotStatementAdapter.GetVariable(AName: string): Variant; var VariableIndex: Integer; begin VariableIndex := FindVariable(AName); if VariableIndex < 0 then raise Exception.Create('Unknown variable: ' + AName); // Result := GetVariableByIndex(VariableIndex); Result := FParams.Items[VariableIndex].ParamValue; end; *) procedure TmORMotStatementAdapter.ReplaceSubstVariables(var s: string); var vi, sv, vp, dp: Integer; vv: Variant; ws, ss: string; Ready: Boolean; VarList: TStringList; VarName: string; begin ws := s; VarList := FindVariables(s, True); for sv := VarList.Count - 1 downto 0 do begin VarName := VarList[sv]; vi := FindVariable(VarName); if (vi >= 0) then begin vv := FParams.Items[vi].ParamValue; if VarIsNull(vv) or VarIsEmpty(vv) then ss := '' else begin (* {$IFNDEF CompilerVersion2009} if VarIsWideString(vv) then ss := UTF8Encode(vv) else {$ENDIF} *) ss := vv; end; if ss = '' then ss := 'null' else begin { TFieldType = (ftUnknown, ftString, ftSmallint, ftInteger, ftWord, // 0..4 ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, // 5..11 ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo, // 12..18 ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, ftWideString, // 19..24 ftLargeint, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, // 25..31 ftVariant, ftInterface, ftIDispatch, ftGuid, ftTimeStamp, ftFMTBcd, // 32..37 ftFixedWideChar, ftWideMemo, ftOraTimeStamp, ftOraInterval, // 38..41 ftLongWord, ftShortint, ftByte, ftExtended, ftConnection, ftParams, ftStream, //42..48 ftTimeStampOffset, ftObject, ftSingle); //49..51 } case FParams.Items[vi].ParamType of ftInteger: ; ftFloat: begin ss := FloatToStr(vv); dp := Pos(',', ss); if dp > 0 then ss[dp] := '.'; end; ftDate: ; //ss := 'to_date(''' + FormatDateTime('dd-mm-yyyy hh:mm:ss', vv) + ''', ''DD-MM-YYYY HH24:MI:SS'')'; else ss := QuotedStr(ss); end; end; vp := Integer(VarList.Objects[sv]); Delete(ws, vp, Length(VarName) + 1); Insert(ss, ws, vp); end; end; VarList.Free; s := ws; end; procedure TmORMotStatementAdapter.Execute; var xSQL: RawUTF8; begin xSQL := trim(StringToUTF8(FSQL)); FConnAdapter.Service.Execute(xSQL,False,False); end; function TmORMotStatementAdapter.ExecuteQuery: IDBResultSet; var xSQL: RawUTF8; fTableJSON: RawUTF8; begin xSQL := trim(StringToUTF8(FSQL)); fTableJSON := FConnAdapter.Service.Execute(xSQL,True,False); // fTableJSON := FConnAdapter.Service.Execute(xSQL,True,True); // Result := TmORMotResultSetAdapter.Create(fTableJSON); result := TmORMotResultSetAdapter.Create(TSQLTableJSON.Create(xSQL,fTableJSON)); end; function TmORMotStatementAdapter.PrepareStatement: TmORMotStatement; var Statement: TmORMotStatement; Param: TDBParam; ParamIdx: integer; begin { // Statement := FDB.Prepare(FSQL); Statement := FSQL; try for Param in FParams do begin if VarIsNull(Param.ParamValue) then Continue; ParamIdx := Statement.BindParameterIndex(':' + Param.ParamName); case Param.ParamType of ftInteger, ftShortint, ftSmallint, ftLargeint: Statement.BindInt64(ParamIdx, Param.ParamValue); ftFloat, ftCurrency, ftExtended: Statement.BindDouble(ParamIdx, Param.ParamValue); ftString, ftWideString, ftFixedChar, ftMemo, ftWideMemo: Statement.BindText(ParamIdx, Param.ParamValue); ftBlob: Statement.BindBlob(ParamIdx, TUtils.VariantToBytes(Param.ParamValue)); else Statement.BindText(ParamIdx, Param.ParamValue); end; end; Result := Statement; except Statement.Free; raise; end; } end; procedure TmORMotStatementAdapter.SetParams(Params: TEnumerable<TDBParam>); var P: TDBParam; begin FParams.Clear; for P in Params do FParams.Add(TDBParam.Create(P.ParamName, P.ParamType, P.ParamValue)); ReplaceSubstVariables(FSQL); end; procedure TmORMotStatementAdapter.SetSQLCommand(SQLCommand: string); begin FSQL := SQLCommand; end; { TmORMotResultSetAdapter } constructor TmORMotResultSetAdapter.Create(AStatement: TSQLTableJSON); begin FStatement := AStatement; FRow := 0; end; destructor TmORMotResultSetAdapter.Destroy; begin // FStatement.Free; inherited; end; function TmORMotResultSetAdapter.GetFieldValue(FieldIndex: Integer): Variant; begin Result := GetFieldValue(FieldIndex,ftString); end; function TmORMotResultSetAdapter.GetFieldValue(FieldName: string): Variant; begin Result := GetFieldValue(FieldName,ftString); end; function TmORMotResultSetAdapter.GetFieldValue(FieldIndex: Integer; ClassFieldType: TFieldType): Variant; var temp: string; begin temp := FStatement.FieldValue(FieldIndex,FStatement.StepRow); case ClassFieldType of ftInteger: Result := StrToInt(temp); else result := temp; end; end; function TmORMotResultSetAdapter.GetFieldValue(FieldName: string; ClassFieldType: TFieldType): Variant; var temp: string; begin (* TFieldType = (ftUnknown, ftString, ftSmallint, ftInteger, ftWord, // 0..4 ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, // 5..11 ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo, // 12..18 ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, ftWideString, // 19..24 ftLargeint, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, // 25..31 ftVariant, ftInterface, ftIDispatch, ftGuid, ftTimeStamp, ftFMTBcd, // 32..37 ftFixedWideChar, ftWideMemo, ftOraTimeStamp, ftOraInterval, // 38..41 ftLongWord, ftShortint, ftByte, ftExtended, ftConnection, ftParams, ftStream, //42..48 ftTimeStampOffset, ftObject, ftSingle); //49..51 *) temp := FStatement.FieldValue(FieldName,FStatement.StepRow); case ClassFieldType of ftInteger: Result := StrToInt(temp); else result := temp; end; end; function TmORMotResultSetAdapter.Next: boolean; begin { if FStatement.Eof then Result := false else begin FStatement.Next; Result := true; end; } Result := FStatement.Step; // FRow := FRow + 1; end; { TSQLiteNativeTransactionAdapter } procedure TmORMotTransactionAdapter.Commit; begin { if (FDatabase = nil) then Exit; FDatabase.Commit; } end; constructor TmORMotTransactionAdapter.Create; //(ADatabase: TSQLiteDatabase); begin // FDatabase := ADatabase; end; procedure TmORMotTransactionAdapter.Rollback; begin { if (FDatabase = nil) then Exit; FDatabase.Rollback; } end; end.
unit SettingsUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts, FMX.ImgList, Forms, FMX.ScrollBox, FMX.Memo; type TSettingsForm = class(TBarForm) Volume: TText; Brithnes: TText; DecVol: TButton; VLev: TLabel; IncVol: TButton; DecBr: TButton; IncBr: TButton; BLev: TLabel; DecCtr: TButton; IncCtr: TButton; CLev: TLabel; Contrast: TText; BG: TGlyph; logoLayout: TLayout; Logo: TGlyph; SPanel: TPanel; nextLayout: TLayout; NextBtn: TSpeedButton; SubName: TText; SubText: TMemo; SubLogo: TGlyph; backLayout: TLayout; BackBtn: TSpeedButton; Main: TLayout; Vol: TLayout; Brith: TLayout; Contr: TLayout; Grid: TLayout; top: TLayout; down: TLayout; mid: TLayout; procedure IncVolClick(Sender: TObject); procedure DecBrClick(Sender: TObject); procedure DecCtrClick(Sender: TObject); procedure BackBtnClick(Sender: TObject); protected procedure onCreate; override; public { Public declarations } end; var SettingsForm: TSettingsForm; implementation {$R *.fmx} uses GameData, SoundManager; procedure TSettingsForm.BackBtnClick(Sender: TObject); begin SM.play(sClick); Close; end; procedure TSettingsForm.DecBrClick(Sender: TObject); begin if ((sender as Tbutton).Tag=1)and(Blev.Tag<10) then Blev.Tag:=Blev.Tag+1 else if ((sender as Tbutton).Tag=0)and(Blev.Tag>0) then Blev.Tag:=Blev.Tag-1; Blev.Text:=Blev.Tag.ToString; GD.brightnes:=Blev.Tag; SM.play(sClick); end; procedure TSettingsForm.DecCtrClick(Sender: TObject); begin if ((sender as Tbutton).Tag=1)and(Clev.Tag<10) then Clev.Tag:=Clev.Tag+1 else if ((sender as Tbutton).Tag=0)and(Clev.Tag>0) then Clev.Tag:=Clev.Tag-1; Clev.Text:=Clev.Tag.ToString; GD.contrast:=Clev.Tag; SM.play(sClick); end; procedure TSettingsForm.IncVolClick(Sender: TObject); begin if ((sender as Tbutton).Tag=1)and(Vlev.Tag<10) then Vlev.Tag:=Vlev.Tag+1 else if ((sender as Tbutton).Tag=0)and(Vlev.Tag>0) then Vlev.Tag:=Vlev.Tag-1; Vlev.Text:=Vlev.Tag.ToString; SM.volume:=Vlev.Tag; SM.play(eSound(2+random(2))); end; procedure TSettingsForm.onCreate; begin backgrounds:=[BG]; layouts:=[main]; Vlev.Tag:=SM.volume; Vlev.Text:=Vlev.Tag.ToString; Blev.Tag:=GD.brightnes; Blev.Text:=Blev.Tag.ToString; Clev.Tag:=GD.contrast; Clev.Text:=Clev.Tag.ToString; setItem(0, Volume); setItem(1, Brithnes); setItem(2, Contrast); end; end.