text
stringlengths
14
6.51M
UNIT WordWorking; INTERFACE CONST Letters: SET OF CHAR = ['A'..'Z', 'a'..'z', 'А'..'Я', 'Ё', 'ё', 'а'..'я']; UpperRusLetters: SET OF CHAR = ['А'..'Я', 'A'..'Z']; WordLength = 60; LetterDist = 32; PROCEDURE GetWord(VAR FIn: TEXT; VAR Wd: STRING); //Получение одного слова из входного файла IMPLEMENTATION PROCEDURE ToLowerCase(VAR Symbol: CHAR); BEGIN {ToLowerCase} IF Symbol IN UpperRusLetters THEN Symbol := CHR(ORD(Symbol) + LetterDist); IF Symbol IN ['Ё', 'ё'] THEN Symbol := 'е'; END; {ToLowerCase} PROCEDURE GetWord(VAR FIn: TEXT; VAR Wd: STRING); VAR Ch: CHAR; BEGIN {GetWord} Wd := ''; READ(FIn, Ch); IF Ch IN Letters THEN BEGIN WHILE (Ch IN Letters) AND (NOT EOF(FIn)) DO BEGIN ToLowerCase(Ch); Wd := Wd + Ch; READ(FIn, Ch); END; IF (EOF(FIn)) AND (Ch IN Letters) THEN BEGIN ToLowerCase(Ch); Wd := Wd + Ch; END; END; END; {GetWord} BEGIN END.
unit VSERender2D; interface uses Windows, AvL, avlUtils, avlMath, OpenGL, oglExtensions, VSEOpenGLExt, VSECore {$IFDEF VSE_LOG}, VSELog{$ENDIF}; type PFont = ^TFont; //internally used TFont = record //internally used Tex, List: Cardinal; Width: array [0..255] of Single; Height: Integer; Size: Integer; Bold: Boolean; Name: string; end; PFloatRect = ^TFloatRect; TFloatRect = packed record Left, Top, Right, Bottom: Single; end; TRender2D = class(TModule) private FVSWidth: Integer; FVSHeight: Integer; FVSScale, FVSPadding: Single; FVSPaddingVertical: Boolean; FEnters: Integer; FFonts: array of PFont; function GetVSBounds: TFloatRect; procedure SetVSWidth(Value: Integer); procedure SetVSHeight(Value: Integer); procedure ResolutionChanged; procedure CreateFontTex(Font: Cardinal); public constructor Create; override; //internally used destructor Destroy; override; //internally used class function Name: string; override; //internally used procedure OnEvent(var Event: TCoreEvent); override; procedure Enter; //Enter 2D mode procedure Leave; //Leave 2D mode function MapCursor(const Cursor: TPoint): TPoint; //Map cursor to virtual screen procedure Move(X, Y: Single; Relative: Boolean = true); //Move origin procedure SetScissor(Left, Top, Width, Height: Single); //Set scissor window procedure RemoveScissor; //Remove scissor window //Draw primitives procedure LineWidth(w: Single); //Set line width procedure DrawLine(X1, Y1, X2, Y2: Single); overload; //Draw line from X1, Y1 to X2, Y2 procedure DrawLine(P1, P2: TPoint); overload; procedure DrawRectBorder(Left, Top, Width, Height: Single); overload; //Draw rect border procedure DrawRectBorder(const Rect: TRect); overload; procedure DrawRect(Left, Top, Width, Height: Single); overload; //Draw rectangle procedure DrawRect(const Rect: TRect); overload; procedure DrawRect(Left, Top, Width, Height, TexLeft, TexTop, TexWidth, TexHeight: Single); overload; //Draw rectangle with texture coordinates procedure DrawRect(const Rect, TexRect: TRect; TexSize: Integer); overload; //Font engine function CreateFont(Name: string; Size: Integer; Bold: Boolean=false): Cardinal; //Create font; Name - font name, Size - font size, Bold - normal/bold font; returns font ID procedure TextOut(Font: Cardinal; X, Y: Single; const Text: string); //Draw text; Font - font ID, X, Y - coordinates of left upper corner of text, Text - text for draw function TextWidth(Font: Cardinal; const Text: string): Integer; //Length of space, needed for drawing text function CharWidth(Font: Cardinal; C: Char): Single; //Exact character width function TextHeight(Font: Cardinal): Integer; //Height of space, needed for drawing text //Virtual screen property VSWidth: Integer read FVSWidth write SetVSWidth; //Virtual screen width property VSHeight: Integer read FVSHeight write SetVSHeight; //Virtual screen height property VSBounds: TFloatRect read GetVSBounds; //Virtual screen bounds end; var Render2D: TRender2D; //Render2D interface FontCharSet: Cardinal = DEFAULT_CHARSET; FontScale: Single = 4 / 3; const InvalidFont: Cardinal = $FFFFFFFF; implementation uses VSETexMan; constructor TRender2D.Create; begin inherited; Render2D := Self; FVSWidth := 800; FVSHeight := 600; ResolutionChanged; end; destructor TRender2D.Destroy; var i: Integer; begin Render2D := nil; {$IFDEF VSE_LOG}LogF(llInfo, 'Render2D: Freeing %d fonts', [Length(FFonts)]);{$ENDIF} for i := 0 to High(FFonts) do begin glDeleteLists(FFonts[i]^.List, 256); Dispose(FFonts[i]); end; Finalize(FFonts); inherited; end; class function TRender2D.Name: string; begin Result := 'Render2D'; end; procedure TRender2D.OnEvent(var Event: TCoreEvent); begin inherited; if (Event is TSysNotify) and ((Event as TSysNotify).Notify = snResolutionChanged) then ResolutionChanged; end; procedure TRender2D.Enter; begin Inc(FEnters); if FEnters > 1 then Exit; glPushAttrib(GL_ENABLE_BIT or GL_POINT_BIT or GL_LINE_BIT or GL_LIGHTING_BIT or GL_CURRENT_BIT or GL_COLOR_BUFFER_BIT or GL_TEXTURE_BIT or GL_SCISSOR_BIT or GL_TRANSFORM_BIT); glePushMatrix; with VSBounds do gleOrthoMatrix2(Left, Top, Right, Bottom); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_LINE_SMOOTH); glEnable(GL_POINT_SMOOTH); glEnable(GL_COLOR_MATERIAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); end; procedure TRender2D.Leave; begin FEnters := Max(FEnters - 1, 0); if FEnters > 0 then Exit; glePopMatrix; glPopAttrib; end; function TRender2D.MapCursor(const Cursor: TPoint): TPoint; begin if FVSPaddingVertical then begin Result.X := Round(Cursor.X / FVSScale); Result.Y := Round(Cursor.Y / FVSScale - FVSPadding); end else begin Result.X := Round(Cursor.X / FVSScale - FVSPadding); Result.Y := Round(Cursor.Y / FVSScale); end; end; procedure TRender2D.Move(X, Y: Single; Relative: Boolean); begin if not Relative then glLoadIdentity; glTranslate(Round(X * FVSScale) / FVSScale, Round(Y * FVSScale) / FVSScale, 0); end; procedure TRender2D.SetScissor(Left, Top, Width, Height: Single); begin if FVSPaddingVertical then Top := Top + FVSPadding else Left := Left + FVSPadding; glEnable(GL_SCISSOR_TEST); glScissor(Round(Left * FVSScale), Core.ResolutionY - Round((Top + Height) * FVSScale) - 1, Round(Width * FVSScale), Round(Height * FVSScale)); end; procedure TRender2D.RemoveScissor; begin glDisable(GL_SCISSOR_TEST); end; procedure TRender2D.LineWidth(w: Single); begin glLineWidth(w); glPointSize(0.9 * w); end; procedure TRender2D.DrawLine(X1, Y1, X2, Y2: Single); begin glBegin(GL_LINES); glVertex2f(X1, Y1); glVertex2f(X2, Y2); glEnd; end; procedure TRender2D.DrawLine(P1, P2: TPoint); begin DrawLine(P1.X, P1.Y, P2.X, P2.Y); end; procedure TRender2D.DrawRectBorder(Left, Top, Width, Height: Single); begin glBegin(GL_LINE_LOOP); glVertex2f(Left, Top); glVertex2f(Left + Width, Top); glVertex2f(Left + Width, Top + Height); glVertex2f(Left, Top + Height); glEnd; glBegin(GL_POINTS); glVertex2f(Left, Top); glVertex2f(Left + Width, Top); glVertex2f(Left + Width, Top + Height); glVertex2f(Left, Top + Height); glEnd; end; procedure TRender2D.DrawRectBorder(const Rect: TRect); begin with Rect do DrawRectBorder(Left, Top, Right - Left, Bottom - Top); end; procedure TRender2D.DrawRect(Left, Top, Width, Height: Single); begin glBegin(GL_QUADS); glVertex2f(Left, Top); glVertex2f(Left + Width, Top); glVertex2f(Left + Width, Top + Height); glVertex2f(Left, Top + Height); glEnd; end; procedure TRender2D.DrawRect(const Rect: TRect); begin with Rect do DrawRect(Left, Top, Right - Left, Bottom - Top); end; procedure TRender2D.DrawRect(Left, Top, Width, Height, TexLeft, TexTop, TexWidth, TexHeight: Single); begin glBegin(GL_QUADS); glTexCoord2f(TexLeft, TexTop); glVertex2f(Left, Top); glTexCoord2f(TexLeft + TexWidth, TexTop); glVertex2f(Left + Width, Top); glTexCoord2f(TexLeft + TexWidth, TexTop + TexHeight); glVertex2f(Left + Width, Top + Height); glTexCoord2f(TexLeft, TexTop + TexHeight); glVertex2f(Left, Top + Height); glEnd; end; procedure TRender2D.DrawRect(const Rect, TexRect: TRect; TexSize: Integer); begin with TexRect do DrawRect(Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, Left / TexSize, Top / TexSize, (Right - Left) / TexSize, (Bottom - Top) / TexSize); end; function TRender2D.CreateFont(Name: string; Size: Integer; Bold: Boolean): Cardinal; const BoolStr: array[Boolean] of Char = ('N', 'B'); var i: Integer; begin {$IFDEF VSE_LOG}Log(llInfo, 'Render2D: Creating font ' + Name + ': ' + IntToStr(Size) + BoolStr[Bold]);{$ENDIF} Name := UpperCase(Name); for i := 0 to High(FFonts) do if (FFonts[i]^.Name = Name) and (FFonts[i]^.Size = Size) and (FFonts[i]^.Bold = Bold) then begin Result := i; Exit; end; Result := Length(FFonts); SetLength(FFonts, Result + 1); New(FFonts[Result]); FFonts[Result]^.Size := Size; FFonts[Result]^.Bold := Bold; FFonts[Result]^.Name := Name; FFonts[Result]^.Tex := TexMan.AddTexture('__FONT_' + Name + IntToStr(Size) + BoolStr[Bold], nil, 1, 1, GL_ALPHA8, GL_ALPHA, true, false); FFonts[Result]^.List := glGenLists(256); CreateFontTex(Result); end; procedure TRender2D.TextOut(Font: Cardinal; X, Y: Single; const Text: string); var i: Integer; begin if (Font >= Cardinal(Length(FFonts))) or (FFonts[Font] = nil) then Exit; X := Round(X * FVSScale) / FVSScale; Y := Round(Y * FVSScale) / FVSScale; glPushAttrib(GL_COLOR_BUFFER_BIT or GL_TEXTURE_BIT or GL_LIST_BIT); glDisable(GL_CULL_FACE); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.1); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glListBase(FFonts[Font]^.List); TexMan.Bind(FFonts[Font]^.Tex, 0); glPushMatrix; glTranslatef(X, Y, 0); for i := 1 to Length(Text) do glCallLists(1, GL_UNSIGNED_BYTE, @Text[i]); glPopMatrix; glPopAttrib; end; function TRender2D.TextWidth(Font: Cardinal; const Text: string): Integer; var i: Integer; W: Single; begin W := 0; if (Font < Cardinal(Length(FFonts))) and Assigned(FFonts[Font]) then for i := 1 to Length(Text) do W := W + FFonts[Font]^.Width[Byte(Text[i])]; Result := Ceil(W); end; function TRender2D.CharWidth(Font: Cardinal; C: Char): Single; begin if (Font < Cardinal(Length(FFonts))) and Assigned(FFonts[Font]) then Result := FFonts[Font]^.Width[Byte(C)] else Result := 0; end; function TRender2D.TextHeight(Font: Cardinal): Integer; begin Result := 0; if (Font >= Cardinal(Length(FFonts))) or (FFonts[Font] = nil) then Exit; Result := FFonts[Font]^.Height; end; function TRender2D.GetVSBounds: TFloatRect; begin with Result do if FVSPaddingVertical then begin Left := 0; Top := -FVSPadding; Right := FVSWidth; Bottom := FVSHeight + FVSPadding; end else begin Left := -FVSPadding; Top := 0; Right := FVSWidth + FVSPadding; Bottom := FVSHeight; end; end; procedure TRender2D.SetVSWidth(Value: Integer); begin if Value <= 0 then Exit; FVSWidth := Value; ResolutionChanged; end; procedure TRender2D.SetVSHeight(Value: Integer); begin if Value <= 0 then Exit; FVSHeight := Value; ResolutionChanged; end; procedure TRender2D.ResolutionChanged; var i: Integer; begin FVSPaddingVertical := FVSWidth / FVSHeight > Core.ResolutionX / Core.ResolutionY; if FVSPaddingVertical then begin FVSScale := Core.ResolutionX / FVSWidth; FVSPadding := (Core.ResolutionY / FVSScale - FVSHeight) / 2; end else begin FVSScale := Core.ResolutionY / FVSHeight; FVSPadding := (Core.ResolutionX / FVSScale - FVSWidth) / 2; end; for i := 0 to High(FFonts) do CreateFontTex(i); end; procedure TRender2D.CreateFontTex(Font: Cardinal); const Weight: array[Boolean] of Integer = (400, 700); Margin = 32; var i: Integer; FNT: HFONT; MDC: HDC; BMP: HBITMAP; BI: BITMAPINFO; Pix: PByteArray; Data: PByteArray; CS: TSize; s, t: Single; CharSize, FontTexSize: TPoint; begin with FFonts[Font]^ do try MDC := CreateCompatibleDC(Core.DC); FNT := Windows.CreateFont(-Ceil(FontScale * FVSScale * Size), 0, 0, 0, Weight[Bold], 0, 0, 0, FontCharSet, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, 0, PChar(Name)); SelectObject(MDC, FNT); CharSize := Point(0, 0); for i := 0 to 255 do begin GetTextExtentPoint32(MDC, @Char(i), 1, CS); CharSize.X := Max(CharSize.X, CS.cx); CharSize.Y := Max(CharSize.Y, CS.cy); end; FontTexSize := Point(Max(128, Min(CeilPOT(16 * CharSize.X + Margin), glMaxTextureSize)), Max(128, Min(CeilPOT(16 * CharSize.Y + Margin), glMaxTextureSize))); ZeroMemory(@BI, SizeOf(BI)); with BI.bmiHeader do begin biSize := SizeOf(BITMAPINFOHEADER); biWidth := FontTexSize.X; biHeight := FontTexSize.Y; biPlanes := 1; biBitCount := 24; biSizeImage := biWidth * biHeight * biBitCount div 8; end; BMP := CreateDIBSection(MDC, BI, DIB_RGB_COLORS, Pointer(Pix), 0, 0); ZeroMemory(Pix, FontTexSize.X * FontTexSize.Y * 3); SelectObject(MDC, BMP); SetBkMode(MDC, TRANSPARENT); SetTextColor(MDC, $FFFFFF); for i := 0 to 255 do Windows.TextOut(MDC, i mod 16 * (FontTexSize.X div 16), i div 16 * (FontTexSize.Y div 16), @Char(i), 1); GetMem(Data, FontTexSize.X * FontTexSize.Y); for i := 0 to FontTexSize.X * FontTexSize.Y - 1 do Data[i] := Pix[i * 3]; glBindTexture(GL_TEXTURE_2D, Tex); glPixelStore(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, FontTexSize.X, FontTexSize.Y, 0, GL_ALPHA, GL_UNSIGNED_BYTE, Data); Height := 0; for i := 0 to 255 do begin glNewList(List + Cardinal(i), GL_COMPILE); s := (i mod 16) / 16; t := (i div 16) / 16; GetTextExtentPoint32(MDC, @Char(i), 1, CS); Width[i] := CS.cx / FVSScale; Height := Max(Ceil(CS.cy / FVSScale), Height); glBegin(GL_QUADS); glTexCoord2f(s, 1 - t); glVertex2f(0, 0); glTexCoord2f(s + CS.cx / FontTexSize.X, 1 - t); glVertex2f(CS.cx / FVSScale, 0); glTexCoord2f(s + CS.cx / FontTexSize.X, 1 - t - CS.cy / FontTexSize.Y); glVertex2f(CS.cx / FVSScale, CS.cy / FVSScale); glTexCoord2f(s, 1 - t - CS.cy / FontTexSize.Y); glVertex2f(0, CS.cy / FVSScale); glEnd; glTranslatef(Width[i], 0, 0); glEndList; end; finally FreeMem(Data); DeleteObject(FNT); DeleteObject(BMP); DeleteDC(MDC); end; end; initialization RegisterModule(TRender2D); end.
(**************************************************************************** * Утилиты для работы с 16-тиричной системой счисления v1.00 beta 2 * * * **************************************************************************** * (C) NiKe'Soft * ****************************************************************************) Unit hex; INTERFACE Function HexB(B: Byte): string; Function HexW(W: Word): string; Function HexL(L: longint): string; IMPLEMENTATION Function HexB(B: Byte): string; Const Digits: array[0..15] of char = '0123456789ABCDEF'; begin HexB[0]:=#2; HexB[1]:=Digits[B SHR 4]; HexB[2]:=DIgits[B AND $0F]; end; Function HexW(W: Word): string; var s: string; begin s:=''; S:=HexB(W SHR 8); S:=S+HexB(W AND $00FF); HexW:=S; end; Function HexL(L: longint): string; var s: string; begin s:=''; S:=HexW(l shr 16); S:=S+HexW(l AND $0000FFFF); HexL:=S; end; end.
unit xxHash64; {$POINTERMATH ON} {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses {$IFDEF FPC} SysUtils {$ELSE} System.SysUtils {$ENDIF}; type PUInt64 = ^UInt64; TxxHash64 = class strict private class function RotateLeft64(value: UInt64; count: Integer): UInt64; static; inline; type TXXH_State = Record private total_len: UInt64; seed: UInt64; v1: UInt64; v2: UInt64; v3: UInt64; v4: UInt64; memsize: LongWord; ptrmemory: Pointer; end; class var const PRIME64_1: UInt64 = 11400714785074694791; PRIME64_2: UInt64 = 14029467366897019727; PRIME64_3: UInt64 = 1609587929392839161; PRIME64_4: UInt64 = 9650029242287828579; PRIME64_5: UInt64 = 2870177450012600261; protected F_state: TXXH_State; public constructor Create(); destructor Destroy(); Override; procedure Init(seed: UInt64 = 0); function Update(const input; len: Integer): Boolean; class function CalculateHash64(const HashData; len: Integer = 0; seed: UInt64 = 0): UInt64; static; function Digest(): UInt64; end; implementation constructor TxxHash64.Create(); begin inherited Create; end; destructor TxxHash64.Destroy(); begin FreeMem(F_state.ptrmemory, 32); inherited Destroy; end; procedure TxxHash64.Init(seed: UInt64 = 0); begin F_state.seed := seed; F_state.v1 := seed + PRIME64_1 + PRIME64_2; F_state.v2 := seed + PRIME64_2; F_state.v3 := seed + 0; F_state.v4 := seed - PRIME64_1; F_state.total_len := 0; F_state.memsize := 0; GetMem(F_state.ptrmemory, 32); end; class function TxxHash64.CalculateHash64(const HashData; len: Integer = 0; seed: UInt64 = 0): UInt64; var v1, v2, v3, v4: UInt64; ptrLimit, ptrEnd, ptrBuffer: Pointer; begin ptrBuffer := @HashData; NativeUInt(ptrEnd) := NativeUInt(ptrBuffer) + UInt32(len); if len >= 32 then begin v1 := seed + PRIME64_1 + PRIME64_2; v2 := seed + PRIME64_2; v3 := seed; v4 := seed - PRIME64_1; NativeUInt(ptrLimit) := NativeUInt(ptrEnd) - 32; repeat v1 := PRIME64_1 * RotateLeft64(v1 + PRIME64_2 * PUInt64(ptrBuffer)^, 31); v2 := PRIME64_1 * RotateLeft64(v2 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 8)^, 31); v3 := PRIME64_1 * RotateLeft64(v3 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 16)^, 31); v4 := PRIME64_1 * RotateLeft64(v4 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 24)^, 31); Inc(NativeUInt(ptrBuffer), 32); until not(NativeUInt(ptrBuffer) <= NativeUInt(ptrLimit)); result := RotateLeft64(v1, 1) + RotateLeft64(v2, 7) + RotateLeft64(v3, 12) + RotateLeft64(v4, 18); v1 := RotateLeft64(v1 * PRIME64_2, 31) * PRIME64_1; result := (result xor v1) * PRIME64_1 + PRIME64_4; v2 := RotateLeft64(v2 * PRIME64_2, 31) * PRIME64_1; result := (result xor v2) * PRIME64_1 + PRIME64_4; v3 := RotateLeft64(v3 * PRIME64_2, 31) * PRIME64_1; result := (result xor v3) * PRIME64_1 + PRIME64_4; v4 := RotateLeft64(v4 * PRIME64_2, 31) * PRIME64_1; result := (result xor v4) * PRIME64_1 + PRIME64_4; end else result := seed + PRIME64_5; Inc(result, UInt64(len)); while (NativeUInt(ptrBuffer) + 8) <= (NativeUInt(ptrEnd)) do begin result := result xor (PRIME64_1 * RotateLeft64(PRIME64_2 * PUInt64(ptrBuffer)^, 31)); result := RotateLeft64(result, 27) * PRIME64_1 + PRIME64_4; Inc(NativeUInt(ptrBuffer), 8); end; if (NativeUInt(ptrBuffer) + 4) <= NativeUInt(ptrEnd) then begin result := result xor (PLongWord(ptrBuffer)^ * PRIME64_1); result := RotateLeft64(result, 23) * PRIME64_2 + PRIME64_3; Inc(NativeUInt(ptrBuffer), 4); end; while NativeUInt(ptrBuffer) < NativeUInt(ptrEnd) do begin result := result xor (PByte(ptrBuffer)^ * PRIME64_5); result := RotateLeft64(result, 11) * PRIME64_1; Inc(NativeUInt(ptrBuffer)); end; result := result xor (result shr 33); result := result * PRIME64_2; result := result xor (result shr 29); result := result * PRIME64_3; result := result xor (result shr 32); end; function TxxHash64.Update(const input; len: Integer): Boolean; var v1, v2, v3, v4: UInt64; ptrBuffer, ptrTemp, ptrEnd, ptrLimit: Pointer; begin ptrBuffer := @input; F_state.total_len := F_state.total_len + UInt64(len); if ((F_state.memsize + UInt32(len)) < UInt32(32)) then begin ptrTemp := Pointer(NativeUInt(F_state.ptrmemory) + F_state.memsize); Move(ptrBuffer^, ptrTemp^, len); F_state.memsize := F_state.memsize + UInt32(len); result := True; Exit; end; ptrEnd := Pointer(NativeUInt(ptrBuffer) + UInt32(len)); if F_state.memsize > 0 then begin ptrTemp := Pointer(NativeUInt(F_state.ptrmemory) + F_state.memsize); Move(ptrBuffer^, ptrTemp^, 32 - F_state.memsize); F_state.v1 := PRIME64_1 * RotateLeft64(F_state.v1 + PRIME64_2 * PUInt64(F_state.ptrmemory)^, 31); F_state.v2 := PRIME64_1 * RotateLeft64(F_state.v2 + PRIME64_2 * PUInt64(NativeUInt(F_state.ptrmemory) + 8)^, 31); F_state.v3 := PRIME64_1 * RotateLeft64(F_state.v3 + PRIME64_2 * PUInt64(NativeUInt(F_state.ptrmemory) + 16)^, 31); F_state.v4 := PRIME64_1 * RotateLeft64(F_state.v4 + PRIME64_2 * PUInt64(NativeUInt(F_state.ptrmemory) + 24)^, 31); ptrBuffer := Pointer(NativeUInt(ptrBuffer) + (32 - F_state.memsize)); F_state.memsize := 0; end; if NativeUInt(ptrBuffer) <= (NativeUInt(ptrEnd) - 32) then begin v1 := F_state.v1; v2 := F_state.v2; v3 := F_state.v3; v4 := F_state.v4; ptrLimit := Pointer(NativeUInt(ptrEnd) - 32); repeat v1 := PRIME64_1 * RotateLeft64(v1 + PRIME64_2 * PUInt64(ptrBuffer)^, 31); v2 := PRIME64_1 * RotateLeft64(v2 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 8)^, 31); v3 := PRIME64_1 * RotateLeft64(v3 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 16)^, 31); v4 := PRIME64_1 * RotateLeft64(v4 + PRIME64_2 * PUInt64(NativeUInt(ptrBuffer) + 24)^, 31); Inc(NativeUInt(ptrBuffer), 32); until not(NativeUInt(ptrBuffer) <= NativeUInt(ptrLimit)); F_state.v1 := v1; F_state.v2 := v2; F_state.v3 := v3; F_state.v4 := v4; end; if NativeUInt(ptrBuffer) < NativeUInt(ptrEnd) then begin ptrTemp := F_state.ptrmemory; Move(ptrBuffer^, ptrTemp^, NativeUInt(ptrEnd) - NativeUInt(ptrBuffer)); F_state.memsize := NativeUInt(ptrEnd) - NativeUInt(ptrBuffer); end; result := True; end; function TxxHash64.Digest: UInt64; var v1, v2, v3, v4: UInt64; ptrBuffer, ptrEnd: Pointer; begin if F_state.total_len >= UInt64(32) then begin v1 := F_state.v1; v2 := F_state.v2; v3 := F_state.v3; v4 := F_state.v4; result := RotateLeft64(v1, 1) + RotateLeft64(v2, 7) + RotateLeft64(v3, 12) + RotateLeft64(v4, 18); v1 := RotateLeft64(v1 * PRIME64_2, 31) * PRIME64_1; result := (result xor v1) * PRIME64_1 + PRIME64_4; v2 := RotateLeft64(v2 * PRIME64_2, 31) * PRIME64_1; result := (result xor v2) * PRIME64_1 + PRIME64_4; v3 := RotateLeft64(v3 * PRIME64_2, 31) * PRIME64_1; result := (result xor v3) * PRIME64_1 + PRIME64_4; v4 := RotateLeft64(v4 * PRIME64_2, 31) * PRIME64_1; result := (result xor v4) * PRIME64_1 + PRIME64_4; end else result := F_state.seed + PRIME64_5; Inc(result, F_state.total_len); ptrBuffer := F_state.ptrmemory; ptrEnd := Pointer(NativeUInt(ptrBuffer) + F_state.memsize); while (NativeUInt(ptrBuffer) + 8) <= NativeUInt(ptrEnd) do begin result := result xor (PRIME64_1 * RotateLeft64(PRIME64_2 * PUInt64(ptrBuffer)^, 31)); result := RotateLeft64(result, 27) * PRIME64_1 + PRIME64_4; Inc(NativeUInt(ptrBuffer), 8); end; if (NativeUInt(ptrBuffer) + 4) <= NativeUInt(ptrEnd) then begin result := result xor PLongWord(ptrBuffer)^ * PRIME64_1; result := RotateLeft64(result, 23) * PRIME64_2 + PRIME64_3; Inc(NativeUInt(ptrBuffer), 4); end; while NativeUInt(ptrBuffer) < NativeUInt(ptrEnd) do begin result := result xor (PByte(ptrBuffer)^ * PRIME64_5); result := RotateLeft64(result, 11) * PRIME64_1; Inc(NativeUInt(ptrBuffer)); end; result := result xor (result shr 33); result := result * PRIME64_2; result := result xor (result shr 29); result := result * PRIME64_3; result := result xor (result shr 32); end; class function TxxHash64.RotateLeft64(value: UInt64; count: Integer): UInt64; begin result := (value shl count) or (value shr (64 - count)); end; {$POINTERMATH OFF} end.
unit UDmFinancas; interface uses SysUtils, Classes, FMTBcd, DB, DBClient, Provider, SqlExpr, DBLocal, DBLocalS; type TDmFinancas = class(TDataModule) sdsDebitosAnuidades: TSQLDataSet; dspDebitosAnuidades: TDataSetProvider; cdsDebitosAnuidades: TClientDataSet; dsDebitosAnuidades: TDataSource; cdsDebitosAnuidadesANUID_ID: TIntegerField; cdsDebitosAnuidadesDESCRICAO: TStringField; cdsDebitosAnuidadesANO: TIntegerField; cdsDebitosAnuidadesVALOR: TFMTBCDField; cdsDebitosAnuidadesVENCIMENTO: TDateField; cdsDebitosAnuidadesTIPOCONTRIB: TStringField; cdsDebitosAnuidadesPARC_ID: TIntegerField; cdsDebitosAnuidadesNUM_PARCELA: TIntegerField; cdsDebitosAnuidadesTPCONTRIB_ID: TIntegerField; cdsDebitosAnuidadesMULTA: TFMTBCDField; cdsDebitosAnuidadesJUROS: TFMTBCDField; cdsDebitosAnuidadesCORRECAO: TFMTBCDField; cdsDebitosAnuidadesTOTAL: TFMTBCDField; sdsDebitosParcelamento: TSQLDataSet; dspDebitosParcelamento: TDataSetProvider; cdsDebitosParcelamento: TClientDataSet; IntegerField1: TIntegerField; StringField1: TStringField; IntegerField2: TIntegerField; FMTBCDField1: TFMTBCDField; DateField1: TDateField; StringField2: TStringField; IntegerField3: TIntegerField; IntegerField4: TIntegerField; IntegerField5: TIntegerField; FMTBCDField2: TFMTBCDField; FMTBCDField3: TFMTBCDField; FMTBCDField4: TFMTBCDField; FMTBCDField5: TFMTBCDField; dsDebitosParcelamento: TDataSource; PROC_GERA_ANUIDADE: TSQLStoredProc; PROC_ANUIDADE_DEL: TSQLStoredProc; sdsGerarBoletos: TSQLDataSet; dspGerarBoletos: TDataSetProvider; cdsGerarBoletos: TClientDataSet; IntegerField6: TIntegerField; StringField3: TStringField; IntegerField7: TIntegerField; FMTBCDField6: TFMTBCDField; DateField2: TDateField; StringField4: TStringField; IntegerField8: TIntegerField; IntegerField9: TIntegerField; IntegerField10: TIntegerField; FMTBCDField7: TFMTBCDField; FMTBCDField8: TFMTBCDField; FMTBCDField9: TFMTBCDField; FMTBCDField10: TFMTBCDField; dsGerarBoletos: TDataSource; sdsGerarBoletosANUID_ID: TIntegerField; sdsGerarBoletosDESCRICAO: TStringField; sdsGerarBoletosANO: TIntegerField; sdsGerarBoletosVALOR: TFMTBCDField; sdsGerarBoletosVENCIMENTO: TDateField; sdsGerarBoletosTIPOCONTRIB: TStringField; sdsGerarBoletosPARC_ID: TIntegerField; sdsGerarBoletosNUM_PARCELA: TIntegerField; sdsGerarBoletosTPCONTRIB_ID: TIntegerField; sdsGerarBoletosMULTA: TFMTBCDField; sdsGerarBoletosJUROS: TFMTBCDField; sdsGerarBoletosCORRECAO: TFMTBCDField; sdsGerarBoletosTOTAL: TFMTBCDField; sdsExtrato: TSQLDataSet; dspExtrato: TDataSetProvider; cdsExtrato: TClientDataSet; dsExtrato: TDataSource; cdsExtratoANUID_ID: TIntegerField; cdsExtratoDESCRICAO: TStringField; cdsExtratoANO: TIntegerField; cdsExtratoVALOR: TFMTBCDField; cdsExtratoVENCIMENTO: TDateField; cdsExtratoTIPOCONTRIB: TStringField; cdsExtratoPARC_ID: TIntegerField; cdsExtratoNUM_PARCELA: TIntegerField; cdsExtratoTPCONTRIB_ID: TIntegerField; cdsExtratoMULTA: TFMTBCDField; cdsExtratoJUROS: TFMTBCDField; cdsExtratoCORRECAO: TFMTBCDField; cdsExtratoTOTAL: TFMTBCDField; sdsTotalExtrato: TSQLDataSet; sdsTotalExtratoTIPOCONTRIB: TStringField; sdsTotalExtratoTOTAL: TFMTBCDField; sdsPrescricao: TSQLDataSet; dspPrescricao: TDataSetProvider; cdsPrescricao: TClientDataSet; dsPrescricao: TDataSource; PROC_PRESCRICAO: TSQLStoredProc; sdsPagtos: TSQLDataSet; dspPagtos: TDataSetProvider; cdsPagtos: TClientDataSet; cdsPagtosBOL_ID: TIntegerField; cdsPagtosCONTA_ID: TIntegerField; cdsPagtosDT_CRIACAO: TDateField; cdsPagtosDT_VENCIMENTO: TDateField; cdsPagtosTP_STATUS_ID: TIntegerField; cdsPagtosVALOR_TOTAL: TFMTBCDField; cdsPagtosNOSSONUMERO: TStringField; cdsPagtosDT_RECEBIMENTO: TDateField; cdsPagtosDT_CREDITO: TDateField; cdsPagtosDT_BAIXA: TDateField; cdsPagtosVALOR_RECEBIMENTO: TFMTBCDField; cdsPagtosMULTA_PAGA: TFMTBCDField; cdsPagtosCORRECAO_PAGA: TFMTBCDField; cdsPagtosJUROS_PAGO: TFMTBCDField; cdsPagtosDESCONTO_PAGTO: TFMTBCDField; cdsPagtosTP_STATUS_DESCRICAO: TStringField; cdsPagtosTP_CONTRIB_DESCRICAO: TStringField; dsPagtos: TDataSource; sdsContribsParcelamento: TSQLDataSet; IntegerField11: TIntegerField; StringField5: TStringField; IntegerField12: TIntegerField; FMTBCDField11: TFMTBCDField; DateField3: TDateField; StringField6: TStringField; IntegerField13: TIntegerField; IntegerField14: TIntegerField; IntegerField15: TIntegerField; FMTBCDField12: TFMTBCDField; FMTBCDField13: TFMTBCDField; FMTBCDField14: TFMTBCDField; FMTBCDField15: TFMTBCDField; dspContribsParcelamento: TDataSetProvider; cdsContribsParcelamento: TClientDataSet; dsContribsParcelamento: TDataSource; cdsContribsParcelamentoANUID_ID: TIntegerField; cdsContribsParcelamentoDESCRICAO: TStringField; cdsContribsParcelamentoANO: TIntegerField; cdsContribsParcelamentoVALOR: TFMTBCDField; cdsContribsParcelamentoVENCIMENTO: TDateField; cdsContribsParcelamentoTIPOCONTRIB: TStringField; cdsContribsParcelamentoPARC_ID: TIntegerField; cdsContribsParcelamentoNUM_PARCELA: TIntegerField; cdsContribsParcelamentoTPCONTRIB_ID: TIntegerField; cdsContribsParcelamentoMULTA: TFMTBCDField; cdsContribsParcelamentoJUROS: TFMTBCDField; cdsContribsParcelamentoCORRECAO: TFMTBCDField; cdsContribsParcelamentoTOTAL: TFMTBCDField; PROC_PARCELAMENTOI: TSQLStoredProc; PROC_PARCELANUIDADES_I: TSQLStoredProc; PROC_PARCELPARCELAS_I: TSQLStoredProc; sdsParcelamento: TSQLDataSet; dspParcelamento: TDataSetProvider; cdsParcelamento: TClientDataSet; cdsParcelamentoPARCEL_ID: TIntegerField; cdsParcelamentoDESCRICAO_PARC: TStringField; cdsParcelamentoDT_PARCEL: TDateField; cdsParcelamentoNUM_PARC: TIntegerField; cdsParcelamentoVALOR_TOTAL: TFMTBCDField; cdsParcelamentoDT_PRIM_PARCELA: TDateField; cdsParcelamentoTP_STATUS_ID: TIntegerField; cdsParcelamentoTP_STATUS_DESCR: TStringField; dsParcelamento: TDataSource; sdsParcelasParcel: TSQLDataSet; dspParcelasParc: TDataSetProvider; cdsParcelasParc: TClientDataSet; dsParcelasParc: TDataSource; cdsParcelasParcPARC_ID: TIntegerField; cdsParcelasParcNUM_PARCELA: TIntegerField; cdsParcelasParcDT_VENCIMENTO: TDateField; cdsParcelasParcVALOR_PARC: TFMTBCDField; cdsParcelasParcDT_RECEBIMENTO: TDateField; cdsParcelasParcNOSSONUMERO: TStringField; sdsParcelAnuidades: TSQLDataSet; dspParcelAnuidades: TDataSetProvider; cdsParcelAnuidades: TClientDataSet; dsParcelAnuidades: TDataSource; cdsParcelAnuidadesANUID_ID: TIntegerField; cdsParcelAnuidadesASS_ID: TIntegerField; cdsParcelAnuidadesTP_CONTRIB_ID: TIntegerField; cdsParcelAnuidadesDESCRICAO: TStringField; cdsParcelAnuidadesANO: TIntegerField; cdsParcelAnuidadesVENCIMENTO: TDateField; cdsParcelAnuidadesSITUACAO: TStringField; cdsParcelasParcPAR_DESCRICAO: TStringField; cdsParcelAnuidadesVALOR_ANUID: TFMTBCDField; cdsParcelAnuidadesMULTA_ANUID: TFMTBCDField; cdsParcelAnuidadesJUROS_ANUID: TFMTBCDField; cdsParcelAnuidadesCORRECAO_ANUID: TFMTBCDField; cdsParcelAnuidadesTOTAL: TFMTBCDField; cdsParcelAnuidadesTP_CONTRIB_DESCRICAO: TStringField; sdsPROC_PARCELAMENTO_DEL: TSQLDataSet; dspPROC_PARCELAMENTO_DEL: TDataSetProvider; cdsPROC_PARCELAMENTO_DEL: TClientDataSet; cdsPROC_PARCELAMENTO_DELEXCLUIDO: TIntegerField; sdsPROC_PARCELAMENTO_AT: TSQLDataSet; dspPROC_PARCELAMENTO_AT: TDataSetProvider; cdsPROC_PARCELAMENTO_AT: TClientDataSet; cdsPROC_PARCELAMENTO_ATAVISO: TIntegerField; cdsPagtosFORMA_PAGTO: TStringField; PROC_MANUT_PAGTO: TSQLStoredProc; sdsEncargos: TSQLDataSet; dspEncargos: TDataSetProvider; cdsEncargos: TClientDataSet; sds_Cobranca: TSQLDataSet; dspCobranca: TDataSetProvider; cdsCobranca: TClientDataSet; cdsCobrancaASS_ID: TIntegerField; cdsCobrancaREGISTRO: TStringField; cdsCobrancaNOME: TStringField; cdsCobrancaEMP_ID: TIntegerField; cdsCobrancaREGIAO: TStringField; cdsCobrancaCPFCNPJ: TStringField; cdsCobrancaANUID_ID: TIntegerField; cdsCobrancaDESCRICAO: TStringField; cdsCobrancaANO: TIntegerField; cdsCobrancaVALOR: TFMTBCDField; cdsCobrancaVENCIMENTO: TDateField; cdsCobrancaTIPOCONTRIB: TStringField; cdsCobrancaPARC_ID: TIntegerField; cdsCobrancaNUM_PARCELA: TIntegerField; cdsCobrancaTPCONTRIB_ID: TIntegerField; cdsCobrancaMULTA: TFMTBCDField; cdsCobrancaJUROS: TFMTBCDField; cdsCobrancaCORRECAO: TFMTBCDField; cdsCobrancaTOTAL: TFMTBCDField; cdsCobrancaEND_ID: TIntegerField; cdsCobrancaEND_LOGRADOURO: TStringField; cdsCobrancaEND_NUMERO: TStringField; cdsCobrancaEND_COMPLEMENTO: TStringField; cdsCobrancaEND_BAIRRO: TStringField; cdsCobrancaEND_CEP: TStringField; cdsCobrancaCIDADE_ID: TIntegerField; cdsCobrancaTP_ENDER_ID: TIntegerField; cdsCobrancaEND_CORRESP: TSmallintField; cdsCobrancaEND_CORRESP_DEV: TSmallintField; cdsCobrancaSTATUSCORRESP: TStringField; cdsCobrancaCIDADE_NOME: TStringField; cdsCobrancaESTADO_NOME: TStringField; cdsCobrancaTP_ENDER_DESCR: TStringField; cdsCobrancaENDER_COMPLETO: TStringField; cdsCobrancaTP_ASSOC_ID: TIntegerField; sdsInadimp: TSQLDataSet; dspInadip: TDataSetProvider; cdsInadip: TClientDataSet; cdsInadipASS_ID: TIntegerField; cdsInadipREGISTRO: TStringField; cdsInadipNOME: TStringField; cdsInadipEMP_ID: TIntegerField; cdsInadipREGIAO: TStringField; cdsInadipCPFCNPJ: TStringField; cdsInadipANUID_ID: TIntegerField; cdsInadipDESCRICAO: TStringField; cdsInadipANO: TIntegerField; cdsInadipVALOR: TFMTBCDField; cdsInadipVENCIMENTO: TDateField; cdsInadipTIPOCONTRIB: TStringField; cdsInadipPARC_ID: TIntegerField; cdsInadipNUM_PARCELA: TIntegerField; cdsInadipTPCONTRIB_ID: TIntegerField; cdsInadipMULTA: TFMTBCDField; cdsInadipJUROS: TFMTBCDField; cdsInadipCORRECAO: TFMTBCDField; cdsInadipTOTAL: TFMTBCDField; cdsInadipEND_ID: TIntegerField; cdsInadipEND_LOGRADOURO: TStringField; cdsInadipEND_NUMERO: TStringField; cdsInadipEND_COMPLEMENTO: TStringField; cdsInadipEND_BAIRRO: TStringField; cdsInadipEND_CEP: TStringField; cdsInadipCIDADE_ID: TIntegerField; cdsInadipTP_ENDER_ID: TIntegerField; cdsInadipEND_CORRESP: TSmallintField; cdsInadipEND_CORRESP_DEV: TSmallintField; cdsInadipSTATUSCORRESP: TStringField; cdsInadipCIDADE_NOME: TStringField; cdsInadipESTADO_NOME: TStringField; cdsInadipTP_ENDER_DESCR: TStringField; cdsInadipENDER_COMPLETO: TStringField; cdsInadipTP_ASSOC_ID: TIntegerField; dsPagtosItens: TDataSource; cdspagtosItens: TClientDataSet; dspPagtosItens: TDataSetProvider; sdsPagtosItens: TSQLDataSet; cdspagtosItensBOL_ID: TIntegerField; cdspagtosItensITEM_BOL_ID: TIntegerField; cdspagtosItensPARC_ID: TIntegerField; cdspagtosItensANUID_ID: TIntegerField; cdspagtosItensDESCRICAO_ITEM: TStringField; cdspagtosItensVALOR_ITEM: TFMTBCDField; cdspagtosItensVALOR_MULTA: TFMTBCDField; cdspagtosItensVALOR_JUROS: TFMTBCDField; cdspagtosItensVALOR_CORRECAO: TFMTBCDField; cdspagtosItensTOTALITEM: TFMTBCDField; cdsPagtosENCARGOS_PAGO: TFMTBCDField; cdsPagtosSITUACAO: TStringField; sdsExtratoGeral: TSQLDataSet; dspExtratogeral: TDataSetProvider; cdsExtratogeral: TClientDataSet; dsExtratoGeral: TDataSource; cdsExtratogeralANUID_ID: TIntegerField; cdsExtratogeralDESCRICAO: TStringField; cdsExtratogeralANO: TIntegerField; cdsExtratogeralVALOR: TFMTBCDField; cdsExtratogeralVENCIMENTO: TDateField; cdsExtratogeralTIPOCONTRIB: TStringField; cdsExtratogeralVALORTOTAL: TFMTBCDField; cdsExtratogeralJUROS: TFMTBCDField; cdsExtratogeralMULTA: TFMTBCDField; cdsExtratogeralCORRECAO: TFMTBCDField; cdsExtratogeralSITUACAO: TStringField; cdsParcelasParcVALOR_PAGO: TFMTBCDField; cdsParcelasParcPARCEL_ID: TIntegerField; cdsEncargosMULTA: TFloatField; cdsEncargosJUROS: TFloatField; cdsEncargosCORRECAO: TFloatField; cdsPrescricaoANUID_ID: TIntegerField; cdsPrescricaoDESCRICAO: TStringField; cdsPrescricaoANO: TIntegerField; cdsPrescricaoVALOR: TFMTBCDField; cdsPrescricaoVENCIMENTO: TDateField; cdsPrescricaoTIPOCONTRIB: TStringField; cdsPrescricaoPARC_ID: TIntegerField; cdsPrescricaoNUM_PARCELA: TIntegerField; cdsPrescricaoTPCONTRIB_ID: TIntegerField; cdsPrescricaoMULTA: TFMTBCDField; cdsPrescricaoJUROS: TFMTBCDField; cdsPrescricaoCORRECAO: TFMTBCDField; cdsPrescricaoTOTAL: TFMTBCDField; sdsRelatParcels: TSQLDataSet; dspRelatParcels: TDataSetProvider; cdsRelatParcels: TClientDataSet; cdsRelatParcelsASS_ID: TIntegerField; cdsRelatParcelsREGISTRO: TStringField; cdsRelatParcelsNOME: TStringField; cdsRelatParcelsREGIAO: TStringField; cdsRelatParcelsCPFCNPJ: TStringField; cdsRelatParcelsTP_PESSOA: TStringField; cdsRelatParcelsDESCRICAO: TStringField; cdsRelatParcelsDT_PARC: TDateField; cdsRelatParcelsNUMPARC: TIntegerField; cdsRelatParcelsEND_ID: TIntegerField; cdsRelatParcelsEND_LOGRADOURO: TStringField; cdsRelatParcelsEND_NUMERO: TStringField; cdsRelatParcelsEND_COMPLEMENTO: TStringField; cdsRelatParcelsEND_BAIRRO: TStringField; cdsRelatParcelsEND_CEP: TStringField; cdsRelatParcelsCIDADE_ID: TIntegerField; cdsRelatParcelsTP_ENDER_ID: TIntegerField; cdsRelatParcelsEND_CORRESP: TSmallintField; cdsRelatParcelsEND_CORRESP_DEV: TSmallintField; cdsRelatParcelsSTATUSCORRESP: TStringField; cdsRelatParcelsCIDADE_NOME: TStringField; cdsRelatParcelsESTADO_NOME: TStringField; cdsRelatParcelsTP_ENDER_DESCR: TStringField; cdsRelatParcelsENDER_COMPLETO: TStringField; sdsQtdeParcelAtivos: TSQLClientDataSet; sdsQtdeParcelAtivosQTDE: TIntegerField; sdsEmdia: TSQLDataSet; dspEmdia: TDataSetProvider; cdsEmdia: TClientDataSet; cdsEmdiaASS_ID: TIntegerField; cdsEmdiaREGISTRO: TStringField; cdsEmdiaNOME: TStringField; cdsEmdiaEMP_ID: TIntegerField; cdsEmdiaREGIAO: TStringField; cdsEmdiaCPFCNPJ: TStringField; cdsEmdiaEND_ID: TIntegerField; cdsEmdiaEND_LOGRADOURO: TStringField; cdsEmdiaEND_NUMERO: TStringField; cdsEmdiaEND_COMPLEMENTO: TStringField; cdsEmdiaEND_BAIRRO: TStringField; cdsEmdiaEND_CEP: TStringField; cdsEmdiaCIDADE_ID: TIntegerField; cdsEmdiaTP_ENDER_ID: TIntegerField; cdsEmdiaEND_CORRESP: TSmallintField; cdsEmdiaEND_CORRESP_DEV: TSmallintField; cdsEmdiaSTATUSCORRESP: TStringField; cdsEmdiaCIDADE_NOME: TStringField; cdsEmdiaESTADO_NOME: TStringField; cdsEmdiaTP_ENDER_DESCR: TStringField; cdsEmdiaENDER_COMPLETO: TStringField; cdsEmdiaTP_ASSOC_ID: TIntegerField; sdsProcDebitos: TSQLDataSet; dspProcDebitos: TDataSetProvider; cdsProcDebitos: TClientDataSet; cdsProcDebitosRESULTADO: TIntegerField; sdsVerParcelamento: TSQLDataSet; dspVerParcelamento: TDataSetProvider; cdsVerParcelamento: TClientDataSet; cdsVerParcelamentoRESULTADO: TIntegerField; PROC_GERA_FINANCAS_ASSOC: TSQLStoredProc; PROC_PARCELA_ALTERDADOS: TSQLStoredProc; SQLDataSet1: TSQLDataSet; DataSetProvider1: TDataSetProvider; ClientDataSet1: TClientDataSet; IntegerField16: TIntegerField; StringField7: TStringField; StringField8: TStringField; IntegerField17: TIntegerField; StringField9: TStringField; StringField10: TStringField; IntegerField18: TIntegerField; StringField11: TStringField; IntegerField19: TIntegerField; FMTBCDField16: TFMTBCDField; DateField4: TDateField; StringField12: TStringField; IntegerField20: TIntegerField; IntegerField21: TIntegerField; IntegerField22: TIntegerField; FMTBCDField17: TFMTBCDField; FMTBCDField18: TFMTBCDField; FMTBCDField19: TFMTBCDField; FMTBCDField20: TFMTBCDField; IntegerField23: TIntegerField; StringField13: TStringField; StringField14: TStringField; StringField15: TStringField; StringField16: TStringField; StringField17: TStringField; IntegerField24: TIntegerField; IntegerField25: TIntegerField; SmallintField1: TSmallintField; SmallintField2: TSmallintField; StringField18: TStringField; StringField19: TStringField; StringField20: TStringField; StringField21: TStringField; StringField22: TStringField; IntegerField26: TIntegerField; sdsRelatInadimplencia: TSQLDataSet; dsRelatInadimplencia: TDataSetProvider; cdsRelatInadimplente: TClientDataSet; cdsRelatInadimplenteASS_ID: TIntegerField; cdsRelatInadimplenteREGISTRO: TStringField; cdsRelatInadimplenteNOME: TStringField; cdsRelatInadimplenteEMP_ID: TIntegerField; cdsRelatInadimplenteREGIAO: TStringField; cdsRelatInadimplenteCPFCNPJ: TStringField; cdsRelatInadimplenteTIPOCONTRIB: TStringField; cdsRelatInadimplenteTPCONTRIB_ID: TIntegerField; cdsRelatInadimplenteEND_ID: TIntegerField; cdsRelatInadimplenteEND_LOGRADOURO: TStringField; cdsRelatInadimplenteEND_NUMERO: TStringField; cdsRelatInadimplenteEND_COMPLEMENTO: TStringField; cdsRelatInadimplenteEND_BAIRRO: TStringField; cdsRelatInadimplenteEND_CEP: TStringField; cdsRelatInadimplenteCIDADE_ID: TIntegerField; cdsRelatInadimplenteTP_ENDER_ID: TIntegerField; cdsRelatInadimplenteEND_CORRESP: TSmallintField; cdsRelatInadimplenteEND_CORRESP_DEV: TSmallintField; cdsRelatInadimplenteSTATUSCORRESP: TStringField; cdsRelatInadimplenteCIDADE_NOME: TStringField; cdsRelatInadimplenteESTADO_NOME: TStringField; cdsRelatInadimplenteTP_ENDER_DESCR: TStringField; cdsRelatInadimplenteENDER_COMPLETO: TStringField; cdsRelatInadimplenteTP_ASSOC_ID: TIntegerField; cdsRelatInadimplenteANOPAGO: TIntegerField; cdsRelatInadimplenteTIPOPESSOADESCR: TStringField; cdsRelatParcelsPARCEL_ID: TIntegerField; cdsRelatInadimplenteTELS: TStringField; cdsRelatInadimplenteEMAIL: TStringField; cdsRelatParcelsTELS: TStringField; PROC_ACERTAIBLGERAL: TSQLStoredProc; sdsContribsRecibo: TSQLDataSet; dspContribsRecibo: TDataSetProvider; cdsContribsRecibo: TClientDataSet; dsContribsRecibo: TDataSource; cdsContribsReciboANUID_ID: TIntegerField; cdsContribsReciboDESCRICAO: TStringField; cdsContribsReciboDESCRTIPO: TStringField; cdsContribsReciboANO: TIntegerField; cdsContribsReciboVALOR: TFMTBCDField; cdsContribsReciboVENCIMENTO: TDateField; cdsContribsReciboTIPOCONTRIB: TStringField; cdsContribsReciboPARC_ID: TIntegerField; cdsContribsReciboNUM_PARCELA: TIntegerField; cdsContribsReciboTPCONTRIB_ID: TIntegerField; cdsContribsReciboMULTA: TFMTBCDField; cdsContribsReciboJUROS: TFMTBCDField; cdsContribsReciboCORRECAO: TFMTBCDField; cdsContribsReciboTOTAL: TFMTBCDField; PROC_BOLETO_PAGAR_MANUAL: TSQLStoredProc; sdsMovPeriodo: TSQLDataSet; dspMovPeriodo: TDataSetProvider; cdsMovPeriodo: TClientDataSet; dsMovPeriodo: TDataSource; cdsMovPeriodoNOME: TStringField; cdsMovPeriodoREGISTRO: TStringField; cdsMovPeriodoCPFCNPJ: TStringField; cdsMovPeriodoREGIAO: TStringField; cdsMovPeriodoDT_VENCIMENTO: TDateField; cdsMovPeriodoSITUACAO: TStringField; cdsMovPeriodoVALOR_TOTAL: TFMTBCDField; cdsMovPeriodoNOSSONUMERO: TStringField; cdsMovPeriodoDT_RECEBIMENTO: TDateField; cdsMovPeriodoVALOR_RECEBIMENTO: TFMTBCDField; cdsMovPeriodoFORMA_PAGTO: TStringField; cdsMovPeriodoITENS: TStringField; cdsPagtosTIPOBOLETO: TIntegerField; cdsRelatParcelsEMAIL: TStringField; cdsRelatInadimplenteSEXO: TStringField; cdsRelatParcelsRECCREDITO: TStringField; sdsRelatParcelsNovo: TSQLDataSet; cdsRelatParcelsPARCELSATRASO: TIntegerField; cdsRelatParcelsVALORTOTALATRASO: TFMTBCDField; cdsRelatParcelsVENCPRIMPARCEL: TDateField; procedure cdsPagtosAfterScroll(DataSet: TDataSet); procedure cdsParcelamentoAfterScroll(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var DmFinancas: TDmFinancas; implementation uses UDMConexao; {$R *.dfm} procedure TDmFinancas.cdsPagtosAfterScroll(DataSet: TDataSet); begin cdspagtosItens.close; cdspagtosItens.Params.ParamByName('bol_id').value:= cdsPagtosBOL_ID.value; cdspagtosItens.open; end; procedure TDmFinancas.cdsParcelamentoAfterScroll(DataSet: TDataSet); begin iF DmFinancas.cdsParcelamento.RECORDCOUNT > 0 THEN BEGIN DmFinancas.cdsParcelasParc.Close; DmFinancas.cdsParcelasParc.Params.ParamByName('p_id').value := DmFinancas.cdsParcelamentoPARCEL_ID.value; DmFinancas.cdsParcelasParc.Open; //Anuidades Parceladas Dmfinancas.cdsParcelAnuidades.close; Dmfinancas.cdsParcelAnuidades.Params.ParamByName('parcel_id').value := DmFinancas.cdsParcelamentoPARCEL_ID.value; Dmfinancas.cdsParcelAnuidades.Open; END; end; end.
unit TXAN.Types; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses SysUtils, Types, JPL.Strings; type TFileStats = record FileSize: Int64; Lines: integer; BlankLines: integer; NotBlankLines: integer; procedure Clear; end; TTotalStats = record Files: integer; TotalSize: Int64; Lines: integer; BlankLines: integer; NotBlankLines: integer; procedure Clear; procedure AddFileStats(const fs: TFileStats; const IncFilesCount: Boolean = True); end; TAppParams = record FileMasks: TStringDynArray; IgnoreFileSymLinks: Boolean; IgnoreDirSymLinks: Boolean; RecursionDepth: Byte; Silent: Boolean; ShowSummary: Boolean; ElapsedTimeStr: string; end; implementation { TTotalStats } procedure TTotalStats.Clear; begin Files := 0; Lines := 0; BlankLines := 0; NotBlankLines := 0; end; procedure TTotalStats.AddFileStats(const fs: TFileStats; const IncFilesCount: Boolean); begin if IncFilesCount then Inc(Files); TotalSize += fs.FileSize; Lines += fs.Lines; BlankLines += fs.BlankLines; NotBlankLines += fs.NotBlankLines; end; { TFileStats } procedure TFileStats.Clear; begin FileSize := 0; Lines := 0; BlankLines := 0; NotBlankLines := 0; end; end.
{$rangeChecks on} {* 中国象棋 * 运行于Terminal下 * 操作方式兼容vi * 需要安装象棋字形: https://www.babelstone.co.uk/Fonts/Xiangqi.html * 建议使用kitty - 一个基于GPU的快速, 多功能终端模拟器(https://sw.kovidgoyal.net/kitty/)来运行。 *} program chess; uses crt, dos, SysUtils; {* 棋盘 棋盘是一个9x10的方格,横线为线,纵线为路,共有10线9路 线路交叉点为棋子点位 *} type TRoad = 1..9; TRank = 1..10; {* 绘制棋盘 绘制棋盘需要绘制棋子的点位,即路和线的交叉点 *} const space = 3; point = '+'; {* 计算棋盘边距 *} function Margin : byte; begin Margin := ( screenwidth - space * high(TRoad) + 1) div 2; end; procedure DrawBoard; var i: TRank; j: TRoad; begin clrscr; for i := low(TRank) to high(TRank) do begin gotoXY(Margin - space, i); writeln(11 - i:2); for j := low(TRoad) to high(TRoad) do begin gotoXY(j * space - space + Margin, i); writeln(point); end; end; for j := low(TRoad) to high(TRoad) do begin gotoXY(j * space - space + Margin, 11); writeln(10 - j); end; end; {* 棋子 棋子分为两方: 红子、黑子 棋子的名称有:帅、士、相、马、车、炮、兵 *} type TSide = (Red, Black); TName = (General, Advisor, Elephant, Horse, Chariot, Cannon, Soldier); {* 棋面 棋面按红方和黑方,及其名字进行确定 *} const faces: Array [TSide, TName] of String = (('🩠', '🩡', '🩢', '🩣', '🩤', '🩥', '🩦'), ('🩧', '🩨', '🩩', '🩪', '🩫', '🩬', '🩭')); {* 棋子 棋子根据红黑方, 名字,以及它在棋盘上的位置互相区别 每个棋子有一个selected值,表示它是否属于选中状态 每个棋子还有一个blink属性,表示它是否属于闪烁状态 每个棋子包括一个next指针,这样可以把所有棋子连起来 *} type TPiece = Record side: TSide; name: TName; rank: TRank; road: TRoad; selected: Boolean; blink: Boolean; next: ^TPiece; end; { 显示棋子 } procedure ShowPiece(p: TPiece); begin gotoXY(p.road * space - space + Margin, p.rank); writeln(faces[p.side][p.name]); end; {* 棋局 一局棋就是一组棋子 在行棋的过程中,棋子会由于被对方吃掉而减少 *} type TRound = ^TPiece; var round: TRound = nil; { 显示某个位置的棋子 } procedure ShowPieceXY(rank: TRank; road: TRoad); var p: ^TPiece = nil; begin p := round; while p <> nil do begin if (p^.rank = rank) and (p^.road = road) then begin gotoXY(road * space - space + Margin, rank); writeln(faces[p^.side][p^.name]); break; end; p := p^.next; end; if p = nil then begin gotoXY(road * space - space + Margin, rank); writeln(point); end; end; { 增加一个棋子 } procedure AddPiece(side: TSide; name: TName; rank: TRank; road: TRoad); var p: ^TPiece; begin new(p); p^.side := side; p^.name := name; p^.rank := rank; p^.road := road; p^.selected := false; p^.blink := false; p^.next := round; round := p; end; { 删除一个棋子 } procedure DelPiece(p: TRound); var q: ^TPiece; begin if p = round then begin round := round^.next; dispose(p); end else begin q := round; while q^.next <> p do q := q^.next; q^.next := q^.next^.next; dispose(p); end; end; procedure ClearPiece; begin while round <> nil do DelPiece(round); end; { 移动棋子 } procedure MovePiece(p: TRound; i: TRank; j: TRoad); var q: TPiece; begin q := p^; p^.rank := i; p^.road := j; ShowPieceXY(q.rank, q.road); end; {* 摆棋 摆棋的过程就是把一局棋所需要的32颗棋子依次摆放到各自固定的位置上,先后顺序无关 *} procedure ResetRound; var p: ^TPiece; begin if round <> nil then ClearPiece; AddPiece(Red, Chariot, 1, 1); AddPiece(Red, Horse, 1, 2); AddPiece(Red, Elephant, 1, 3); AddPiece(Red, Advisor, 1, 4); AddPiece(Red, General, 1, 5); AddPiece(Red, Advisor, 1, 6); AddPiece(Red, Elephant, 1, 7); AddPiece(Red, Horse, 1, 8); AddPiece(Red, Chariot, 1, 9); AddPiece(Red, Cannon, 3, 2); AddPiece(Red, Cannon, 3, 8); AddPiece(Red, Soldier, 4, 1); AddPiece(Red, Soldier, 4, 3); AddPiece(Red, Soldier, 4, 5); AddPiece(Red, Soldier, 4, 7); AddPiece(Red, Soldier, 4, 9); AddPiece(Black, Chariot, 10, 1); AddPiece(Black, Horse, 10, 2); AddPiece(Black, Elephant, 10, 3); AddPiece(Black, Advisor, 10, 4); AddPiece(Black, General, 10, 5); AddPiece(Black, Advisor, 10, 6); AddPiece(Black, Elephant, 10, 7); AddPiece(Black, Horse, 10, 8); AddPiece(Black, Chariot, 10, 9); AddPiece(Black, Cannon, 8, 2); AddPiece(Black, Cannon, 8, 8); AddPiece(Black, Soldier, 7, 1); AddPiece(Black, Soldier, 7, 3); AddPiece(Black, Soldier, 7, 5); AddPiece(Black, Soldier, 7, 7); AddPiece(Black, Soldier, 7, 9); p := round; while p <> nil do begin ShowPiece(p^); p := p^.next; end; end; { 当前行棋方,以及选择移动的棋子 } var curside: TSide = Red; curpiece: ^TPiece = nil; { 改变行棋方 } procedure ChangeSide; begin if curside = Red then curside := Black else curside := Red; end; {* 闪烁棋子 闪烁棋子的原理是通过重复的调用,根据时间来刷新blink为true的棋子的显示状态。 *} procedure BlinkPiece; procedure Blink(enable: Boolean); var p: ^TPiece; begin p := round; while p <> nil do begin if p^.blink then begin gotoXY(p^.road * space - space + Margin, p^.rank); if enable then writeln(point) else writeln(faces[p^.side][p^.name]); end; p := p^.next; end; end; { Blink } var sec, sec100, min, hour: word; begin getTime(hour, min, sec, sec100); Blink(sec100 > 50); end; {*行棋 行棋就是移动一颗棋子到另一个位置,如果该位置有对方的棋子,则对方的棋子就被吃掉 如果对方的General棋子被吃掉,则行棋方赢棋 名字不同的棋子,其行棋规则也不相同,包括: 车: 1. 下一个位置和当前位置相隔若干条线,或者若干条路 2. 下一个位置和当前位置之间不能有其它棋子 马: 1. 下一个位置和当前位置相隔一条线、两条路,或者一条路、两条线 2. 下一个位置和当前位置之间相隔一的相邻位置不能有其它棋子 象/相: 1. 下一个位置和当前位置相隔两条线、两条路 2. 相隔一条线、一条路的位置不能有棋子 士: 1. 下一个位置和当前位置相隔一条线、一条路 2. 下一个位置不能超出九宫格的范围 将: 1. 下一个位置和当前位置相隔一条线,或者一条路 2. 同士2 炮: 1. 同车1 2. 下一个位置和当前位置中间有且只能有一个棋子 兵: 1. 同将1 2. 当前位置的线小于6时,下一个位置的线必须大于当前位置的线 3. 当前位置的线大于5时,下一个位置的线不得小于当前位置的线 *} begin DrawBoard; ResetRound; gotoXY(1, ScreenHeight - 1); end.
type pos = record x,y:integer; end; node = record p: pos; next: ^node; end; queue = record head: ^node; tail: ^node; end; maze:array of array of boolean; //queues procedure init(var q: queue); begin q.head := nil; q.tail := nil; end; procedure enqueue(var q: queue; p: pos); var n: ^node; begin new(n); n^.p := p; n^.next := nil; if q.head = nil then begin q.head := n; q.tail := n; end else begin q.tail^.next := n; // append to tail q.tail := n; end; end; function dequeue(var q: queue): pos; var p: ^node; begin dequeue := q.head^.p; p := q.head; q.head := q.head^.next; dispose(p); if q.head = nil then q.tail := nil; end; function isEmpty(q: queue): boolean; begin exit(q.head = nil); end; procedure path(const m:maze); const dx:array[1,4] of integer=(1,-1,0,0); dy:array[1,4] of integer=(0,0,-1,1); var g:array of array of char; dir:integer; width,height:integer; q:queue; p:pos; visited:array of array of boolean; parent:array of array of pos; function valid(x,y:integer):boolean; begin exit((x>=0) and (x<width) and (y>=0) and (y<height)); end; begin init(q); width:=length(m); height:=length(m[0]); setLength(visited, width, height); setLength(parent, width,height); enqueue(q,0,0); visited[0][0]:=true; while not isEmpty(q) do begin p:=dequeue(q); if (x=width-1) and (y=height-1) then break; for dir:=1 to 4 do begin x1:=x+dx[dir]; y1:=y+dy[dir]; if valid(x1, y1) and (not visited[x1][y1]) and (not m[x1][y1]) do begin enqueue(q,x1,y1); visited[x1][y1]:=true; parent[x1][y1].x:=x; parent[x1][y1].y:=y; end; end; end; setLength(g,width, height); for x:=0 to width-1 do begin for y:=0 to height-1 do begin if m[x,y] then g[x,y]:='#'; else g[x,y]:=' '; end; end; x:=width-1; y:=height-1; while x<>0 or y<>0 do begin g[x,y]:='.'; p:=parent[x,y]; x:=p.x; y:=p.y; end; end;
{******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Agência Bancária 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> @author T2Ti @version 2.0 *******************************************************************************} unit UAgenciaBanco; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, AgenciaBancoVO, AgenciaBancoController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, JvBaseEdits, Controller; type [TFormDescription(TConstantes.MODULO_CADASTROS, 'Agência Bancária')] TFAgenciaBanco = class(TFTelaCadastro) EditCodigo: TLabeledEdit; EditBanco: TLabeledEdit; EditNome: TLabeledEdit; EditLogradouro: TLabeledEdit; EditNumero: TLabeledEdit; EditBairro: TLabeledEdit; EditMunicipio: TLabeledEdit; EditUf: TLabeledEdit; EditGerente: TLabeledEdit; EditContato: TLabeledEdit; EditCEP: TLabeledMaskEdit; EditTelefone: TLabeledMaskEdit; BevelEdits: TBevel; MemoObservacao: TLabeledMemo; EditIdBanco: TLabeledCalcEdit; procedure FormCreate(Sender: TObject); procedure EditIdBancoKeyUp(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 FAgenciaBanco: TFAgenciaBanco; implementation uses ULookup, BancoController, BancoVO, Biblioteca; {$R *.dfm} {$REGION 'Infra'} procedure TFAgenciaBanco.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TAgenciaBancoVO; ObjetoController := TAgenciaBancoController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFAgenciaBanco.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditCodigo.SetFocus; end; end; function TFAgenciaBanco.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditCodigo.SetFocus; end; end; function TFAgenciaBanco.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('AgenciaBancoController.TAgenciaBancoController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('AgenciaBancoController.TAgenciaBancoController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFAgenciaBanco.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TAgenciaBancoVO.Create; TAgenciaBancoVO(ObjetoVO).Codigo := EditCodigo.Text; TAgenciaBancoVO(ObjetoVO).IdBanco := StrToInt(EditIdBanco.Text); TAgenciaBancoVO(ObjetoVO).BancoNome := EditBanco.Text; TAgenciaBancoVO(ObjetoVO).Nome := EditNome.Text; TAgenciaBancoVO(ObjetoVO).Logradouro := EditLogradouro.Text; TAgenciaBancoVO(ObjetoVO).Numero := EditNumero.Text; TAgenciaBancoVO(ObjetoVO).Bairro := EditBairro.Text; TAgenciaBancoVO(ObjetoVO).Cep := EditCEP.Text; TAgenciaBancoVO(ObjetoVO).Municipio := EditMunicipio.Text; TAgenciaBancoVO(ObjetoVO).Uf := EditUf.Text; TAgenciaBancoVO(ObjetoVO).Telefone := EditTelefone.Text; TAgenciaBancoVO(ObjetoVO).Contato := EditContato.Text; TAgenciaBancoVO(ObjetoVO).Gerente := EditGerente.Text; TAgenciaBancoVO(ObjetoVO).Observacao := MemoObservacao.Text; if StatusTela = stInserindo then begin TController.ExecutarMetodo('AgenciaBancoController.TAgenciaBancoController', 'Insere', [TAgenciaBancoVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TAgenciaBancoVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('AgenciaBancoController.TAgenciaBancoController', 'Altera', [TAgenciaBancoVO(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 'Controles de Grid'} procedure TFAgenciaBanco.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TAgenciaBancoVO(TController.BuscarObjeto('AgenciaBancoController.TAgenciaBancoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditCodigo.Text := TAgenciaBancoVO(ObjetoVO).Codigo; EditIdBanco.Text := IntToStr(TAgenciaBancoVO(ObjetoVO).IdBanco); EditBanco.Text := TAgenciaBancoVO(ObjetoVO).BancoNome; EditNome.Text := TAgenciaBancoVO(ObjetoVO).Nome; EditLogradouro.Text := TAgenciaBancoVO(ObjetoVO).Logradouro; EditNumero.Text := TAgenciaBancoVO(ObjetoVO).Numero; EditBairro.Text := TAgenciaBancoVO(ObjetoVO).Bairro; EditCEP.Text := TAgenciaBancoVO(ObjetoVO).Cep; EditMunicipio.Text := TAgenciaBancoVO(ObjetoVO).Municipio; EditUf.Text := TAgenciaBancoVO(ObjetoVO).Uf; EditTelefone.Text := TAgenciaBancoVO(ObjetoVO).Telefone; EditContato.Text := TAgenciaBancoVO(ObjetoVO).Contato; EditGerente.Text := TAgenciaBancoVO(ObjetoVO).Gerente; MemoObservacao.Text := TAgenciaBancoVO(ObjetoVO).Observacao; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFAgenciaBanco.EditIdBancoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdBanco.Value <> 0 then Filtro := 'ID = ' + EditIdBanco.Text else Filtro := 'ID=0'; try EditIdBanco.Clear; EditBanco.Clear; if not PopulaCamposTransientes(Filtro, TBancoVO, TBancoController) then PopulaCamposTransientesLookup(TBancoVO, TBancoController); if CDSTransiente.RecordCount > 0 then begin EditIdBanco.Text := CDSTransiente.FieldByName('ID').AsString; EditBanco.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdBanco.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
unit KInfoDictionaryFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, KDictionaryFrame, BaseGUI, UniButtonsFrame, ExtCtrls, ActnList, Buttons, ImgList, ComCtrls, ToolWin, CoreDescription, Menus; type TfrmInfoDictionary = class; TInfoDictGUIAdapter = class(TGUIAdapter) private function GetActiveDict: TDictionary; function GetFrameOwner: TfrmInfoDictionary; public property FrameOwner: TfrmInfoDictionary read GetFrameOwner; property ActiveDict: TDictionary read GetActiveDict; procedure Clear; override; function Save: integer; override; procedure Reload; override; function StartFind: integer; override; constructor Create(AOwner: TComponent); override; end; TfrmInfoDictionary = class(TFrame, IGUIAdapter) GroupBox3: TGroupBox; frmBtns: TfrmButtons; GroupBox2: TGroupBox; fdlg: TFontDialog; actnList: TActionList; actnFont: TAction; actnColor: TAction; imgList: TImageList; cldlg: TColorDialog; ToolBar1: TToolBar; ToolButton1: TToolButton; GroupBox4: TGroupBox; edtName: TEdit; actnAddRoot: TAction; lstAllValues: TListView; pm: TPopupMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; ActnLst: TActionList; actnSetTrueWord: TAction; lstAllWords: TListBox; procedure edtNameChange(Sender: TObject); procedure frmBtnsactnAddExecute(Sender: TObject); procedure frmBtnsactnDeleteExecute(Sender: TObject); procedure clbxChange(Sender: TObject); procedure actnFontExecute(Sender: TObject); procedure actnColorExecute(Sender: TObject); procedure frmBtnsactnEditExecute(Sender: TObject); procedure lstAllRootsClick(Sender: TObject); procedure lstAllRootsDblClick(Sender: TObject); procedure lstAllRootsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure lstAllValuesCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure lstAllValuesDblClick(Sender: TObject); procedure actnSetTrueWordExecute(Sender: TObject); private FActiveDict: TDictionary; FActiveRoot: TRoot; FActiveWord: TDictionaryWord; FInfoDictGUIAdapter: TInfoDictGUIAdapter; procedure SetActiveDict(const Value: TDictionary); function GetActiveRoot: TRoot; function GetActiveWord: TDictionaryWord; public property ActiveDict: TDictionary read FActiveDict write SetActiveDict; property ActiveRoot: TRoot read GetActiveRoot; property ActiveWord: TDictionaryWord read GetActiveWord; property GUIAdapter: TInfoDictGUIAdapter read FInfoDictGUIAdapter implements IGUIAdapter; procedure AddWord(AObject: TDictionaryWord); procedure SetActiveElements(AValue: boolean); constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses KAddWord, Facade, KCommonFunctions, BaseFacades, Math; {$R *.dfm} { TfrmInfoDictionary } constructor TfrmInfoDictionary.Create(AOwner: TComponent); begin inherited; FInfoDictGUIAdapter := TInfoDictGUIAdapter.Create(Self); frmBtns.GUIAdapter := FInfoDictGUIAdapter; lstAllValues.Column[0].Width := 0; lstAllValues.Column[4].Width := 0; end; destructor TfrmInfoDictionary.Destroy; begin FInfoDictGUIAdapter.Free; inherited; end; procedure TfrmInfoDictionary.SetActiveDict(const Value: TDictionary); begin GUIAdapter.BeforeReload; if FActiveDict <> Value then begin FActiveDict := Value; GUIAdapter.Reload; end; if not Assigned(FActiveDict) then GUIAdapter.Clear; end; procedure TfrmInfoDictionary.AddWord(AObject: TDictionaryWord); begin frmAddWord := TfrmAddWord.Create(Self); frmAddWord.ActiveDict := ActiveDict; if Assigned (AObject) then frmAddWord.ActiveWord := AObject else if Assigned (frmAddWord.ActiveWord) then frmAddWord.ActiveWord := nil; frmAddWord.Reload; if frmAddWord.ShowModal = mrOk then begin FActiveDict.Roots.MakeList(lstAllWords.Items); FActiveDict.Roots.MakeList(lstAllValues.Items, true, true); FActiveWord := frmAddWord.ActiveWord; lstAllWords.Selected[lstAllWords.Count - 1] := true; end; GUIAdapter.Reload; frmAddWord.Free; end; procedure TfrmInfoDictionary.SetActiveElements(AValue: boolean); begin edtName.ReadOnly := not AValue; frmBtns.Enabled := AValue; frmBtns.actnSave.Enabled := AValue; frmBtns.actnAdd.Enabled := AValue; frmBtns.actnEdit.Enabled := AValue; frmBtns.actnAutoSave.Enabled := AValue; frmBtns.actnDelete.Enabled := AValue; frmBtns.actnClear.Enabled := AValue; frmBtns.actnReload.Enabled := AValue; frmBtns.actnSelectAll.Enabled := AValue; frmBtns.actnAddGroup.Enabled := AValue; end; function TfrmInfoDictionary.GetActiveRoot: TRoot; begin Result := nil; if ActiveDict.Name <> 'Литология (нередактируемый справочник)' then Result := ActiveDict.Roots.ItemsByID[StrToInt(lstAllValues.ItemFocused.SubItems[3])] as TRoot; end; function TfrmInfoDictionary.GetActiveWord: TDictionaryWord; begin Result := nil; if ActiveDict.Name <> 'Литология (нередактируемый справочник)' then begin try Result := ActiveRoot.Words.ItemsByID[StrToInt(lstAllValues.ItemFocused.Caption)] as TDictionaryWord; except end end else Result := (TMainFacade.GetInstance as TMainFacade).AllWords.GetItemByName(lstAllValues.ItemFocused.SubItems[1]) as TDictionaryWord; { if Assigned(Result) then begin //FActiveRoot := FActiveWord.Owner as TRoot; if ActiveWord.Correct then pm.Items[0].Visible := false else pm.Items[0].Visible := true end else pm.Items[0].Visible := true; } end; { TInfoDictGUIAdapter } procedure TInfoDictGUIAdapter.Clear; begin inherited; with FrameOwner do begin edtName.Clear; lstAllWords.Clear; lstAllValues.Clear; end; ChangeMade := false; end; constructor TInfoDictGUIAdapter.Create(AOwner: TComponent); begin inherited; Buttons := [abAutoSave, abSave, abReload, abAdd, abEdit, abDelete, abClear]; Self.SetAutoSave(false); end; function TInfoDictGUIAdapter.GetActiveDict: TDictionary; begin Result := FrameOwner.FActiveDict; end; function TInfoDictGUIAdapter.GetFrameOwner: TfrmInfoDictionary; begin Result := Owner as TfrmInfoDictionary; end; procedure TInfoDictGUIAdapter.Reload; var i: integer; begin if Assigned(ActiveDict) then with FrameOwner do begin edtName.Text := trim(ActiveDict.Name); for i := 0 to (TMainFacade.GetInstance as TMainFacade).Dicts.Count - 1 do begin try if Trim(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['ID' + IntToStr(i)]) <> '' then if StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['ID' + IntToStr(i)]) = FActiveDict.ID then begin FActiveDict.Font.Name := TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Name' + IntToStr(i)]; FActiveDict.Font.Charset := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['CharSet' + IntToStr(i)]); FActiveDict.Font.Color := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Color' + IntToStr(i)]); FActiveDict.Font.Size := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Size' + IntToStr(i)]); FActiveDict.Font.Style := TFontStyles(Byte(StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Style' + IntToStr(i)]))); lstAllWords.Font.Name := TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Name' + IntToStr(i)]; lstAllWords.Font.Charset := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['CharSet' + IntToStr(i)]); lstAllWords.Font.Color := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Color' + IntToStr(i)]); lstAllWords.Font.Size := StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Size' + IntToStr(i)]); lstAllWords.Font.Style := TFontStyles(Byte(StrToInt(TMainFacade.GetInstance.SystemSettings.SectionByName['Options'].SectionValues.Values['Style' + IntToStr(i)]))); end; except FActiveDict.Font.Name := (TMainFacade.GetInstance as TMainFacade).Font.Name; FActiveDict.Font.Charset := (TMainFacade.GetInstance as TMainFacade).Font.Charset; FActiveDict.Font.Color := (TMainFacade.GetInstance as TMainFacade).Font.Color; FActiveDict.Font.Size := (TMainFacade.GetInstance as TMainFacade).Font.Size; FActiveDict.Font.Style := (TMainFacade.GetInstance as TMainFacade).Font.Style; lstAllWords.Font.Name := (TMainFacade.GetInstance as TMainFacade).Font.Name; lstAllWords.Font.Charset := (TMainFacade.GetInstance as TMainFacade).Font.Charset; lstAllWords.Font.Color := (TMainFacade.GetInstance as TMainFacade).Font.Color; lstAllWords.Font.Size := (TMainFacade.GetInstance as TMainFacade).Font.Size; lstAllWords.Font.Style := (TMainFacade.GetInstance as TMainFacade).Font.Style; end; end; // добавить значения из справочника по литологии if ActiveDict.Name = 'Литология (нередактируемый справочник)' then ActiveDict.Roots.GetAddWords((TMainFacade.GetInstance as TMainFacade).AllRoots, (TMainFacade.GetInstance as TMainFacade).AllLithologies); ActiveDict.Roots.MakeList(lstAllValues.Items, true, true); end; inherited; end; function TInfoDictGUIAdapter.Save: integer; begin Result := 0; if Assigned(ActiveDict) then begin ActiveDict.Name := trim(FrameOwner.edtName.Text); ActiveDict.Font.Name := FrameOwner.lstAllWords.Font.Name; ActiveDict.Font.Charset := FrameOwner.lstAllWords.Font.Charset; ActiveDict.Font.Color := FrameOwner.lstAllWords.Font.Color; ActiveDict.Font.Size := FrameOwner.lstAllWords.Font.Size; ActiveDict.Font.Style := FrameOwner.lstAllWords.Font.Style; // коллекция со словами сохраняется сразу же, когда добавляется, // редактируется или удаляется слово Result := ActiveDict.Update; // сохранить настройки (TMainFacade.GetInstance as TMainFacade).Dicts.SaveFont((TMainFacade.GetInstance as TMainFacade).Dicts); //(TMainFacade.GetInstance as TMainFacade).SystemSettings.SaveToFile((TMainFacade.GetInstance as TMainFacade).SettingsFileName); ChangeMade := false; Reload; end else Clear; end; function TInfoDictGUIAdapter.StartFind: integer; begin Result := 0; end; procedure TfrmInfoDictionary.edtNameChange(Sender: TObject); begin GUIAdapter.ChangeMade := true; end; procedure TfrmInfoDictionary.frmBtnsactnAddExecute(Sender: TObject); begin if ActiveDict.Name <> 'Литология (нередактируемый справочник)' then begin frmBtns.actnAddExecute(Sender); AddWord(nil); end; end; procedure TfrmInfoDictionary.frmBtnsactnDeleteExecute(Sender: TObject); var ls: TListWords; Deleted: boolean; index: integer; begin if ActiveDict.Name <> 'Литология (нередактируемый справочник)' then begin //frmBtns.actnDeleteExecute(Sender); Deleted := false; // проверяем есть ли такое слово в каком-либо описании керна try ls := TListWords.Create; ls.Poster.GetFromDB('kern_value_id = ' + IntToStr(ActiveWord.id), ls); // проверяем используется это слово где-нить или нет if ls.Count = 0 then Deleted := true else if MessageBox(0, PChar('Слово встречается в одном/нескольких из описании керна. Продолжить?'), PChar('Предупреждение'), MB_YESNO + MB_ICONWARNING + MB_APPLMODAL) = ID_YES then Deleted := true; ls.Free; except Deleted := false; end; if Deleted then begin // по внешнему ключу все лишнее должно удалиться //index := (TMainFacade.GetInstance as TMainFacade).AllWords.IndexOf(ActiveWord); //(TMainFacade.GetInstance as TMainFacade).AllWords.OwnsObjects := false; //ActiveWord.Collection.OwnsObjects := false; //(TMainFacade.GetInstance as TMainFacade).AllWords.Delete(index); //ActiveRoot.Words.Free; //ActiveWord.Collection.OwnsObjects := true; //ActiveRoot.Words.Update(ActiveRoot.Words); ActiveRoot.Words.Remove(ActiveWord); GUIAdapter.Reload; end; end; end; procedure TfrmInfoDictionary.clbxChange(Sender: TObject); begin GUIAdapter.ChangeMade := true; end; procedure TfrmInfoDictionary.actnFontExecute(Sender: TObject); begin fdlg.Font := ActiveDict.Font; if fdlg.Execute then begin lstAllWords.Font := fdlg.Font; GUIAdapter.ChangeMade := true; GUIAdapter.Save; end; end; procedure TfrmInfoDictionary.actnColorExecute(Sender: TObject); begin if cldlg.Execute then lstAllWords.Font.Color := cldlg.Color; end; procedure TfrmInfoDictionary.frmBtnsactnEditExecute(Sender: TObject); begin if ActiveDict.Name <> 'Литология (нередактируемый справочник)' then begin frmBtns.actnEditExecute(Sender); AddWord(ActiveWord); end; end; procedure TfrmInfoDictionary.lstAllRootsClick(Sender: TObject); begin if (lstAllWords.ItemIndex >= 0) and (lstAllWords.Count > 0) then FActiveWord := lstAllWords.Items.Objects[lstAllWords.ItemIndex] as TDictionaryWord; end; procedure TfrmInfoDictionary.lstAllRootsDblClick(Sender: TObject); begin frmBtnsactnEditExecute(Sender); end; procedure TfrmInfoDictionary.lstAllRootsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Color: TColor; ABrush: TBrush; begin ABrush := TBrush.Create; with (Control as TListBox).Canvas do begin Color := ActiveDict.Font.Color; ABrush.Style := TBrushStyle(ActiveDict.Font.Style); ABrush.Color := Color; Windows.FillRect(handle, Rect, ABrush.Handle); Brush.Style := bsClear; TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]); ABrush.Free; end; end; procedure TfrmInfoDictionary.lstAllValuesCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); var r: TRect; begin r := Item.DisplayRect(drBounds); if Item.Index mod 2 = 0 then begin lstAllValues.Canvas.Brush.Color := $00EFEFEF; lstAllValues.Canvas.FillRect(r); end else begin lstAllValues.Canvas.Brush.Color := $00FFFFFF; lstAllValues.Canvas.FillRect(r); end; //if Assigned(FActiveRoot.Words.ItemsByID[StrToInt(Item.Caption)] as TDictionaryWord) then //if not (FActiveRoot.Words.ItemsByID[StrToInt(Item.Caption)] as TDictionaryWord).Correct then //begin // lstAllValues.Canvas.Brush.Color := clRed; // lstAllValues.Canvas.FillRect(r); //end; lstAllValues.Canvas.Font.Color := FActiveDict.Font.Color; lstAllValues.Canvas.Font.Style := FActiveDict.Font.Style; lstAllValues.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption); end; procedure TfrmInfoDictionary.lstAllValuesDblClick(Sender: TObject); begin if (lstAllValues.ItemIndex > -1) and (ActiveDict.Name <> 'Литология (нередактируемый справочник)') then frmBtns.actnEdit.Execute; end; procedure TfrmInfoDictionary.actnSetTrueWordExecute(Sender: TObject); begin ActiveWord.Correct := true; end; end.
unit tMSql; interface Uses tSQLCls,DBTables,Classes,Forms,DB,SysUtils; const sqlSuccess=0; sqlDBOpen=1; Type TMicrosoftSQL=class(TSQL) public constructor Create(dsn,uid,pwd:string); {Virtual Functions} function Connect(uid,pwd:string):integer; override; function CurrentDate:String;override; function CurrentDateTime:String;override; function CurrentUser:String;override; function TableKeyword(FieldName:string):string;override; function DatePart(fn:string):string;override; function ConvertToDate(fn:string):string;override; function ConvertToDateTime(fn:string):string;override; function TimePart(fn:string):string;override; function CharStr(fn:string):string;override; function UpperCase(fn:string):string;override; function SortLongString(fn:string):string;override; function UserID(uid:string):longint;override; function CreateUser(uid,pwd:string):longint;override; function ChangePassword(uid,pwd:string):integer; override; function DropUser(uid:string):integer;override; function GrantRole(uid,group:string):integer;override; function RevokeRole(uid,group:string):integer;override; procedure MultiString(sl:TStrings; p:PChar);override; function RunFunction(FunName,Params,Alias:string):TQuery; override; function RunFunctionEx(FunName:TSQLString;Params:TStrings):TQuery; override; function ConnectCount:longint; override; function LockRecord(Table,Field,Value,Condition:string):integer; override; procedure SplitText(sl:TStrings; p:Pchar; sep:string); override; end; implementation Uses lblmemo; constructor TMicrosoftSQL.Create(dsn,uid,pwd:string); begin inherited Create(dsn,uid,pwd); PrefixTable:='DBA.'; DualTable:='DBA.DUAL' end; function TMicrosoftSQL.CurrentDate:String; begin CurrentDate:='GETDATE()' end; function TMicrosoftSQL.CurrentDateTime:String; begin CurrentDateTime:='GETDATE()' end; function TMicrosoftSQL.CurrentUser:String; {Возвращает текущего пользователя } begin CurrentUser:='USER_NAME()' end; function TMicrosoftSQL.TableKeyword(FieldName:string):string; begin TableKeyword:=SYSUTILS.UpperCase(FieldName) end; function TMicrosoftSQL.DatePart(fn:string):string; {Возвращает от типа DATE часть, содержащую дату} begin DatePart:=fn end; function TMicrosoftSQL.ConvertToDate(fn:string):string; begin ConvertToDate:=fn {'CONVERT(DATETIME,'+fn+',102)'} end; function TMicrosoftSQL.ConvertToDateTime(fn:string):string; begin ConvertToDateTime:=ConvertToDate(fn); end; function TMicrosoftSQL.TimePart(fn:string):string; {Возвращает от типа DATE часть, содержащую время} begin TimePart:=fn end; function TMicrosoftSQL.CharStr(fn:string):string; {Возвращает значение типа CHAR целого цисла : x=CHR(67)-> x='D'} begin CharStr:='CHAR('+fn+')' end; function TMicrosoftSQL.UpperCase(fn:string):string; begin UpperCase:='UPPER('+fn+')' end; function TMicrosoftSQL.SortLongString(fn:string):string; begin SortLongString:=fn; end; function TMicrosoftSQL.UserID(uid:string):longint; begin UserID:=1; end; function TMicrosoftSQL.CreateUser(uid,pwd:string):longint; var s:string; begin s:='sp_addlogin '+uid; if pwd<>'' then s:=s+','+pwd; ExecOneSQL(s); if ExecOneSQL('sp_adduser '+uid+','+uid)=0 then CreateUser:=UserID(uid) else CreateUser:=-1 end; function TMicrosoftSQL.DropUser(uid:string):integer; begin DropUser:=ExecOneSQL('sp_dropuser '+uid); ExecOneSQL('sp_droplogin '+uid); end; function TMicrosoftSQL.GrantRole(uid,group:string):integer; begin GrantRole:=sql.ExecOneSQL('sp_changegroup '+group+','+uid) end; function TMicrosoftSQL.RevokeRole(uid,group:string):integer; begin RevokeRole:=GrantRole(uid,'public'); end; procedure TMicrosoftSQL.MultiString(sl:TStrings; p:PChar); //var i:integer; begin if p=NIL then sl.Add('NULL') else if p[0]=#0 then sl.Add('''''') else SplitText(sl,p,'+'); end; procedure TMicrosoftSQL.SplitText(sl:TStrings; p:Pchar; sep:string); var i,l,t:integer; s:string; begin l:=StrLen(p); s:=''; t:=0; i:=0; while ((i<l) and (i<250)) do begin { if (p[i]=#13) and (p[i]=#10) then begin s:=s+'\x1310\'; i:=i+2; end else begin} s:=s+p[i]; i:=i+1; { end;} end; sl.Add(MakeStr(s)); end; function TMicrosoftSQL.RunFunction(FunName,Params,Alias:string):TQuery; var sl:TStringList; begin sl:=TStringList.Create; sl.Add(Params); RunFunction:=RunFunctionEx(SYSUTILS.UpperCase(FunName),sl); sl.Free end; function TMicrosoftSQL.RunFunctionEx(FunName:TSQLString;Params:TStrings):TQuery; var //q:TQuery; sl:TStringList; begin sl:=TStringList.Create; sl.Add('BEGIN DECLARE @@tmpVar INT; EXEC '+AddPrefix(FunName)); sl.AddStrings(Params); sl.Add(',@@tmpVar OUTPUT; SELECT @@tmpVar TempVar; END;'); RunFunctionEx:=CreateQuery(sl); sl.Free; end; function TMicrosoftSQL.ConnectCount:longint; begin ConnectCount:=0 end; function TMicrosoftSQL.LockRecord(Table,Field,Value,Condition:string):integer; begin LockRecord:=0; end; function TMicrosoftSQL.ChangePassword(uid,pwd:string):integer; var s:string; begin s:='sp_password '; if LoginPassword='' then s:=s+'NULL' else s:=s+'"'+LoginPassword+'"'; if pwd='' then pwd:='NULL' else pwd:='"'+pwd+'"'; s:=s+','+pwd; ChangePassword:=sql.ExecOneSQL(s) end; function TMicrosoftSQL.Connect(uid,pwd:string):integer; var res:integer; begin res:=inherited Connect(uid,pwd); if res=0 then ExecOneSQL('SET FORCEPLAN ON'); Connect:=res end; end.
unit UFormSelectReceive; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UMyUtil; type TfrmReceiveFile = class(TForm) Panel1: TPanel; Label1: TLabel; Label2: TLabel; Image5: TImage; Label3: TLabel; Label4: TLabel; Panel2: TPanel; btnRecevicePathBrowse: TButton; edtRecevicePath: TEdit; lbRecevicePath: TLabel; btnOK: TButton; btnCancel: TButton; lbFileName: TLabel; lbFileFrom: TLabel; lbFileSize: TLabel; lbIncludeFiles: TLabel; procedure btnRecevicePathBrowseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } public procedure SetFileInfo( FileName, FileFrom : string ); procedure SetFileSpace( FileSize : Int64; FileCount : Integer ); procedure SetReceivePath( ReceivePath : string ); public function getReceivePath : string; end; const FormTitle_ResetReceivePath : string = 'Select your receive path'; var frmReceiveFile: TfrmReceiveFile; implementation {$R *.dfm} { TfrmReceiveFile } procedure TfrmReceiveFile.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmReceiveFile.btnOKClick(Sender: TObject); begin Close; ModalResult := mrOk; end; procedure TfrmReceiveFile.btnRecevicePathBrowseClick(Sender: TObject); var ReceivePath : string; begin if MySelectFolderDialog.Select( FormTitle_ResetReceivePath, edtRecevicePath.Text, ReceivePath, Self.Handle ) then edtRecevicePath.Text := ReceivePath; end; procedure TfrmReceiveFile.FormShow(Sender: TObject); begin ModalResult := mrCancel; end; function TfrmReceiveFile.getReceivePath: string; begin Result := edtRecevicePath.Text; end; procedure TfrmReceiveFile.SetFileInfo(FileName, FileFrom: string); begin lbFileName.Caption := FileName; lbFileFrom.Caption := FileFrom; end; procedure TfrmReceiveFile.SetFileSpace(FileSize: Int64; FileCount: Integer); begin lbFileSize.Caption := MySize.getFileSizeStr( FileSize ); lbIncludeFiles.Caption := MyCount.getCountStr( FileCount ); end; procedure TfrmReceiveFile.SetReceivePath(ReceivePath: string); begin edtRecevicePath.Text := ReceivePath; end; end.
unit uJSON; { Catarinka Lua Library - JSON Object Copyright (c) 2013-2015 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface uses Classes, SysUtils, Lua, LuaObject, SuperObject, CatStrings, Variants, CatJSON; type TCatarinkaJSON = class(TLuaObject) private public obj: TCatJSON; function GetPropValue(propName: String): Variant; override; function SetPropValue(propName: String; const AValue: Variant) : Boolean; override; constructor Create(LuaState: PLua_State; AParent: TLuaObject = nil); overload; override; destructor Destroy; override; end; procedure RegisterCatarinkaJSON(L: PLua_State); implementation uses pLua; function method_settext(L: PLua_State): Integer; cdecl; var o: TCatarinkaJSON; begin o := TCatarinkaJSON(LuaToTLuaObject(L, 1)); o.obj.text := lua_tostring(L, 2); result := 1; end; function method_loadfromfile(L: PLua_State): Integer; cdecl; var o: TCatarinkaJSON; begin o := TCatarinkaJSON(LuaToTLuaObject(L, 1)); o.obj.LoadFromFile(lua_tostring(L, 2)); result := 1; end; function method_savetofile(L: PLua_State): Integer; cdecl; var o: TCatarinkaJSON; begin o := TCatarinkaJSON(LuaToTLuaObject(L, 1)); o.obj.SaveToFile(lua_tostring(L, 2)); result := 1; end; function method_gettext(L: PLua_State): Integer; cdecl; var o: TCatarinkaJSON; begin o := TCatarinkaJSON(LuaToTLuaObject(L, 1)); lua_pushstring(L, o.obj.text); result := 1; end; function method_gettext_withunquotedkeys(L: PLua_State): Integer; cdecl; var o: TCatarinkaJSON; begin o := TCatarinkaJSON(LuaToTLuaObject(L, 1)); lua_pushstring(L, o.obj.TextUnquoted); result := 1; end; procedure register_methods(L: PLua_State; classTable: Integer); begin RegisterMethod(L, '__tostring', @method_gettext, classTable); RegisterMethod(L, 'getjson', @method_gettext, classTable); RegisterMethod(L, 'getjson_unquoted', @method_gettext_withunquotedkeys, classTable); RegisterMethod(L, 'load', @method_settext, classTable); RegisterMethod(L, 'loadfromfile', @method_loadfromfile, classTable); RegisterMethod(L, 'savetofile', @method_savetofile, classTable); end; const cObjectName = 'ctk_json'; function new_callback(L: PLua_State; AParent: TLuaObject = nil): TLuaObject; begin result := TCatarinkaJSON.Create(L, AParent); end; function Create(L: PLua_State): Integer; cdecl; var p: TLuaObjectNewCallback; begin p := @new_callback; result := new_LuaObject(L, cObjectName, p); end; procedure RegisterCatarinkaJSON(L: PLua_State); begin RegisterTLuaObject(L, cObjectName, @Create, @register_methods); end; constructor TCatarinkaJSON.Create(LuaState: PLua_State; AParent: TLuaObject); begin inherited Create(LuaState, AParent); obj := TCatJSON.Create; end; destructor TCatarinkaJSON.Destroy; begin obj.Free; inherited Destroy; end; function TCatarinkaJSON.GetPropValue(propName: String): Variant; begin if obj.sobject.o[propName] <> nil then begin case obj.sobject.o[propName].DataType of stNull: result := Null; stBoolean: result := obj.sobject.b[propName]; stDouble: result := obj.sobject.d[propName]; stInt: result := obj.sobject.i[propName]; stString: result := obj.sobject.s[propName]; // stObject,stArray, stMethod: end; end; end; function TCatarinkaJSON.SetPropValue(propName: String; const AValue: Variant): Boolean; var ltype: Integer; begin result := true; ltype := lua_type(L, 3); case ltype of LUA_TSTRING: obj.sobject.s[propName] := lua_tostring(L, 3); LUA_TBOOLEAN: obj.sobject.b[propName] := lua_toboolean(L, 3); LUA_TNUMBER: begin if TVarData(AValue).vType = varDouble then obj.sobject.d[propName] := lua_tonumber(L, 3) else obj.sobject.i[propName] := lua_tointeger(L, 3); end; else obj[propName] := AValue; end; end; end.
unit itcmm; { ================================================================= Instrutech ITC-16/18 Interface Library V1.0 (c) John Dempster, University of Strathclyde, All Rights Reserved =================================================================} interface uses WinTypes,Dialogs, SysUtils, WinProcs,mmsystem; procedure ITCMM_InitialiseBoard ; procedure ITCMM_LoadLibrary ; function ITCMM_GetDLLAddress( Handle : Integer ; const ProcName : string ) : Pointer ; procedure ITCMM_ConfigureHardware( EmptyFlagIn : Integer ) ; function ITCMM_ADCToMemory( var HostADCBuf : Array of SmallInt ; nChannels : Integer ; nSamples : Integer ; var dt : Double ; ADCVoltageRange : Single ; TriggerMode : Integer ; CircularBuffer : Boolean ) : Boolean ; function ITCMM_StopADC : Boolean ; procedure ITCMM_GetADCSamples ( var OutBuf : Array of SmallInt ; var OutBufPointer : Integer ) ; procedure ITCMM_CheckSamplingInterval( var SamplingInterval : Double ; var Ticks : Cardinal ) ; function ITCMM_MemoryToDACAndDigitalOut( var DACValues : Array of SmallInt ; nChannels : Integer ; nPoints : Integer ; var DigValues : Array of SmallInt ; DigitalInUse : Boolean ) : Boolean ; function ITCMM_GetDACUpdateInterval : double ; function ITCMM_StopDAC : Boolean ; procedure ITCMM_WriteDACsAndDigitalPort( var DACVolts : array of Single ; nChannels : Integer ; DigValue : Integer ) ; function ITCMM_GetLabInterfaceInfo( var Model : string ; { Laboratory interface model name/number } var ADCMinSamplingInterval : Double ; { Smallest sampling interval } var ADCMaxSamplingInterval : Double ; { Largest sampling interval } var ADCMinValue : Integer ; { Negative limit of binary ADC values } var ADCMaxValue : Integer ; { Positive limit of binary ADC values } var ADCVoltageRanges : Array of single ; { A/D voltage range option list } var NumADCVoltageRanges : Integer ; { No. of options in above list } var ADCBufferLimit : Integer ; { Max. no. samples in A/D buffer } var DACMaxVolts : Single ; { Positive limit of bipolar D/A voltage range } var DACMinUpdateInterval : Double {Min. D/A update interval } ) : Boolean ; function ITCMM_GetMaxDACVolts : single ; function ITCMM_ReadADC( Channel : Integer ) : SmallInt ; procedure ITCMM_GetChannelOffsets( var Offsets : Array of Integer ; NumChannels : Integer ) ; procedure ITCMM_CloseLaboratoryInterface ; procedure SetBits( var Dest : Word ; Bits : Word ) ; procedure ClearBits( var Dest : Word ; Bits : Word ) ; function TrimChar( Input : Array of Char ) : string ; function MinInt( const Buf : array of LongInt ) : LongInt ; function MaxInt( const Buf : array of LongInt ) : LongInt ; Procedure ITCMM_CheckError( Err : Cardinal ; ErrSource : String ) ; implementation uses SESLabIO ; const MAX_DEVICE_TYPE_NUMBER = 4 ; ITC16_ID = 0 ; ITC16_MAX_DEVICE_NUMBER= 16 ; ITC18_ID = 1 ; ITC18_MAX_DEVICE_NUMBER = 16 ; ITC1600_ID = 2 ; ITC1600_MAX_DEVICE_NUMBER = 16 ; ITC00_ID = 3 ; ITC00_MAX_DEVICE_NUMBER = 16 ; ITC_MAX_DEVICE_NUMBER = 16 ; NORMAL_MODE = 0 ; SMART_MODE = 1 ; D2H = $00 ; //Input H2D = $01 ; //Output DIGITAL_INPUT = $02 ; //Digital Input DIGITAL_OUTPUT = $03 ; //Digital Output AUX_INPUT = $04 ; //Aux Input AUX_OUTPUT = $05 ; //Aux Output //STUB -> check the correct number NUMBER_OF_D2H_CHANNELS = 32 ; //ITC1600: 8+F+S0+S1+4(AUX) == 15 * 2 = 30 NUMBER_OF_H2D_CHANNELS = 15 ; //ITC1600: 4+F+S0+S1 == 7 * 2 = 14 + 1-Host-Aux //STUB -> Move this object to the Registry ITC18_SOFTWARE_SEQUENCE_SIZE = 4096 ; //STUB ->Verify ITC16_SOFTWARE_SEQUENCE_SIZE = 1024 ; ITC18_NUMBEROFCHANNELS = 16 ; //4 + 8 + 2 + 1 + 1 ITC18_NUMBEROFOUTPUTS = 7 ; //4 + 2 + 1 ITC18_NUMBEROFINPUTS = 9 ; //8 + 1 ITC18_NUMBEROFADCINPUTS = 8 ; ITC18_NUMBEROFDACOUTPUTS = 4 ; ITC18_NUMBEROFDIGINPUTS = 1 ; ITC18_NUMBEROFDIGOUTPUTS = 2 ; ITC18_NUMBEROFAUXINPUTS = 0 ; ITC18_NUMBEROFAUXOUTPUTS = 1 ; ITC18_DA_CH_MASK = $3 ; //4 DA Channels ITC18_DO0_CH = $4 ; //DO0 ITC18_DO1_CH = $5 ; //DO1 ITC18_AUX_CH = $6 ; //AUX ITC16_NUMBEROFCHANNELS = 14 ; //4 + 8 + 1 + 1 ITC16_NUMBEROFOUTPUTS = 5 ; //4 + 1 ITC16_NUMBEROFINPUTS = 9 ; //8 + 1 ITC16_DO_CH = 4 ; ITC16_NUMBEROFADCINPUTS = 8 ; ITC16_NUMBEROFDACOUTPUTS = 4 ; ITC16_NUMBEROFDIGINPUTS = 1 ; ITC16_NUMBEROFDIGOUTPUTS = 1 ; ITC16_NUMBEROFAUXINPUTS = 0 ; ITC16_NUMBEROFAUXOUTPUTS = 0 ; //STUB: Check the numbers ITC1600_NUMBEROFCHANNELS = 47 ; //15 + 32 ITC1600_NUMBEROFINPUTS = 32 ; //(8 AD + 1 Temp + 4 Aux + 3 Dig) * 2 ITC1600_NUMBEROFOUTPUTS = 15 ; //(4 + 3) * 2 + 1 ITC1600_NUMBEROFADCINPUTS = 16 ; //8+8 ITC1600_NUMBEROFDACOUTPUTS = 8 ; //4+4 ITC1600_NUMBEROFDIGINPUTS = 6 ; //F+S+S * 2 ITC1600_NUMBEROFDIGOUTPUTS = 6 ; //F+S+S * 2 ITC1600_NUMBEROFAUXINPUTS = 8 ; //4+4 ITC1600_NUMBEROFAUXOUTPUTS = 1 ; //On Host ITC1600_NUMBEROFTEMPINPUTS = 2 ; //1+1 ITC1600_NUMBEROFINPUTGROUPS = 8 ; // ITC1600_NUMBEROFOUTPUTGROUPS = 5 ; //(DAC, SD) + (DAC, SD) + FD + FD + HOST //*************************************************************************** //ITC1600 CHANNELS //DACs ITC1600_DA0 = 0 ; //RACK0 ITC1600_DA1 = 1 ; ITC1600_DA2 = 2 ; ITC1600_DA3 = 3 ; ITC1600_DA4 = 4 ; //RACK1 ITC1600_DA5 = 5 ; ITC1600_DA6 = 6 ; ITC1600_DA7 = 7; //Digital outputs ITC1600_DOF0 = 8 ; //RACK0 ITC1600_DOS00 = 9 ; ITC1600_DOS01 = 10 ; ITC1600_DOF1 = 11 ; //RACK1 ITC1600_DOS10 = 12 ; ITC1600_DOS11 = 13 ; ITC1600_HOST = 14 ; //ADCs ITC1600_AD0 = 0 ; //RACK0 ITC1600_AD1 = 1 ; ITC1600_AD2 = 2 ; ITC1600_AD3 = 3 ; ITC1600_AD4 = 4 ; ITC1600_AD5 = 5 ; ITC1600_AD6 = 6 ; ITC1600_AD7 = 7 ; ITC1600_AD8 = 8 ; //RACK1 ITC1600_AD9 = 9 ; ITC1600_AD10 = 10 ; ITC1600_AD11 = 11 ; ITC1600_AD12 = 12 ; ITC1600_AD13 = 13 ; ITC1600_AD14 = 14 ; ITC1600_AD15 = 15 ; //Slow ADCs ITC1600_SAD0 = 16 ; //RACK0 ITC1600_SAD1 = 17 ; ITC1600_SAD2 = 18 ; ITC1600_SAD3 = 19 ; ITC1600_SAD4 = 20 ; //RACK1 ITC1600_SAD5 = 21 ; ITC1600_SAD6 = 22 ; ITC1600_SAD7 = 23 ; //Temperature ITC1600_TEM0 = 24 ; //RACK0 ITC1600_TEM1 = 25 ; //RACK1 //Digital inputs ITC1600_DIF0 = 26 ; //RACK0 ITC1600_DIS00 = 27 ; ITC1600_DIS01 = 28 ; ITC1600_DIF1 = 29 ; //RACK1 ITC1600_DIS10 = 31 ; ITC1600_DIS11 = 32 ; ITC18_STANDARD_FUNCTION = 0 ; ITC18_PHASESHIFT_FUNCTION = 1 ; ITC18_DYNAMICCLAMP_FUNCTION = 2 ; ITC18_SPECIAL_FUNCTION = 3 ; ITC1600_STANDARD_FUNCTION = 0 ; //*************************************************************************** //Overflow/Underrun Codes ITC_READ_OVERFLOW_H = $01 ; ITC_WRITE_UNDERRUN_H = $02 ; ITC_READ_OVERFLOW_S = $10 ; ITC_WRITE_UNDERRUN_S = $20 ; ITC_STOP_CH_ON_OVERFLOW = $0001 ; //Stop One Channel ITC_STOP_CH_ON_UNDERRUN = $0002 ; ITC_STOP_CH_ON_COUNT = $1000 ; ITC_STOP_PR_ON_COUNT = $2000 ; ITC_STOP_DR_ON_OVERFLOW = $0100 ; //Stop One Direction ITC_STOP_DR_ON_UNDERRUN = $0200 ; ITC_STOP_ALL_ON_OVERFLOW = $1000 ; //Stop System (Hardware STOP) ITC_STOP_ALL_ON_UNDERRUN = $2000 ; //*************************************************************************** //Software Keys MSB PaulKey = $5053 ; HekaKey = $4845 ; UicKey = $5543 ; InstruKey = $4954 ; AlexKey = $4142 ; EcellKey = $4142 ; SampleKey = $5470 ; TestKey = $4444 ; TestSuiteKey = $5453 ; ITC_EMPTY = 0 ; ITC_RESERVE = $80000000 ; ITC_INIT_FLAG = $00008000 ; ITC_FUNCTION_MASK = $00000FFF ; RUN_STATE = $10 ; ERROR_STATE = $80000000 ; DEAD_STATE = $00 ; EMPTY_INPUT = $01 ; EMPTY_OUTPUT = $02 ; USE_FREQUENCY = $0 ; USE_TIME = $1 ; USE_TICKS = $2 ; NO_SCALE = $0 ; MS_SCALE = $4 ; US_SCALE = $8 ; NS_SCALE = $C ; READ_TOTALTIME = $01 ; READ_RUNTIME = $02 ; READ_ERRORS = $04 ; READ_RUNNINGMODE = $08 ; READ_OVERFLOW = $10 ; READ_CLIPPING = $20 ; RESET_FIFO_COMMAND = $10000 ; PRELOAD_FIFO_COMMAND = $20000 ; LAST_FIFO_COMMAND = $40000 ; FLUSH_FIFO_COMMAND = $80000 ; // Error flags ACQ_SUCCESS = 0 ; Error_DeviceIsNotSupported = $0001000 ; //1000 0000 0000 0001 0000 0000 0000 Error_UserVersionID = $80001000 ; Error_KernelVersionID = $81001000 ; Error_DSPVersionID = $82001000; Error_TimerIsRunning = $8CD01000 ; Error_TimerIsDead = $8CD11000 ; Error_TimerIsWeak = $8CD21000 ; Error_MemoryAllocation = $80401000 ; Error_MemoryFree = $80411000 ; Error_MemoryError = $80421000 ; Error_MemoryExist = $80431000 ; Warning_AcqIsRunning = $80601000 ; Error_TIMEOUT = $80301000 ; Error_OpenRegistry = $8D101000 ; Error_WriteRegistry = $8DC01000 ; Error_ReadRegistry = $8DB01000 ; Error_ParamRegistry = $8D701000 ; Error_CloseRegistry = $8D201000 ; Error_Open = $80101000 ; Error_Close = $80201000 ; Error_DeviceIsBusy = $82601000 ; Error_AreadyOpen = $80111000 ; Error_NotOpen = $80121000 ; Error_NotInitialized = $80D01000 ; Error_Parameter = $80701000 ; Error_ParameterSize = $80A01000 ; Error_Config = $89001000 ; Error_InputMode = $80611000 ; Error_OutputMode = $80621000 ; Error_Direction = $80631000 ; Error_ChannelNumber = $80641000 ; Error_SamplingRate = $80651000 ; Error_StartOffset = $80661000 ; Error_Software = $8FF01000 ; type //Specification for Hardware Configuration THWFunction = packed record Mode : Cardinal ; //Mode: 0 - Internal Clock; 1 - Intrabox Clock; 2 External Clock U2F_File :Pointer ; //U2F File name -> may be NULL SizeOfSpecificFunction : Cardinal ; //Sizeof SpecificFunction SpecificFunction : Pointer ; //Specific for each device end ; TITC1600_Special_HWFunction = packed record Func : Cardinal ; //HWFunction DSPType : Cardinal ; //LCA for Interface side HOSTType : Cardinal ; //LCA for Interface side RACKType : Cardinal ; //LCA for Interface side end ; TITC18_Special_HWFunction = packed record Func : Cardinal ; //HWFunction InterfaceData : Pointer ; //LCA for Interface side IsolatedData : Pointer ; //LCA for Isolated side end ; TITCChannelInfo = packed record ModeNumberOfPoints : Cardinal ; ChannelType : Cardinal ; ChannelNumber : Cardinal ; ScanNumber : Cardinal ; //0 - does not care; Use High speed if possible ErrorMode : Cardinal ; //See ITC_STOP_XX..XX definition for Error Modes ErrorState : Cardinal ; FIFOPointer : Pointer ; FIFONumberOfPoints : Cardinal ; //In Points ModeOfOperation : Cardinal ; SizeOfModeParameters : Cardinal ; ModeParameters : Pointer ; SamplingIntervalFlag : Cardinal ; //See flags above SamplingRate : Double ; //See flags above StartOffset : Double ; //Seconds Gain : Double ; //Times Offset : Double ; //Volts end ; TITCStatus = packed record CommandStatus : Cardinal ; RunningMode : Cardinal ; Overflow : Cardinal ; Clipping : Cardinal ; TotalSeconds : Double ; RunSeconds : Double ; end ; //Specification for Acquisition Configuration TITCPublicConfig = packed record DigitalInputMode : Cardinal ; //Bit 0: Latch Enable, Bit 1: Invert. For ITC1600; See AES doc. ExternalTriggerMode : Cardinal ; //Bit 0: Transition, Bit 1: Invert ExternalTrigger : Cardinal ; //Enable EnableExternalClock : Cardinal ; //Enable DACShiftValue : Cardinal ; //For ITC18 Only. Needs special LCA InputRange : Cardinal ; //AD0.. AD7 TriggerOutPosition : Cardinal ; OutputEnable : Integer ; SequenceLength : Cardinal ; //In/Out for ITC16/18; Out for ITC1600 Sequence : Pointer ; //In/Out for ITC16/18; Out for ITC1600 SequenceLengthIn : Cardinal ; //For ITC1600 only SequenceIn : Pointer ; //For ITC1600 only ResetFIFOFlag : Cardinal ; //Reset FIFO Pointers / Total Number of points in NORMALMODE ControlLight : Cardinal ; SamplingInterval : Double ; //In Seconds. Note: may be calculated from channel setting end ; TITCChannelData = packed record ChannelType : Cardinal ; //Channel Type + Command ChannelNumber : Cardinal ; //Channel Number Value : Integer ; //Number of points OR Data Value DataPointer : Pointer ; //Data end ; TITCSingleScanData = packed record ChannelType : Cardinal ; //Channel Type ChannelNumber : Cardinal ; //Channel Number IntegrationPeriod : Double ; DecimateMode : Cardinal ; end ; TVersionInfo = packed record Major : Integer ; Minor : Integer ; Description : Array[0..79] of char ; Date : Array[0..79] of char ; end ; TGlobalDeviceInfo = packed record DeviceType : Cardinal ; DeviceNumber : Cardinal ; PrimaryFIFOSize : Cardinal ; //In Points SecondaryFIFOSize : Cardinal ; //In Points LoadedFunction : Cardinal ; SoftKey : Cardinal ; Mode : Cardinal ; MasterSerialNumber : Cardinal ; SecondarySerialNumber : Cardinal ; HostSerialNumber : Cardinal ; NumberOfDACs : Cardinal ; NumberOfADCs : Cardinal ; NumberOfDOs : Cardinal ; NumberOfDIs : Cardinal ; NumberOfAUXOs : Cardinal ; NumberOfAUXIs : Cardinal ; Reserved0 : Cardinal ; Reserved1 : Cardinal ; Reserved2 : Cardinal ; Reserved3 : Cardinal ; end ; TITCStartInfo = packed record ExternalTrigger : Integer ; //-1 - do not change OutputEnable : Integer ; //-1 - do not change StopOnOverflow : Integer ; //-1 - do not change StopOnUnderrun : Integer ; //-1 - do not change DontUseTimerThread : Integer ; Reserved1 : Cardinal ; Reserved2 : Cardinal ; Reserved3 : Cardinal ; StartTime : Double ; StopTime : Double ; end ; TITCLimited = packed record ChannelType : Cardinal ; ChannelNumber : Cardinal ; SamplingIntervalFlag : Cardinal ; //See flags above SamplingRate : Double ; //See flags above TimeIntervalFlag : Cardinal ; //See flags above Time : Double ; //See flags above DecimationMode : Cardinal ; Data : Pointer ; end ; // *** DLL libray function templates *** TITC_Devices = Function ( DeviceType : Cardinal ; Var DeviceNumber : Cardinal ) : Cardinal ; cdecl ; TITC_GetDeviceHandle = Function( DeviceType : Cardinal ; DeviceNumber : Cardinal ; Var DeviceHandle : Integer ) : Cardinal ; cdecl ; TITC_GetDeviceType = Function( DeviceHandle : Integer ; Var DeviceType : Cardinal ; Var DeviceNumber : Cardinal ) : Cardinal ; cdecl ; TITC_OpenDevice = Function ( DeviceType : Cardinal ; DeviceNumber : Cardinal ; Mode : Cardinal ; Var DeviceHandle : Integer ) : Cardinal ; cdecl ; TITC_CloseDevice = Function( DeviceHandle : Integer ) : Cardinal ; cdecl ; TITC_InitDevice = Function( DeviceHandle : Integer ; {Var} sHWFunction : pointer {THWFunction} ) : Cardinal ; cdecl ; //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM //M //M STATIC INFORMATION FUNCTIONs //M //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM TITC_GetDeviceInfo = Function( DeviceHandle : Integer ; Var DeviceInfo : TGlobalDeviceInfo ) : Cardinal ; cdecl ; TITC_GetVersions = Function( DeviceHandle : Integer ; Var ThisDriverVersion : TVersionInfo ; Var KernelLevelDriverVersion : TVersionInfo ; Var HardwareVersion: TVersionInfo ) : Cardinal ; cdecl ; TITC_GetSerialNumbers = Function( DeviceHandle : Integer ; Var HostSerialNumber : Integer ; Var MasterBoxSerialNumber : Integer ; Var SlaveBoxSerialNumber : Integer ) : Cardinal ; cdecl ; TITC_GetStatusText = Function( DeviceHandle : Integer ; Status : Integer ; Text : PChar ; MaxCharacters : Cardinal ) : Cardinal ; cdecl ; TITC_SetSoftKey = Function( DeviceHandle : Integer ; SoftKey : Cardinal ) : Cardinal ; cdecl ; //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM //M //M DYNAMIC INFORMATION FUNCTIONs //M //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM TITC_GetState = Function( DeviceHandle : Integer ; Var sParam : TITCStatus ) : Cardinal ; cdecl ; TITC_SetState = Function( DeviceHandle : Integer ; Var sParam : TITCStatus ): Cardinal ; cdecl ; TITC_GetFIFOInformation = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var ChannelData : Array of TITCChannelData ) : Cardinal ; cdecl ; //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM //M //M CONFIGURATION FUNCTIONs //M //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM TITC_ResetChannels = Function( DeviceHandle : Integer ) : Cardinal ; cdecl ; TITC_SetChannels = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Channels : Array of TITCChannelInfo ) : Cardinal ; cdecl ; TITC_UpdateChannels = Function( DeviceHandle : Integer ) : Cardinal ; cdecl ; TITC_GetChannels = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Channels : Array of TITCChannelInfo ): Cardinal ; cdecl ; TITC_ConfigDevice = Function( DeviceHandle : Integer ; Var ITCConfig : TITCPublicConfig ): Cardinal ; cdecl ; TITC_Start = Function( DeviceHandle : Integer ; Var StartInfo : TITCStartInfo ) : Cardinal ; cdecl ; TITC_Stop = Function( DeviceHandle : Integer ; Var StartInfo : TITCStartInfo ) : Cardinal ; cdecl ; TITC_UpdateNow = Function( DeviceHandle : Integer ; Var StartInfo : TITCStartInfo ) : Cardinal ; cdecl ; TITC_SingleScan = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCSingleScanData ) : Cardinal ; cdecl ; TITC_AsyncIO = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCChannelData ) : Cardinal ; cdecl ; //*************************************************************************** TITC_GetDataAvailable = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCChannelData ) : Cardinal ; cdecl ; TITC_UpdateFIFOPosition = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCChannelData ) : Cardinal ; cdecl ; TITC_ReadWriteFIFO = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCChannelData ) : Cardinal ; cdecl ; TITC_UpdateFIFOInformation = Function( DeviceHandle : Integer ; NumberOfChannels : Cardinal ; Var Data : Array of TITCChannelData ) : Cardinal ; cdecl ; var ITC_Devices : TITC_Devices ; ITC_GetDeviceHandle : TITC_GetDeviceHandle ; ITC_GetDeviceType : TITC_GetDeviceType ; ITC_OpenDevice : TITC_OpenDevice ; ITC_CloseDevice : TITC_CloseDevice ; ITC_InitDevice : TITC_InitDevice ; ITC_GetDeviceInfo : TITC_GetDeviceInfo ; ITC_GetVersions : TITC_GetVersions ; ITC_GetSerialNumbers : TITC_GetSerialNumbers ; ITC_GetStatusText : TITC_GetStatusText ; ITC_SetSoftKey : TITC_SetSoftKey ; ITC_GetState : TITC_GetState ; ITC_SetState : TITC_SetState ; ITC_GetFIFOInformation : TITC_GetFIFOInformation ; ITC_ResetChannels : TITC_ResetChannels ; ITC_SetChannels : TITC_SetChannels ; ITC_UpdateChannels : TITC_UpdateChannels ; ITC_GetChannels : TITC_GetChannels ; ITC_ConfigDevice : TITC_ConfigDevice ; ITC_Start : TITC_Start ; ITC_Stop : TITC_Stop ; ITC_UpdateNow : TITC_UpdateNow ; ITC_SingleScan : TITC_SingleScan ; ITC_AsyncIO : TITC_AsyncIO ; ITC_GetDataAvailable : TITC_GetDataAvailable ; ITC_UpdateFIFOPosition : TITC_UpdateFIFOPosition ; ITC_ReadWriteFIFO : TITC_ReadWriteFIFO ; ITC_UpdateFIFOInformation : TITC_UpdateFIFOInformation ; LibraryHnd : THandle ; // ITCMM DLL library handle DVPLibraryHnd : THandle ; Device : Integer ; // ITCMM device handle DeviceType : Cardinal ; // ITC interface type (ITC16/ITC18) LibraryLoaded : boolean ; // Libraries loaded flag DeviceInitialised : Boolean ; DeviceInfo : TGlobalDeviceInfo ; // ITC device hardware information FADCVoltageRangeMax : Single ; // Upper limit of A/D input voltage range FADCMinValue : Integer ; // Max. A/D integer value FADCMaxValue : Integer ; // Min. A/D integer value FADCSamplingInterval : Double ; FADCMinSamplingInterval : Single ; FADCMaxSamplingInterval : Single ; FADCBufferLimit : Integer ; CyclicADCBuffer : Boolean ; EmptyFlag : SmallInt ; FNumADCSamples : Integer ; FNumADCChannels : Integer ; FNumSamplesRequired : Integer ; OutPointer : Integer ; FDACVoltageRangeMax : Single ; // Upper limit of D/A voltage range FDACMinValue : Integer ; // Max. D/A integer value FDACMaxValue : Integer ; // Min. D/A integer value FNumDACPoints : Integer ; FNumDACChannels : Integer ; FDACMinUpdateInterval : Single ; DACFIFO : Array[0..3] of PSmallIntArray ; // D/A waveform storage buffers ADCFIFO : Array[0..7] of PSmallIntArray ; // A/D sample storage buffers ADCPointer : Array[0..7] of Integer ; // A/D FIFO latest sample pointer DIGFIFO : PSmallIntArray ; // Digital O/P buffer DefaultDigValue : Integer ; ADCActive : Boolean ; FADCSweepDone : Boolean ; DACActive : Boolean ; function ITCMM_GetLabInterfaceInfo( var Model : string ; { Laboratory interface model name/number } var ADCMinSamplingInterval : Double ; { Smallest sampling interval } var ADCMaxSamplingInterval : Double ; { Largest sampling interval } var ADCMinValue : Integer ; { Negative limit of binary ADC values } var ADCMaxValue : Integer ; { Positive limit of binary ADC values } var ADCVoltageRanges : Array of single ; { A/D voltage range option list } var NumADCVoltageRanges : Integer ; { No. of options in above list } var ADCBufferLimit : Integer ; { Max. no. samples in A/D buffer } var DACMaxVolts : Single ; { Positive limit of bipolar D/A voltage range } var DACMinUpdateInterval : Double {Min. D/A update interval } ) : Boolean ; { -------------------------------------------- Get information about the interface hardware -------------------------------------------- } begin if not DeviceInitialised then ITCMM_InitialiseBoard ; { Get type of Digidata 1320 } if DeviceInitialised then begin { Get device model and serial number } if DeviceType = ITC16_ID then Model := format( ' ITC-16 s/n %d',[DeviceInfo.MasterSerialNumber] ) else if DeviceType = ITC18_ID then Model := format( ' ITC-18 s/n %d',[DeviceInfo.MasterSerialNumber] ) else Model := 'Unknown' ; // Define available A/D voltage range options ADCVoltageRanges[0] := 10.24 ; ADCVoltageRanges[1] := 5.12 ; ADCVoltageRanges[2] := 2.06 ; ADCVoltageRanges[3] := 1.03 ; NumADCVoltageRanges := 4 ; FADCVoltageRangeMax := ADCVoltageRanges[0] ; // A/D sample value range (16 bits) ADCMinValue := -32678 ; ADCMaxValue := -ADCMinValue - 1 ; FADCMinValue := ADCMinValue ; FADCMaxValue := ADCMaxValue ; // Upper limit of bipolar D/A voltage range DACMaxVolts := 10.25 ; FDACVoltageRangeMax := 10.25 ; DACMinUpdateInterval := 2.5E-6 ; FDACMinUpdateInterval := DACMinUpdateInterval ; // Min./max. A/D sampling intervals ADCMinSamplingInterval := 2.5E-6 ; ADCMaxSamplingInterval := 100.0 ; FADCMinSamplingInterval := ADCMinSamplingInterval ; FADCMaxSamplingInterval := ADCMaxSamplingInterval ; FADCBufferLimit := High(TSmallIntArray) ; ADCBufferLimit := FADCBufferLimit ; end ; Result := DeviceInitialised ; end ; procedure ITCMM_LoadLibrary ; { ------------------------------------- Load ITCMM.DLL library into memory -------------------------------------} begin { Load ITC-16 interface DLL library } LibraryHnd := LoadLibrary( PChar('itcmm.DLL')); { Get addresses of procedures in library } if LibraryHnd > 0 then begin @ITC_Devices :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_Devices') ; @ITC_GetDeviceHandle :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetDeviceHandle') ; @ITC_GetDeviceType :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetDeviceType') ; @ITC_OpenDevice :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_OpenDevice') ; @ITC_CloseDevice :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_CloseDevice') ; @ITC_InitDevice :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_InitDevice') ; @ITC_GetDeviceInfo :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetDeviceInfo') ; @ITC_GetVersions :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetVersions') ; @ITC_GetSerialNumbers :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetSerialNumbers') ; @ITC_GetStatusText :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetStatusText') ; @ITC_SetSoftKey :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_SetSoftKey') ; @ITC_GetState :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetState') ; @ITC_SetState :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_SetState') ; @ITC_GetFIFOInformation :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetFIFOInformation') ; @ITC_ResetChannels :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_ResetChannels') ; @ITC_SetChannels :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_SetChannels') ; @ITC_UpdateChannels :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_UpdateChannels') ; @ITC_GetChannels :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetChannels') ; @ITC_ConfigDevice :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_ConfigDevice') ; @ITC_Start :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_Start') ; @ITC_Stop :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_Stop') ; @ITC_UpdateNow :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_UpdateNow') ; @ITC_SingleScan :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_SingleScan') ; @ITC_AsyncIO :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_AsyncIO') ; @ITC_GetDataAvailable :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_GetDataAvailable') ; @ITC_UpdateFIFOPosition :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_UpdateFIFOPosition') ; @ITC_ReadWriteFIFO :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_ReadWriteFIFO') ; @ITC_UpdateFIFOInformation :=ITCMM_GetDLLAddress(LibraryHnd,'ITC_UpdateFIFOInformation') ; LibraryLoaded := True ; end else begin MessageDlg( ' Instrutech interface library (ITCMM.DLL) not found', mtWarning, [mbOK], 0 ) ; LibraryLoaded := False ; end ; end ; function ITCMM_GetDLLAddress( Handle : Integer ; const ProcName : string ) : Pointer ; // ----------------------------------------- // Get address of procedure within ITC16 DLL // ----------------------------------------- begin Result := GetProcAddress(Handle,PChar(ProcName)) ; if Result = Nil then MessageDlg('ITC16.DLL- ' + ProcName + ' not found',mtWarning,[mbOK],0) ; end ; function ITCMM_GetMaxDACVolts : single ; { ----------------------------------------------------------------- Return the maximum positive value of the D/A output voltage range -----------------------------------------------------------------} begin Result := FDACVoltageRangeMax ; end ; procedure ITCMM_InitialiseBoard ; { ------------------------------------------- Initialise Instrutech interface hardware -------------------------------------------} var i,Err : Integer ; NumDevices : Cardinal ; begin DeviceInitialised := False ; if not LibraryLoaded then ITCMM_LoadLibrary ; if LibraryLoaded then begin // Determine type of ITC interface Err := ITC_Devices( ITC16_ID, NumDevices ) ; ITCMM_CheckError( Err, 'ITC_Devices' ) ; if Err <> ACQ_SUCCESS then exit else begin if NumDevices > 0 then DeviceType := ITC16_ID else begin ITC_Devices( ITC18_ID, NumDevices ) ; if NumDevices > 0 then DeviceType := ITC18_ID ; end ; end ; DeviceType := ITC18_ID ; // Open device Err := ITC_OpenDevice( DeviceType, 0, SMART_MODE, Device ) ; if Err = Error_DeviceIsBusy then begin MessageDlg( 'ITC : Device is busy, trying again', mtError, [mbOK], 0) ; Err := ITC_OpenDevice( DeviceType, 0, SMART_MODE, Device ) ; end ; ITCMM_CheckError( Err, 'ITC_OpenDevice' ) ; if Err <> ACQ_SUCCESS then exit ; // Initialise interface hardware Err := ITC_InitDevice( Device, Nil ) ; ITCMM_CheckError( Err, 'ITC_InitDevice' ) ; // Get device information Err := ITC_GetDeviceInfo( Device, DeviceInfo ) ; ITCMM_CheckError( Err, 'ITC_DeviceInfo' ) ; // Create A/D, D/A and digital O/P buffers for i := 0 to High(ADCFIFO) do New(ADCFIFO[i]) ; for i := 0 to High(DACFIFO) do New(DACFIFO[i]) ; New(DIGFIFO) ; DeviceInitialised := True ; end ; end ; procedure ITCMM_ConfigureHardware( EmptyFlagIn : Integer ) ; { -------------------------------------------------------------------------- -------------------------------------------------------------------------- } begin EmptyFlag := EmptyFlagIn ; end ; function ITCMM_ADCToMemory( var HostADCBuf : Array of SmallInt ; { A/D sample buffer (OUT) } nChannels : Integer ; { Number of A/D channels (IN) } nSamples : Integer ; { Number of A/D samples ( per channel) (IN) } var dt : Double ; { Sampling interval (s) (IN) } ADCVoltageRange : Single ; { A/D input voltage range (V) (IN) } TriggerMode : Integer ; { A/D sweep trigger mode (IN) } CircularBuffer : Boolean { Repeated sampling into buffer (IN) } ) : Boolean ; { Returns TRUE indicating A/D started } { ----------------------------- Start A/D converter sampling -----------------------------} var i,j : Word ; ch,iBuf : Integer ; Ticks : Cardinal ; StartInfo : TITCStartInfo ; ChannelInfo : Array[0..7] of TITCChannelInfo ; ChannelData : Array[0..7] of TITCChannelData ; Err : Cardinal ; OK : Boolean ; Config : TITCPublicConfig ; ADCSeq : Array[0..7] of Cardinal ; begin if not DeviceInitialised then ITCMM_InitialiseBoard ; if DeviceInitialised then begin // Stop any acquisition in progress ITCMM_StopADC ; // Copy to internal storage FNumADCSamples := nSamples ; FNumADCChannels := nChannels ; FNumSamplesRequired := nChannels*nSamples ; FADCSamplingInterval := dt ; CyclicADCBuffer := CircularBuffer ; Config.DigitalInputMode := 0 ; Config.ExternalTriggerMode := 2 ; Config.ExternalTrigger := 0 ; Config.EnableExternalClock := 0 ; Config.DACShiftValue := 0 ; Config.TriggerOutPosition := 0 ; Config.OutputEnable := 0 ; Config.SequenceLength := nChannels ; for ch := 0 to nChannels-1 do begin ADCSeq[ch] := ch ; end ; Config.Sequence := @ADCSeq ; Config.SequenceLength := 0 ; Config.Sequence := Nil ; Config.SequenceLengthIn := 0 ; Config.SequenceIn := Nil ; Config.ResetFIFOFlag := 1 ; Config.ControlLight := 0 ; Config.SamplingInterval := dt ; Err := ITC_ConfigDevice( Device, Config ) ; ITCMM_CheckError( Err, 'ITC_ConfigDevice' ) ; // Reset all existing channels Err := ITC_ResetChannels( Device ) ; ITCMM_CheckError( Err, 'ITC_ResetChannels' ) ; // Make sure that dt is an integer number of microsecs ITCMM_CheckSamplingInterval( dt, Ticks ) ; // Define new A/D input channels for ch := 0 to nChannels-1 do begin ChannelInfo[ch].ModeNumberOfPoints := 0 ; ChannelInfo[ch].ChannelType := D2H ; ChannelInfo[ch].ChannelNumber := ch ; ChannelInfo[ch].ScanNumber := 0 ; if CyclicADCBuffer then ChannelInfo[ch].ErrorMode := 0 else ChannelInfo[ch].ErrorMode := ITC_STOP_ALL_ON_OVERFLOW ; ChannelInfo[ch].ErrorState := 0 ; ChannelInfo[ch].FIFOPointer := Nil ; ChannelInfo[ch].FIFONumberOfPoints := nSamples ; ChannelInfo[ch].ModeOfOperation := 0 ; ChannelInfo[ch].SizeOfModeParameters := 0 ; ChannelInfo[ch].ModeParameters := 0 ; ChannelInfo[ch].SamplingIntervalFlag := USE_TIME or US_SCALE; ChannelInfo[ch].SamplingRate := dt*1E6 ; ChannelInfo[ch].StartOffset := 0.0 ; ChannelInfo[ch].Gain := ADCVoltageRange / FADCVoltageRangeMax ; ChannelInfo[ch].Offset := 0.0 ; end ; // Load new channel settings Err := ITC_SetChannels( Device, nChannels, ChannelInfo ) ; ITCMM_CheckError( Err, 'ITC_SetChannels' ) ; // Update interface with new settings Err := ITC_UpdateChannels( Device ) ; ITCMM_CheckError( Err, 'ITC_UpdateChannels' ) ; // Clear A/D FIFOs for ch := 0 to FNumADCChannels-1 do begin ChannelData[ch].ChannelType := D2H or FLUSH_FIFO_COMMAND ; ChannelData[ch].ChannelNumber := ch ; ChannelData[ch].Value := 0 ; end ; Err := ITC_ReadWriteFIFO( Device, FNumADCChannels, ChannelData ) ; ITCMM_CheckError(Err,'ITC_ReadWriteFIFO') ; // Start A/D sampling if TriggerMode <> tmWaveGen then begin // Free Run vs External Trigger of recording seeep if TriggerMode = tmExtTrigger then StartInfo.ExternalTrigger := 1 else StartInfo.ExternalTrigger := 0 ; StartInfo.OutputEnable := -1 ; StartInfo.StopOnOverFlow := -1 ; StartInfo.StopOnUnderRun := -1 ; StartInfo.DontUseTimerThread := -1 ; Err := ITC_Start( Device, StartInfo ) ; ITCMM_CheckError( Err, 'ITC_START' ) ; ADCActive := True ; OK := True ; end else OK := True ; OutPointer := 0 ; Result := OK ; end ; FADCSweepDone := False ; end ; function ITCMM_StopADC : Boolean ; { Returns False indicating A/D stopped } { ------------------------------- Reset A/D conversion sub-system -------------------------------} var Status : TITCStatus ; Dummy : TITCStartInfo ; Err : Cardinal ; begin if not DeviceInitialised then ITCMM_InitialiseBoard ; { Stop ITC interface (both A/D and D/A) } if DeviceInitialised then begin Status.CommandStatus := READ_RUNNINGMODE ; Err := ITC_GetState( Device, Status ) ; ITCMM_CheckError( Err, 'ITC_GetState' ) ; if Status.RunningMode <> DEAD_STATE then begin ITC_Stop( Device, Dummy ) ; ITCMM_CheckError( Err, 'ITC_Stop' ) ; end ; end ; ADCActive := False ; DACActive := False ; // Since A/D and D/A are synchronous D/A stops too Result := ADCActive ; end ; procedure ITCMM_GetADCSamples( var OutBuf : Array of SmallInt ; { Buffer to receive A/D samples } var OutBufPointer : Integer { Latest sample pointer [OUT]} ) ; // ----------------------------------------- // Get A/D samples from ITC interface FIFOS // ----------------------------------------- var Err,ch,i : Integer ; ChannelData : Array[0..7] of TITCChannelData ; NumCompleteChannelGroups : Integer ; Status : TITCStatus ; begin if ADCActive then begin // Determine number of samples available in FIFOs NumCompleteChannelGroups := High(NumCompleteChannelGroups) ; for ch := 0 to FNumADCChannels-1 do begin ChannelData[ch].ChannelType := D2H ; ChannelData[ch].ChannelNumber := ch ; ChannelData[ch].Value := 0 ; end ; Err := ITC_GetDataAvailable( Device, FNumADCChannels, ChannelData ) ; ITCMM_CheckError(Err,'ITC_GetDataAvailable') ; { for ch := 0 to FNumADCChannels-1 do begin outputdebugString(PChar(format('%d %d',[ch,ChannelData[ch].Value]))) ; end ;} Status.CommandStatus := READ_RUNNINGMODE ; Err := ITC_GetState( Device, Status ) ; ITCMM_CheckError(Err,'ITC_GetState') ; outputdebugString(PChar(format('%x',[Status.RunningMode]))) ; NumCompleteChannelGroups := High(NumCompleteChannelGroups) ; for ch := 0 to FNumADCChannels-1 do begin if NumCompleteChannelGroups > ChannelData[ch].Value then NumCompleteChannelGroups:= ChannelData[ch].Value ; end ; NumCompleteChannelGroups := ChannelData[0].Value ; // Read A/D samples from FIFO for ch := 0 to FNumADCChannels-1 do begin ChannelData[ch].ChannelType := D2H ; ChannelData[ch].ChannelNumber := ch ; ChannelData[ch].Value := NumCompleteChannelGroups ; ChannelData[ch].DataPointer := ADCFIFO[ch] ; end ; Err := ITC_ReadWriteFIFO( Device, FNumADCChannels, ChannelData ) ; ITCMM_CheckError(Err,'ITC_ReadWriteFIFO') ; // Interleave samples from A/D FIFO buffers into O/P buffer if not CyclicADCBuffer then begin // Single sweep for i := 0 to NumCompleteChannelGroups-1 do begin for ch := 0 to FNumADCChannels-1 do begin OutBuf[OutPointer] := ADCFIFO[ch]^[i] ; Inc(OutPointer) ; end ; end ; if Outpointer >= (FNumSamplesRequired) then FADCSweepDone := True ; OutBufPointer := MinInt([OutPointer,(FNumSamplesRequired-1)]) ; end else begin // Cyclic buffer for i := 0 to NumCompleteChannelGroups-1 do begin for ch := 0 to FNumADCChannels-1 do begin OutBuf[OutPointer] := ADCFIFO[ch]^[i] ; Inc(OutPointer) ; if Outpointer >= FNumSamplesRequired then Outpointer := 0 ; end ; end ; end ; end ; end ; procedure ITCMM_CheckSamplingInterval( var SamplingInterval : Double ; var Ticks : Cardinal ) ; { --------------------------------------------------- Convert sampling period from <SamplingInterval> (in s) into clocks ticks, Returns no. of ticks in "Ticks" ---------------------------------------------------} const SecsToMicrosecs = 1E6 ; var TicksRequired,Multiplier,iStep : Cardinal ; Steps : Array[0..4] of Cardinal ; begin Steps[0] := 1 ; Steps[1] := 2 ; Steps[2] := 4 ; Steps[3] := 5 ; Steps[4] := 8 ; TicksRequired := Round(SamplingInterval*SecsToMicrosecs) ; iStep := 0 ; Multiplier := 1 ; Ticks := Steps[iStep]*Multiplier ; while Ticks < TicksRequired do begin Ticks := Steps[iStep]*Multiplier ; if iStep = High(Steps) then begin Multiplier := Multiplier*10 ; iStep := 0 ; end else Inc(iStep) ; end ; SamplingInterval := Ticks/SecsToMicrosecs ; end ; function ITCMM_MemoryToDACAndDigitalOut( var DACValues : Array of SmallInt ; nChannels : Integer ; nPoints : Integer ; var DigValues : Array of SmallInt ; DigitalInUse : Boolean ) : Boolean ; { -------------------------------------------------------------- Send a voltage waveform stored in DACBuf to the D/A converters 30/11/01 DigFill now set to correct final value to prevent spurious digital O/P changes between records --------------------------------------------------------------} var i,j,ch,DACValue,Err : Integer ; StartInfo : TITCStartInfo ; ChannelInfo : Array[0..7] of TITCChannelInfo ; ChannelData : Array[0..7] of TITCChannelData ; State : TITCStatus ; begin if not DeviceInitialised then ITCMM_InitialiseBoard ; if DeviceInitialised then begin { Stop any acquisition in progress } {if ADCActive then} ADCActive := ITCMM_StopADC ; // Copy D/A values into D/A FIFO buffers for ch := 0 to nChannels-1 do begin j := ch ; for i := 0 to nPoints-1 do begin DACFIFO[ch]^[i] := DACValues[j] ; j := j + nChannels ; end ; end ; // Define D/A output channels for ch := 0 to nChannels-1 do begin ChannelInfo[ch].ChannelType := H2D ; ChannelInfo[ch].ChannelNumber := ch ; ChannelInfo[ch].ScanNumber := 0 ; ChannelInfo[ch].ErrorMode := {ITC_STOP_ALL_ON_UNDERRUN}0 ; ChannelInfo[ch].ErrorState := 0 ; ChannelInfo[ch].FIFOPointer := DACFIFO[ch] ; ChannelInfo[ch].FIFONumberOfPoints := nPoints ; ChannelInfo[ch].ModeOfOperation := 0 ; ChannelInfo[ch].SizeOfModeParameters := 0 ; ChannelInfo[ch].ModeParameters := 0 ; ChannelInfo[ch].SamplingIntervalFlag := USE_TIME or US_SCALE; ChannelInfo[ch].SamplingRate := FADCSamplingInterval*1E6 ; ChannelInfo[ch].StartOffset := 0.0 ; ChannelInfo[ch].Gain := 1.0 ; ChannelInfo[ch].Offset := 0.0 ; end ; // Add digital output channel if DigitalInUse then begin for i := 0 to nPoints-1 do DigFIFO^[i] := DigValues[i] ; ChannelInfo[0].ChannelType := DIGITAL_OUTPUT ; ChannelInfo[0].ChannelNumber := 0 ; ChannelInfo[0].ScanNumber := 0 ; ChannelInfo[0].ErrorMode := ITC_STOP_ALL_ON_OVERFLOW ; ChannelInfo[0].ErrorState := 0 ; ChannelInfo[0].FIFOPointer := DigFIFO ; ChannelInfo[0].FIFONumberOfPoints := nPoints ; ChannelInfo[0].ModeOfOperation := 0 ; ChannelInfo[0].SizeOfModeParameters := 0 ; ChannelInfo[0].ModeParameters := 0 ; ChannelInfo[0].SamplingIntervalFlag := USE_TIME or US_SCALE; ChannelInfo[0].SamplingRate := FADCSamplingInterval*1E6 ; ChannelInfo[0].StartOffset := 0.0 ; ChannelInfo[0].Gain := 1.0 ; ChannelInfo[0].Offset := 0.0 ; end ; // Load new channel settings Err := ITC_SetChannels( Device, {nChannels}1, ChannelInfo ) ; ITCMM_CheckError( Err, 'ITC_SetChannels' ) ; // Update interface with new settings Err := ITC_UpdateChannels( Device ) ; ITCMM_CheckError(Err,'ITC_UpdateChannels') ; // Write D/A samples to FIFO for ch := 0 to nChannels-1 do begin ChannelData[ch].ChannelType := H2D or RESET_FIFO_COMMAND or PRELOAD_FIFO_COMMAND {or LAST_FIFO_COMMAND} ; ChannelData[ch].ChannelNumber := ch ; ChannelData[ch].Value := nPoints ; ChannelData[ch].DataPointer := DACFIFO[ch] ; end ; Err := ITC_ReadWriteFIFO( Device, {nChannels}1, ChannelData ) ; ITCMM_CheckError(Err,'ITC_ReadWriteFIFO') ; {Save D/A sweep data } FNumDACPoints := nPoints ; FNumDACChannels := nChannels ; // Start combined A/D & D/A sweep StartInfo.ExternalTrigger := 0 ; // Start sweep immediately StartInfo.OutputEnable := 1 ; // Enable D/A output on interface StartInfo.StopOnOverFlow := -1 ; StartInfo.StopOnUnderRun := -1 ; StartInfo.DontUseTimerThread := -1 ; Err := ITC_Start( Device, StartInfo ) ; ITCMM_CheckError( Err, 'ITC_Start' ) ; DACActive := True ; ADCActive := True ; end ; Result := DACActive ; end ; function ITCMM_GetDACUpdateInterval : double ; { ----------------------- Get D/A update interval -----------------------} begin Result := FADCSamplingInterval ; { NOTE. DAC update interval is constrained to be the same as A/D sampling interval (set by ITCMM_ADCtoMemory. } end ; function ITCMM_StopDAC : Boolean ; { --------------------------------- Disable D/A conversion sub-system ---------------------------------} begin if not DeviceInitialised then ITCMM_InitialiseBoard ; DACActive := False ; Result := DACActive ; end ; procedure ITCMM_WriteDACsAndDigitalPort( var DACVolts : array of Single ; nChannels : Integer ; DigValue : Integer ) ; { ---------------------------------------------------- Update D/A outputs with voltages suppled in DACVolts and TTL digital O/P with bit pattern in DigValue ----------------------------------------------------} const MaxDACValue = 32767 ; MinDACValue = -32768 ; var DACScale : single ; ch,DACValue,NumCh : Integer ; ChannelData : Array[0..4] of TITCChannelData ; Err : Integer ; begin if not DeviceInitialised then ITCMM_InitialiseBoard ; if DeviceInitialised then begin // Scale from Volts to binary integer units DACScale := MaxDACValue/FDACVoltageRangeMax ; { Set up D/A channel values } NumCh := 0 ; for ch := 0 to nChannels-1 do begin // Correct for errors in hardware DAC scaling factor DACValue := Round(DACVolts[ch]*DACScale) ; // Keep within legitimate limits if DACValue > MaxDACValue then DACValue := MaxDACValue ; if DACValue < MinDACValue then DACValue := MinDACValue ; ChannelData[NumCh].ChannelType := H2D ; ChannelData[NumCh].ChannelNumber := ch ; ChannelData[NumCh].Value := DACValue ; Inc(NumCh) ; end ; // Set up digital O/P values ChannelData[NumCh].ChannelType := DIGITAL_OUTPUT ; ChannelData[NumCh].ChannelNumber := 0 ; ChannelData[NumCh].Value := DigValue ; Inc(NumCh) ; Err := ITC_AsyncIO( Device, NumCh, ChannelData ) ; ITCMM_CheckError( Err, 'ITC_AsyncIO' ) ; { Keep dig. value for use by DD132X_MemoryToDAC } DefaultDigValue := DigValue ; end ; end ; function ITCMM_ReadADC( Channel : Integer // A/D channel ) : SmallInt ; // --------------------------- // Read Analogue input channel // --------------------------- var ChannelData : TITCChannelData ; Err : Integer ; begin if not DeviceInitialised then ITCMM_InitialiseBoard ; if DeviceInitialised then begin ChannelData.ChannelType := D2H ; ChannelData.ChannelNumber := Channel ; Err := ITC_AsyncIO( Device, 1, ChannelData ) ; ITCMM_CheckError( Err, 'ITC_AsyncIO' ) ; Result := ChannelData.Value ; end ; end ; procedure ITCMM_GetChannelOffsets( var Offsets : Array of Integer ; NumChannels : Integer ) ; { -------------------------------------------------------- Returns the order in which analog channels are acquired and stored in the A/D data buffers --------------------------------------------------------} var ch : Integer ; begin for ch := 0 to NumChannels-1 do Offsets[ch] := ch ; end ; procedure ITCMM_CloseLaboratoryInterface ; { ----------------------------------- Shut down lab. interface operations ----------------------------------- } var i : Integer ; Err : Cardinal ; begin if DeviceInitialised then begin { Stop any acquisition in progress } ITCMM_StopADC ; { Close connection with interface } Err := ITC_CloseDevice( Device ) ; // Free A/D, D/A and digital O/P buffers for i := 0 to High(ADCFIFO) do Dispose(ADCFIFO[i]) ; for i := 0 to High(DACFIFO) do Dispose(DACFIFO[i]) ; Dispose(DIGFIFO) ; DeviceInitialised := False ; DACActive := False ; ADCActive := False ; end ; end ; procedure SetBits( var Dest : Word ; Bits : Word ) ; { --------------------------------------------------- Set the bits indicated in "Bits" in the word "Dest" ---------------------------------------------------} begin Dest := Dest or Bits ; end ; procedure ClearBits( var Dest : Word ; Bits : Word ) ; { --------------------------------------------------- Clear the bits indicated in "Bits" in the word "Dest" ---------------------------------------------------} var NotBits : Word ; begin NotBits := not Bits ; Dest := Dest and NotBits ; end ; function TrimChar( Input : Array of Char ) : string ; var i : Integer ; pInput : PChar ; begin pInput := @Input ; Result := '' ; for i := 0 to StrLen(pInput)-1 do Result := Result + Input[i] ; end ; { ------------------------------------------- Return the smallest value in the array 'Buf' -------------------------------------------} function MinInt( const Buf : array of LongInt { List of numbers (IN) } ) : LongInt ; { Returns Minimum of Buf } var i,Min : LongInt ; begin Min := High(Min) ; for i := 0 to High(Buf) do if Buf[i] < Min then Min := Buf[i] ; Result := Min ; end ; { ------------------------------------------- Return the largest value in the array 'Buf' -------------------------------------------} function MaxInt( const Buf : array of LongInt { List of numbers (IN) } ) : LongInt ; { Returns Maximum of Buf } var i,Max : LongInt ; begin Max := -High(Max) ; for i := 0 to High(Buf) do if Buf[i] > Max then Max := Buf[i] ; Result := Max ; end ; Procedure ITCMM_CheckError( Err : Cardinal ; // Error code ErrSource : String ) ; // Name of procedure which returned Err // ---------------------------------------------- // Report type and source of ITC interface error // ---------------------------------------------- var ErrName : string ; begin if Err <> ACQ_SUCCESS then begin Case Err of Error_DeviceIsNotSupported : ErrName := 'DeviceIsNotSupported' ; Error_UserVersionID : ErrName := 'UserVersionID' ; Error_KernelVersionID : ErrName := 'KernelVersionID' ; Error_DSPVersionID : ErrName := 'DSPVersionID' ; Error_TimerIsRunning : ErrName := 'TimerIsRunning' ; Error_TimerIsDead : ErrName := 'TimerIsDead' ; Error_TimerIsWeak : ErrName := 'TimerIsWeak' ; Error_MemoryAllocation : ErrName := 'MemoryAllocation' ; Error_MemoryFree : ErrName := 'MemoryFree' ; Error_MemoryError : ErrName := 'MemoryError' ; Error_MemoryExist : ErrName := 'MemoryExist' ; Warning_AcqIsRunning : ErrName := 'AcqIsRunning' ; Error_TIMEOUT : ErrName := 'TIMEOUT' ; Error_OpenRegistry : ErrName := 'OpenRegistry' ; Error_WriteRegistry : ErrName := 'WriteRegistry' ; Error_ReadRegistry : ErrName := 'ReadRegistry' ; Error_ParamRegistry : ErrName := 'ParamRegistry' ; Error_CloseRegistry : ErrName := 'CloseRegistry' ; Error_Open : ErrName := 'Open' ; Error_Close : ErrName := 'Close' ; Error_DeviceIsBusy : ErrName := 'DeviceIsBusy' ; Error_AreadyOpen : ErrName := 'AreadyOpen' ; Error_NotOpen : ErrName := 'NotOpen' ; Error_NotInitialized : ErrName := 'NotInitialized' ; Error_Parameter : ErrName := 'Parameter' ; Error_ParameterSize : ErrName := 'ParameterSize' ; Error_Config : ErrName := 'Config' ; Error_InputMode : ErrName := 'InputMode' ; Error_OutputMode : ErrName := 'OutputMode' ; Error_Direction : ErrName := 'Direction' ; Error_ChannelNumber : ErrName := 'ChannelNumber' ; Error_SamplingRate : ErrName := 'SamplingRate' ; Error_StartOffset : ErrName := 'StartOffset' ; Error_Software : ErrName := 'Software' ; else ErrName := 'Unknown' ; end ; MessageDlg( 'Error ' + ErrName + ' in ' + ErrSource, mtError, [mbOK], 0) ; end ; end ; end.
unit UCalculadora; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.Imaging.pngimage; type TForm1 = class(TForm) txt_Num1: TEdit; txt_Num2: TEdit; bt_Calcular: TButton; bt_Clear: TButton; bt_Dividir: TBitBtn; bt_Multiplicar: TBitBtn; bt_Subtrair: TBitBtn; bt_Soma: TBitBtn; lbl_Resultado: TLabel; procedure bt_CalcularClick(Sender: TObject); procedure bt_SomaClick(Sender: TObject); procedure bt_SubtrairClick(Sender: TObject); procedure bt_MultiplicarClick(Sender: TObject); procedure bt_DividirClick(Sender: TObject); procedure bt_ClearClick(Sender: TObject); procedure txt_Num1Change(Sender: TObject); private function Soma(num1, num2: double) : double; function Sub(num1, num2: double) : double; function Mult(num1, num2: double) : double; function Divisao(num1, num2: double) : double; public { Public declarations } end; var Form1: TForm1; num1, num2: double; operadores: array[0..3] of Boolean; count: integer; implementation {$R *.dfm} // Procedures procedure TForm1.txt_Num1Change(Sender: TObject); begin if (txt_Num1.Text = '') and (txt_Num2.Text = '') then begin txt_Num2.Enabled := false; end end; procedure TForm1.bt_SomaClick(Sender: TObject); begin operadores[0] := true; count := 0; if (txt_Num1.Text <> '') and (operadores[0] = true) then begin txt_Num2.Enabled := true; end else if (txt_Num2.Text <> '') then begin txt_Num2.Enabled := true; end else txt_Num2.Enabled := false; end; procedure TForm1.bt_SubtrairClick(Sender: TObject); begin operadores[1] := true; count := 1; if (txt_Num1.Text <> '') and (operadores[1] = true) then begin txt_Num2.Enabled := true; end else if (txt_Num2.Text <> '') then begin txt_Num2.Enabled := true; end else txt_Num2.Enabled := false; end; procedure TForm1.bt_MultiplicarClick(Sender: TObject); begin operadores[2] := true; count := 2; if (txt_Num1.Text <> '') and (operadores[2] = true) then begin txt_Num2.Enabled := true; end else if (txt_Num2.Text <> '') then begin txt_Num2.Enabled := true; end else txt_Num2.Enabled := false; end; procedure TForm1.bt_ClearClick(Sender: TObject); begin operadores[0] := false; operadores[1] := false; operadores[2] := false; operadores[3] := false; txt_Num2.Enabled := false; txt_Num1.Text := ''; txt_Num2.Text := ''; lbl_Resultado.Caption := ''; end; procedure TForm1.bt_DividirClick(Sender: TObject); begin operadores[3] := true; count := 3; if (txt_Num1.Text <> '') and (operadores[3] = true) then begin txt_Num2.Enabled := true; end else if (txt_Num2.Text <> '') then begin txt_Num2.Enabled := true; end else txt_Num2.Enabled := false; end; procedure TForm1.bt_CalcularClick(Sender: TObject); begin num1 := StrToFloat(txt_Num1.Text); num2 := StrToFloat(txt_Num2.Text); case count of 0: lbl_Resultado.Caption := FloatToStr(Soma(num1, num2)); 1: lbl_Resultado.Caption := FloatToStr(Sub(num1, num2)); 2: lbl_Resultado.Caption := FloatToStr(Mult(num1, num2)); 3: lbl_Resultado.Caption := FloatToStr(Divisao(num1, num2)); end; end; //Funções function TForm1.Soma(num1, num2: double) : double; begin result := num1 + num2; end; function TForm1.Sub(num1, num2: double) : double; begin result := num1 - num2; end; function TForm1.Mult(num1, num2: double) : double; begin result := num1 * num2; end; function TForm1.Divisao(num1, num2: double) : double; begin result := num1 / num2; end; end.
unit uGnEnumerator; interface uses Generics.Collections, SysUtils, uGnGenerics; type TGnEnumerator<_DataType, _IteratorType> = class(TEnumerator<_DataType>) type TGetCurrent = function (const AIterator: _IteratorType): _DataType of object; TMoveNext = function (var AIterator: _IteratorType): Boolean of object; strict private FGetCurrent : TGetCurrent; FMoveNext : TMoveNext; FIterator : _IteratorType; FStartPos : _IteratorType; strict protected function DoGetCurrent: _DataType; override; function DoMoveNext: Boolean; override; public constructor Create(const AStartPos : _IteratorType; const AGetCurrent : TGetCurrent; const AMoveNext : TMoveNext); function GetEnumerator: TEnumerator<_DataType>; end; implementation { TGnEnumerator } constructor TGnEnumerator<_DataType, _IteratorType>.Create(const AStartPos: _IteratorType; const AGetCurrent: TGetCurrent; const AMoveNext: TMoveNext); begin FStartPos := AStartPos; FIterator := FStartPos; FGetCurrent := AGetCurrent; FMoveNext := AMoveNext; end; function TGnEnumerator<_DataType, _IteratorType>.DoGetCurrent: _DataType; begin Result := FGetCurrent(FIterator) end; function TGnEnumerator<_DataType, _IteratorType>.DoMoveNext: Boolean; begin Result := FMoveNext(FIterator); end; function TGnEnumerator<_DataType, _IteratorType>.GetEnumerator: TEnumerator<_DataType>; begin Result := Self; end; end.
Program Aufgabe5(input, output); { Rekursive Funktion ist zu schreiben die entscheided ob ein Integer-Wert in einem Baum vom Typ tRefBinBaum enthalten ist. Diese Funktion soll einen Boolean welt zurückgeben} type tRefBinBaum= ^tBinBaum; tBinBaum= record wert : Integer; links, rechts : tRefBinBaum end; var baum : tRefBinBaum; function enthalten (inWert : integer; inBaum : tRefBinBaum) : boolean; { Returns true if inWert is contained in the inBaum tree } begin { base case - the empty tree } if (inBaum = nil) then begin enthalten := false; end else begin if (inBaum^.wert = inWert) then begin enthalten := true; end else begin enthalten := enthalten(inWert, inBaum^.links) or enthalten (inWert, inBaum^.rechts); end; end; end; begin { build tree } new(baum); baum^.wert := 0; new(baum^.links); new(baum^.rechts); baum^.links^.wert := 1; baum^.rechts^.wert := 2; { find element } writeln(enthalten(0, baum)); end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [NFCE_OPERADOR] The MIT License Copyright: Copyright (C) 2014 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 NfceOperadorController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, Generics.Collections, NfceOperadorVO; type TNfceOperadorController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TNfceOperadorVO>; class function ConsultaObjeto(pFiltro: String): TNfceOperadorVO; class function Usuario(pLogin, pSenha: String): TNfceOperadorVO; class procedure Insere(pObjeto: TNfceOperadorVO); class function Altera(pObjeto: TNfceOperadorVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses T2TiORM; class procedure TNfceOperadorController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TNfceOperadorVO>; begin try Retorno := TT2TiORM.Consultar<TNfceOperadorVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TNfceOperadorVO>(Retorno); finally end; end; class function TNfceOperadorController.ConsultaLista(pFiltro: String): TObjectList<TNfceOperadorVO>; begin try Result := TT2TiORM.Consultar<TNfceOperadorVO>(pFiltro, '-1', True); finally end; end; class function TNfceOperadorController.ConsultaObjeto(pFiltro: String): TNfceOperadorVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TNfceOperadorVO>(pFiltro, True); finally end; end; class function TNfceOperadorController.Usuario(pLogin, pSenha: String): TNfceOperadorVO; var Filtro: String; begin try Filtro := 'LOGIN = '+QuotedStr(pLogin)+' AND SENHA = '+QuotedStr(pSenha); Result := TT2TiORM.ConsultarUmObjeto<TNfceOperadorVO>(Filtro, True); finally end; end; class procedure TNfceOperadorController.Insere(pObjeto: TNfceOperadorVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TNfceOperadorController.Altera(pObjeto: TNfceOperadorVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TNfceOperadorController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TNfceOperadorVO; begin try ObjetoLocal := TNfceOperadorVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); TratarRetorno(Result); finally FreeAndNil(ObjetoLocal) end; end; class function TNfceOperadorController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TNfceOperadorController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TNfceOperadorController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TNfceOperadorVO>(TObjectList<TNfceOperadorVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TNfceOperadorController); finalization Classes.UnRegisterClass(TNfceOperadorController); end.
unit DataModul; interface uses SysUtils, Classes, DB, DBTables; type TData = class(TDataModule) TFournisseur: TTable; DFournisseur: TDataSource; TFournisseurORDRE: TStringField; TFournisseurCODE_FOUR: TStringField; TFournisseurNOM_ENTREPRISE: TStringField; TFournisseurSTATUT: TStringField; TFournisseurDOMAINE: TStringField; TFournisseurPRODUITS: TStringField; TFournisseurNOM_FOUR: TStringField; TFournisseurPRENOM_FOUR: TStringField; TFournisseurADRESSE: TMemoField; TFournisseurVILLE: TStringField; TFournisseurTELEPHONE: TStringField; TFournisseurFAX: TStringField; TFournisseurE_MAIL: TStringField; TFournisseurSITE_INTERNET: TStringField; TFournisseurETS_BANCAIRE: TStringField; TFournisseurCPT_BANCAIRE: TStringField; TFournisseurREG_COMMERCE: TStringField; TFournisseurIDENTIFIANT_FISCAL: TStringField; TFournisseurART_IMPOSITION: TStringField; TFournisseurDATE_PRE_CONTACT: TDateField; TFournisseurREMARQUES: TMemoField; TFournisseurMONTANT: TFloatField; procedure DataModuleCreate(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; var Data: TData; implementation {$R *.dfm} procedure TData.DataModuleCreate(Sender: TObject); begin TFournisseur.Open; end; end.
(* Category: SWAG Title: RECORD RELATED ROUTINES Original name: 0002.PAS Description: BLOCKRW2.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:55 *) (* Program to demonstrate BlockRead and BlockWrite *) (* routines. *) Program BlockReadWriteDemo; Uses Crt; Type st20 = String[20]; st40 = String[40]; st80 = String[80]; rcPersonInfo = Record stFirst : st20; stLast : st20; byAge : Byte end; Const coRecSize = sizeof(rcPersonInfo); Var wototalRecs : Word; rcTemp : rcPersonInfo; fiData : File; (***** Initialize Program Variables. *) Procedure Init; begin ClrScr; wototalRecs := 0; fillChar(rcTemp, coRecSize, 0); fillChar(fiData, sizeof(fiData), 0) end; (* Init. *) (***** Handle Program errors. *) Procedure ErrorHandler(byErrorNumber : Byte; boHalt : Boolean); begin Case byErrorNumber of 1 : Writeln('Error creating new data-File.'); 2 : Writeln('Error writing Record to data-File.'); 3 : Writeln('Record does not exist.'); 4 : Writeln('Error reading Record from data-File.'); 5 : Writeln('Error erasing Record in data-File.') end; (* Case byErrorNumber of *) if boHalt then halt(byErrorNumber) end; (* ErrorHandler. *) (***** Create new data-File to hold Record data. *) Function CreateDataFile(Var fiData : File) : Boolean; begin {$I-} reWrite(fiData, 1); {$I+} if (ioresult = 0) then CreateDataFile := True else CreateDataFile := False end; (* CreateDataFile. *) (***** Open data-File. *) Procedure OpenDataFile(Var fiData : File; stFileName : st80); begin assign(fiData, stFileName); {$I-} reset(fiData, 1); {$I+} if (ioresult <> 0) then begin if (CreateDataFile(fiData) = False) then ErrorHandler(1, True) else Writeln('New data-File ', stFileName, ' created.') end else Writeln('Data-File ', stFileName, ' opened.'); wototalRecs := Filesize(fiData) div coRecSize end; (* OpenDataFile. *) (***** Add a Record to the data-File. *) Procedure AddRecord(woRecNum : Word; Var rcTemp : rcPersonInfo); Var woBytesWritten : Word; begin if (woRecNum > succ(wototalRecs)) then woRecNum := succ(wototalRecs); seek(fiData, (pred(woRecNum) * coRecSize)); blockWrite(fiData, rcTemp, coRecSize, woBytesWritten); if (woBytesWritten = coRecSize) then inc(wototalRecs) else ErrorHandler(2, True) end; (* AddRecord. *) (*** PART 2 *****) (***** Get a Record from the data-File. *) Procedure GetRecord(woRecNum : Word; Var rcTemp : rcPersonInfo); Var woBytesRead : Word; begin if (woRecNum > wototalRecs) or (woRecNum < 1) then begin ErrorHandler(3, False); Exit end; seek(fiData, (pred(woRecNum) * coRecSize)); blockread(fiData, rcTemp, coRecSize, woBytesRead); if (woBytesRead <> coRecSize) then ErrorHandler(4, True) end; (* GetRecord. *) (***** Erase the contents of a data-File Record. *) Procedure EraseRecord(woRecNum : Word); Var woBytesWritten : Word; rcEmpty : rcPersonInfo; begin if (woRecNum > wototalRecs) or (woRecNum < 1) then begin ErrorHandler(3, False); Exit end; fillChar(rcEmpty, coRecSize, 0); seek(fiData, (pred(woRecNum) * coRecSize)); blockWrite(fiData, rcEmpty, coRecSize, woBytesWritten); if (woBytesWritten <> coRecSize) then ErrorHandler(5, True) end; (* EraseRecord. *) (***** Display a Record's fields. *) Procedure DisplayRecord(Var rcTemp : rcPersonInfo); begin With rcTemp do begin Writeln; Writeln(' Firstname = ', stFirst); Writeln(' Lastname = ', stLast); Writeln(' Age = ', byAge); Writeln end end; (* DisplayRecord. *) (***** Enter data into a Record. *) Procedure EnterRecData(Var rcTemp : rcPersonInfo); begin Writeln; With rcTemp do begin Write('Enter First-name : '); readln(stFirst); Write('Enter Last-name : '); readln(stLast); Write('Enter Age : '); readln(byAge) end; Writeln end; (* EnterRecData. *) (***** Obtain user response to Yes/No question. *) Function YesNo(stMessage : st40) : Boolean; Var chTemp : Char; begin Writeln; Write(stMessage, ' (Y/N) [ ]', #8#8); While KeyPressed do chTemp := ReadKey; Repeat chTemp := upCase(ReadKey) Until (chTemp in ['Y','N']); Writeln(chTemp); if (chTemp = 'Y') then YesNo := True else YesNo := False end; (* YesNo. *) (***** Compact data-File by removing empty Records. *) Procedure PackDataFile(Var fiData : File); begin (* This one I'm leaving For you to Complete. *) end; (* PackDataFile. *) (***** PART 3 *****) (* Main Program execution block. *) begin Init; OpenDataFile(fiData, 'TEST.DAT'); rcTemp.stFirst := 'Bill'; rcTemp.stLast := 'Gates'; rcTemp.byAge := 36; DisplayRecord(rcTemp); AddRecord(1, rcTemp); rcTemp.stFirst := 'Phillipe'; rcTemp.stLast := 'Khan '; rcTemp.byAge := 39; DisplayRecord(rcTemp); AddRecord(2, rcTemp); GetRecord(1, rcTemp); DisplayRecord(rcTemp); EraseRecord(1); GetRecord(1, rcTemp); DisplayRecord(rcTemp); EnterRecData(rcTemp); AddRecord(1, rcTemp); DisplayRecord(rcTemp); close(fiData); if YesNo('Erase the Record data-File ?') then erase(fiData) end.
unit CatPrefs; { Catarinka Preferences (TCatPreferences) Copyright (c) 2013-2017 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, System.Variants, {$ELSE} Classes, SysUtils, Variants, {$ENDIF} CatJSON; type TCatPreferences = class private fCurrent: TCatJSON; fDefault: TCatJSON; fFilename: string; fLockedOptions: TStringList; fOptionList: TStringList; function Encrypt(const CID: string; const Value: Variant): Variant; function Decrypt(const CID: string; const Value: Variant): Variant; function FGetValue(const CID: string): Variant; function GetCIDList: string; public function GetValue(const CID: string): Variant; overload; function GetValue(const CID: string; const DefaultValue: Variant) : Variant; overload; function GetRegValue(const CID: string; const DefaultValue: Variant): Variant; procedure Lock(const CID: string); procedure SetValue(const CID: string; const Value: Variant); procedure SetValues(const CIDs: array of string; const Value: Variant); procedure LoadFromFile(const f: string); procedure LoadFromString(const s: string); procedure RegisterDefault(const CID: string; const DefaultValue: Variant; const AddToOptionList: boolean = true); procedure RestoreDefaults; procedure SaveToFile(const f: string); constructor Create; destructor Destroy; override; // properties property CIDList: string read GetCIDList; property Current: TCatJSON read fCurrent; property Default: TCatJSON read fDefault; property Filename: string read fFilename write fFilename; property LockedOptions: TStringList read fLockedOptions; property OptionList: TStringList read fOptionList; property Values[const CID: string]: Variant read FGetValue write SetValue; default; end; implementation uses CatDCP, CatStrings, CatDCPKey; function IsEncryptedCID(CID: string): boolean; begin result := false; if endswith(CID, '.password') then result := true else if endswith(CID, '.encrypted') then result := true; end; function TCatPreferences.Encrypt(const CID: string; const Value: Variant): Variant; begin if IsEncryptedCID(CID) then result := strtoaes(Value,GetDCPKey(CATKEY_PASSWORD),false) else result := Value; end; function TCatPreferences.Decrypt(const CID: string; const Value: Variant): Variant; begin if IsEncryptedCID(CID) then result := aestostr(Value,GetDCPKey(CATKEY_PASSWORD),false) else result := Value; end; // Returns the CID of all available options function TCatPreferences.GetCIDList: string; begin result := fOptionList.text; end; function TCatPreferences.FGetValue(const CID: string): Variant; begin result := fCurrent.GetValue(CID, fdefault [CID]); result := Decrypt(CID, result); end; function TCatPreferences.GetValue(const CID: string): Variant; begin result := FGetValue(CID); end; function TCatPreferences.GetValue(const CID: string; const DefaultValue: Variant): Variant; begin result := fCurrent.GetValue(CID, DefaultValue); result := Decrypt(CID, result); end; function TCatPreferences.GetRegValue(const CID: string; const DefaultValue: Variant): Variant; begin RegisterDefault(CID, DefaultValue); result := fCurrent.GetValue(CID, DefaultValue); result := Decrypt(CID, result); end; procedure TCatPreferences.SetValue(const CID: string; const Value: Variant); begin fCurrent[CID] := Encrypt(CID, Value); end; procedure TCatPreferences.SetValues(const CIDs: array of string; const Value: Variant); var X: Byte; begin for X := Low(CIDs) to High(CIDs) do if not (CIDs[X] = '') then SetValue(CIDs[X],Value); end; // Reverts to the default configuration procedure TCatPreferences.RestoreDefaults; begin fCurrent.text := fdefault.text; end; procedure TCatPreferences.RegisterDefault(const CID: string; const DefaultValue: Variant; const AddToOptionList: boolean = true); begin if AddToOptionList then begin if fOptionList.indexof(CID) = -1 then fOptionList.Add(CID); end; fDefault [CID] := DefaultValue; end; procedure TCatPreferences.LoadFromFile(const f: string); begin Filename := f; fCurrent.LoadFromFile(f); end; procedure TCatPreferences.LoadFromString(const s: string); begin if s = emptystr then fCurrent.text := EmptyJSONStr else fCurrent.text := s; end; procedure TCatPreferences.Lock(const CID: string); begin if flockedoptions.IndexOf(CID) = -1 then flockedoptions.Add(CID); end; procedure TCatPreferences.SaveToFile(const f: string); begin fCurrent.SaveToFile(f); end; constructor TCatPreferences.Create; begin inherited Create; fCurrent := TCatJSON.Create; fDefault := TCatJSON.Create; fOptionList := TStringList.Create; fLockedOptions := TStringList.Create; end; destructor TCatPreferences.Destroy; begin fLockedOptions.free; fOptionList.free; fDefault.free; fCurrent.free; inherited; end; end.
{ ID: a_zaky01 PROG: nuggets LANG: PASCAL } const max=65536; var n,i,j,ans,gcd0:longint; a:array[1..10] of integer; stat:array[0..max] of boolean; fin,fout:text; function gcd(a,b:longint):longint; begin if a<b then gcd:=gcd(b,a) else if b=0 then gcd:=a else gcd:=gcd(b,a mod b); end; begin assign(fin,'nuggets.in'); assign(fout,'nuggets.out'); reset(fin); rewrite(fout); readln(fin,n); for i:=1 to n do readln(fin,a[i]); gcd0:=0; for i:=1 to n do gcd0:=gcd(gcd0,a[i]); if gcd0>1 then writeln(fout,0) else begin ans:=0; stat[0]:=true; for i:=1 to n do for j:=a[i] to max do stat[j]:=stat[j] or stat[j-a[i]]; for i:=max downto 1 do if not stat[i] then begin ans:=i; break; end; writeln(fout,ans); end; close(fin); close(fout); end.
unit PointerscanresultReader; {$MODE Delphi} { The TPointerscanresultReader will read the results from the pointerfile and present them to the pointerscanner as if it is just one file } interface {$ifdef darwin} uses macport, MacTypes, LCLIntf, sysutils, classes, CEFuncProc, NewKernelHandler, symbolhandler, math, dialogs, LazUTF8,macportdefines; {$endif} {$ifdef windows} uses windows, LCLIntf, sysutils, classes, CEFuncProc, NewKernelHandler, symbolhandler, math, dialogs, LazUTF8; {$endif} resourcestring rsPSRCorruptedPointerscanFile = 'Corrupted pointerscan file'; rsPSRInvalidPointerscanFileVersion = 'Invalid pointerscan file version'; rsBuggedList = 'BuggedList'; {$ifdef windows} function GetFileSizeEx(hFile:HANDLE; FileSize:PQWord):BOOL; stdcall; external 'kernel32.dll' name 'GetFileSizeEx'; {$endif} type TPointerscanResult=packed record modulenr: integer; moduleoffset: int64; offsetcount: integer; offsets: array [0..1000] of integer; end; type PPointerscanResult= ^TPointerscanResult; type TPointerscanresultReader=class; TPointerscanresultReader=class private Fcount: qword; sizeOfEntry: integer; maxlevel: integer; modulelist: tstringlist; FFileName: widestring; files: array of record startindex: qword; lastindex: qword; filename: widestring; filesize: qword; f,fm: Thandle; end; cacheStart: integer; cacheSize: size_t; cache: pointer; cacheStart2: integer; cacheSize2: integer; cache2: pointer; fExternalScanners: integer; fGeneratedByWorkerID: integer; fCompressedPtr: boolean; fAligned: boolean; MaskModuleIndex: dword; MaskLevel: dword; MaskOffset: dword; fMaxBitCountModuleIndex: dword; fMaxBitCountModuleOffset: dword; fMaxBitCountLevel: dword; fMaxBitCountOffset: dword; fEndsWithOffsetList: array of dword; fCanResume: boolean; fdidBaseRangeScan: boolean; foriginalBaseScanRange: qword; CompressedPointerScanResult: PPointerscanResult; compressedTempBuffer: PByteArray; fLastRawPointer: pointer; fmergedresults: array of integer; function InitializeCache(i: qword): boolean; function getModuleListCount: integer; function getMergedResultCount: integer; function getMergedResult(index: integer): integer; function getEndsWithOffsetListCount: integer; function getEndsWithOffsetListEntry(index: integer): dword; public procedure resyncModulelist; procedure saveModulelistToResults(s: Tstream); function getModulename(modulenr: integer): string; function getModuleBase(modulenr: integer): ptrUint; procedure setModuleBase(modulenr: integer; newModuleBase: ptruint); function getPointer(i: qword): PPointerscanResult; overload; function getPointer(i: qword; var pointsto: ptrUint): PPointerscanResult; overload; procedure getFileList(list: TStrings); procedure ReleaseFiles; constructor create(filename: widestring; original: TPointerscanresultReader=nil); destructor destroy; override; property count: qword read FCount; property offsetCount: integer read maxlevel; property filename: widestring read FFilename; property entrySize: integer read sizeOfEntry; property modulelistCount: integer read getModuleListcount; property modulename[index: integer]: string read getModuleName; property modulebase[index: integer]: ptruint read getModuleBase write setModuleBase; property mergedresultcount: integer read getMergedResultCount; property mergedresults[index: integer]: integer read getMergedResult; property EndsWithOffsetListCount: integer read getEndsWithOffsetListCount; property EndsWithOffsetList[index: integer]: dword read getEndsWithOffsetListEntry; property compressedptr: boolean read fCompressedPtr; property aligned: boolean read fAligned; property MaxBitCountModuleIndex: dword read fMaxBitCountModuleIndex; property MaxBitCountModuleOffset: dword read fMaxBitCountModuleOffset; property MaxBitCountLevel: dword read fMaxBitCountLevel; property MaxBitCountOffset: dword read fMaxBitCountOffset; property LastRawPointer: pointer read fLastRawPointer; property CanResume: boolean read fCanResume; property DidBaseRangeScan: boolean read fdidBaseRangeScan; property BaseScanRange: qword read foriginalBaseScanRange; end; procedure findAllResultFilesForThisPtr(filename: string; rs: TStrings; lookupmode: integer=0); implementation uses ProcessHandlerUnit, PointerscanStructures, Maps, AvgLvlTree; procedure findAllResultFilesForThisPtr(filename: string; rs: TStrings; lookupmode: integer=0); var fr: TRawbyteSearchRec; i,j: integer; ext1, ext2: string; basesort: boolean; v1, v2: int64; sepindex: integer; temp: string; swap: boolean; filemap: TMap; f: string; fn: pchar; path: string; it: TMapIterator; begin //search the folder this ptr file is in for .result.* files //extract1 rs.clear; filemap:=TMap.Create(its8, sizeof(pointer)); if lookupmode=1 then filename:=UTF8ToWinCP(filename); path:=ExtractFilePath(filename); if FindFirst(filename+'.results.*', 0, fr)=0 then begin repeat ext1:=ExtractFileExt(fr.name); ext1:=copy(ext1, 2, length(ext1)-1); if copy(ext1,1,5)='child' then begin rs.add(path+fr.name); //no need to sort end else if TryStrToInt64('$'+ext1, v1) then begin f:=path+fr.name; getmem(fn, length(f)+1); strcopy(fn, @f[1]); filemap.Add(v1, fn); end; until FindNext(fr)<>0; FindClose(fr); end else begin if lookupmode<1 then begin findAllResultFilesForThisPtr(filename, rs, lookupmode+1); exit; end; end; it:=TMapIterator.Create(filemap); it.First; while not it.EOM do begin it.GetData(fn); rs.add(fn); freememandnil(fn); it.Next; end; it.free; filemap.Clear; freeandnil(filemap); end; function TPointerscanresultreader.getMergedResultCount: integer; begin result:=length(fmergedresults); end; function TPointerscanresultreader.getMergedResult(index: integer): integer; begin if index<mergedresultcount then result:=fmergedresults[index] else result:=-1; end; function TPointerscanresultreader.getEndsWithOffsetListCount: integer; begin result:=length(fEndsWithOffsetList); end; function TPointerscanresultreader.getEndsWithOffsetListEntry(index: integer): dword; begin result:=fEndsWithOffsetList[index] end; procedure TPointerscanresultreader.resyncModulelist; var tempmodulelist: TStringList; i,j: integer; begin tempmodulelist:=tstringlist.Create; try symhandler.getModuleList(tempmodulelist); //sift through the list filling in the modulelist of the opened pointerfile for i:=0 to modulelist.Count-1 do begin j:=tempmodulelist.IndexOf(modulelist[i]); if j<>-1 then modulelist.Objects[i]:=tempmodulelist.Objects[j] else begin try modulelist.Objects[i]:=pointer(symhandler.getAddressFromName(modulelist[i])); except modulelist.Objects[i]:=nil; end; end; end; finally tempmodulelist.free; end; end; procedure TPointerscanresultReader.saveModuleListToResults(s: TStream); var i: integer; x: dword; begin //save the number of modules x:=modulelist.Count; s.Write(x,sizeof(x)); for i:=0 to modulelist.Count-1 do begin //for each module //save the length x:=length(modulelist[i]); s.Write(x,sizeof(x)); //and the name s.Write(modulelist[i][1],x); //and the base (for debugging info) s.WriteQWord(qword(modulelist.Objects[i])); end; end; function TPointerscanresultReader.InitializeCache(i: qword): boolean; var j: integer; actualread: dword; wantedoffset: qword; offset: qword; begin result:=false; // OutputDebugString('InitializeCache'); if i>=fcount then exit; //find which file to use for j:=0 to length(files)-1 do begin if InRangeQ(i, files[j].startindex, files[j].lastindex) then begin wantedoffset:=int64(sizeOfEntry*(i-files[j].startindex)); if (wantedoffset mod systeminfo.dwAllocationGranularity)<>0 then begin //bring offset down to a location matching systeminfo.dwAllocationGranularity offset:=wantedoffset-(wantedoffset mod systeminfo.dwAllocationGranularity); end else offset:=wantedoffset; {$if FPC_FULLVERSION<30200} cachesize:=min(files[j].filesize-offset, systeminfo.dwAllocationGranularity*32); //normally 2MBZ {$else} cachesize:=min(files[j].filesize-offset, qword(systeminfo.dwAllocationGranularity*32)); //normally 2MBZ {$endif} if cache2<>nil then unmapviewoffile(cache2); cache2:=MapViewOfFile(files[j].fm, FILE_MAP_READ, offset shr 32, offset and $ffffffff, cachesize ); // if cache2=nil then // OutputDebugString('Failure to map view of file'); //point cache to the start of the wanted offset cache:=pointer(ptruint(cache2)+(wantedoffset-offset)); cachesize:=(cachesize-(wantedoffset-offset)) div sizeofentry; result:=cache2<>nil; // OutputDebugString('InitializeCache success'); exit; end; end; //nothing found... // OutputDebugString('InitializeCache nothing found'); end; function TPointerscanresultReader.getModuleListCount: integer; begin result:=modulelist.count; end; function TPointerscanresultReader.getModuleBase(modulenr: integer): ptrUint; {pre: modulenr must be valid, so not -1 } begin if (modulenr>=0) and (modulenr<modulelist.Count) then result:=ptrUint(modulelist.Objects[modulenr]) else result:=0; end; procedure TPointerscanresultReader.setModuleBase(modulenr: integer; newModuleBase: ptruint); begin if (modulenr>=0) and (modulenr<modulelist.Count) then modulelist.objects[modulenr]:=pointer(newModulebase); end; function TPointerscanresultReader.getModulename(modulenr: integer): string; begin if (modulenr>=0) and (modulenr<modulelist.Count) then result:=modulelist[modulenr] else result:=rsBuggedList; end; function TPointerscanresultReader.getPointer(i: uint64): PPointerscanResult; { for those that know what they want } var cachepos: integer; p: PByteArray; bit: integer; j: integer; begin result:=nil; if i>=count then exit; //check if i is in the cache if not InRange(i, cachestart,cachestart+cachesize-1) then begin //if not, reload the cache starting from i if not InitializeCache(i) then exit; cachestart:=i; end; //find out at which position in the cache this index is cachepos:=i-cachestart; if fCompressedPtr then begin p:=PByteArray(ptrUint(cache)+(cachepos*sizeofentry)); CopyMemory(compressedTempBuffer, p, sizeofentry); if MaxBitCountModuleOffset=32 then //only 2 possibilities compressedPointerScanResult.moduleoffset:=PInteger(compressedTempBuffer)^ else compressedPointerScanResult.moduleoffset:=PInt64(compressedTempBuffer)^; bit:=MaxBitCountModuleOffset; compressedPointerScanResult.modulenr:=pdword(@compressedTempBuffer[bit shr 3])^; compressedPointerScanResult.modulenr:=compressedPointerScanResult.modulenr and MaskModuleIndex; if compressedPointerScanResult.modulenr shr (fMaxBitCountModuleIndex-1) = 1 then //most significant bit is set, sign extent this value begin //should be -1 as that is the only one possible dword(compressedPointerScanResult.modulenr):=dword(compressedPointerScanResult.modulenr) or (not MaskModuleIndex); if compressedPointerScanResult.modulenr<>-1 then begin //my assumption was wrong compressedPointerScanResult.modulenr:=-1; end; end; inc(bit, fMaxBitCountModuleIndex); { compressedPointerScanResult.offsetcount:=pdword(@compressedTempBuffer[bit div 8])^; compressedPointerScanResult.offsetcount:=compressedPointerScanResult.offsetcount shr (bit mod 8); compressedPointerScanResult.offsetcount:=compressedPointerScanResult.offsetcount and MaskLevel; } compressedPointerScanResult.offsetcount:=(pdword(@compressedTempBuffer[bit shr 3])^ shr (bit and $7)) and MaskLevel; inc(compressedPointerScanResult.offsetcount, length(fEndsWithOffsetList)); inc(bit, fMaxBitCountLevel); for j:=0 to length(fEndsWithOffsetList)-1 do compressedPointerScanResult.offsets[j]:=fEndsWithOffsetList[j]; for j:=length(fEndsWithOffsetList) to compressedPointerScanResult.offsetcount-1 do begin { compressedPointerScanResult.offsets[j]:=pdword(@compressedTempBuffer[bit div 8])^; compressedPointerScanResult.offsets[j]:=compressedPointerScanResult.offsets[j] shr (bit mod 8); compressedPointerScanResult.offsets[j]:=compressedPointerScanResult.offsets[j] and MaskOffset; if aligned then compressedPointerScanResult.offsets[j]:=compressedPointerScanResult.offsets[j] shl 2; } if aligned then compressedPointerScanResult.offsets[j]:=((pdword(@compressedTempBuffer[bit shr 3])^ shr (bit and $7) ) and MaskOffset) shl 2 else compressedPointerScanResult.offsets[j]:=(pdword(@compressedTempBuffer[bit shr 3])^ shr (bit and $7) ) and MaskOffset; inc(bit, fMaxBitCountOffset); end; result:=compressedPointerScanResult; fLastRawPointer:=compressedTempBuffer; end else begin result:=PPointerscanResult(ptrUint(cache)+(cachepos*sizeofentry)); fLastRawPointer:=result; end; end; function TPointerscanresultReader.getPointer(i: qword; var pointsto: ptrUint): PPointerscanResult; { For use for simple display } var x: ptruint; address,address2: ptrUint; j: integer; begin result:=getpointer(i); address:=0; address2:=0; //resolve the pointer pointsto:=0; if result.modulenr=-1 then address:=result.moduleoffset else begin if result.modulenr<modulelist.count then begin address:=ptruint(modulelist.objects[result.modulenr]); address:=address+result.moduleoffset; end else begin //error. Should never happen address:=$12345678; end; end; for j:=result.offsetcount-1 downto 0 do begin if readprocessmemory(processhandle, pointer(address), @address2, processhandler.pointersize, x) then address:=address2+result.offsets[j] else exit; //can't fully resolve end; pointsto:=address; end; procedure TPointerscanresultReader.getFileList(list: TStrings); var i: integer; begin for i:=0 to length(files)-1 do list.add(files[i].FileName); end; constructor TPointerscanresultReader.create(filename: widestring; original: TPointerscanresultReader=nil); var configfile: TFileStream; modulelistLength: integer; tempmodulelist: Tstringlist; x: dword; i,j: integer; temppchar: pchar; temppcharmaxlength: dword; filenamecount: integer; error: boolean; a: ptruint; fn: widestring; filenames: array of widestring; fnames: tstringlist; pscanversion: byte; begin FFilename:=filename; configfile:=TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite); if configfile.ReadByte<>$ce then raise exception.create(rsPSRCorruptedPointerscanFile); pscanversion:=configfile.ReadByte; if pscanversion>pointerscanfileversion then raise exception.create(rsPSRInvalidPointerscanFileVersion); configfile.ReadBuffer(modulelistlength,sizeof(modulelistlength)); modulelist:=tstringlist.create; tempmodulelist:=tstringlist.create; temppcharmaxlength:=256; getmem(temppchar, temppcharmaxlength); //get the module list myself if original=nil then symhandler.getModuleList(tempmodulelist) else modulelist.Assign(original.modulelist); //sift through the list filling in the modulelist of the opened pointerfile for i:=0 to modulelistlength-1 do begin configfile.Read(x,sizeof(x)); while x>=temppcharmaxlength do begin temppcharmaxlength:=temppcharmaxlength*2; ReallocMem(temppchar, temppcharmaxlength); end; configfile.Read(temppchar[0], x); temppchar[x]:=#0; a:=configfile.ReadQWord; //discard this info (only used for scandata) if original=nil then begin j:=tempmodulelist.IndexOf(temppchar); if j<>-1 then modulelist.Addobject(temppchar, tempmodulelist.Objects[j]) //add it and store the base address else begin a:=symhandler.getAddressFromName(temppchar,false,error,nil); if not error then modulelist.Addobject(temppchar, pointer(a)) else modulelist.Add(temppchar); end; end; end; //read maxlevel configfile.Read(maxlevel,sizeof(maxlevel)); //read compressedptr info fCompressedPtr:=configfile.ReadByte=1; if fCompressedPtr then begin fAligned:=configFile.ReadByte=1; fMaxBitCountModuleIndex:=configfile.ReadByte; fMaxBitCountModuleOffset:=configfile.ReadByte; fMaxBitCountLevel:=configfile.ReadByte; fMaxBitCountOffset:=configfile.ReadByte; setlength(fEndsWithOffsetList, configfile.ReadByte); for i:=0 to length(fEndsWithOffsetList)-1 do fEndsWithOffsetList[i]:=configfile.ReadDWord; sizeofentry:=MaxBitCountModuleOffset+MaxBitCountModuleIndex+MaxBitCountLevel+MaxBitCountOffset*(maxlevel-length(fEndsWithOffsetList)); sizeofentry:=(sizeofentry+7) div 8; MaskModuleIndex:=0; for i:=1 to MaxBitCountModuleIndex do MaskModuleIndex:=(MaskModuleIndex shl 1) or 1; for i:=1 to MaxBitCountLevel do MaskLevel:=(MaskLevel shl 1) or 1; for i:=1 to MaxBitCountOffset do MaskOffset:=(MaskOffset shl 1) or 1; getmem(CompressedPointerScanResult, 16+4*maxlevel); getmem(CompressedTempBuffer, sizeofentry+4); end else begin sizeofentry:=16+(4*maxlevel) end; if pscanversion>=2 then begin fdidBaseRangeScan:=configFile.readByte=1; if fdidBaseRangeScan then foriginalBaseScanRange:=configfile.ReadQWord; end; //get the filenames fnames:=tstringlist.create; findAllResultFilesForThisPtr(filename, fnames); setlength(filenames, fnames.count); for i:=0 to fnames.count-1 do filenames[i]:=fnames[i]; fnames.free; setlength(files, length(filenames)); j:=0; for i:=0 to length(filenames)-1 do begin try if pos(PathDelim, filenames[i])=0 then fn:=ExtractFilePath(filename)+filenames[i] else fn:=filenames[i]; files[j].filename:=fn; files[j].f:=CreateFileW(pwchar(fn), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_DELETE, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0); if (files[j].f<>0) and (files[j].f<>INVALID_HANDLE_VALUE) then begin files[j].startindex:=fcount; if GetFileSizeEx(files[j].f, @files[j].filesize)=false then begin OutputDebugString('GetFileSizeEx failed with error: '+inttostr(GetLastError)); end; if files[j].filesize>0 then begin fcount:=fcount+uint64(files[j].filesize div uint64(sizeofentry)); files[j].lastindex:=fcount-1; files[j].fm:=CreateFileMapping(files[j].f, nil,PAGE_READONLY, 0,0,nil); end else files[j].fm:=0; if (files[j].fm=0) then closehandle(files[j].f) else inc(j); end; except end; end; setlength(files,j); // getmem(cache, sizeofEntry*maxcachecount); // getmem(cache2, sizeofEntry*maxcachecount); InitializeCache(0); freememandnil(temppchar); configfile.Free; fCanResume:=fileexists(filename+'.resume.config') and fileexists(filename+'.resume.scandata') and fileexists(filename+'.resume.queue'); if length(filenames)=0 then MessageDlg('There was an error loading the results. Check that the path is readable', mtError, [mbok],0); end; procedure TPointerscanresultReader.ReleaseFiles; //if only the config file is needed. This releases the results var i: integer; begin for i:=0 to length(files)-1 do if files[i].f<>0 then begin if files[i].fm<>0 then closehandle(files[i].fm); closehandle(files[i].f); end; end; destructor TPointerscanresultReader.destroy; var i: integer; begin if modulelist<>nil then modulelist.free; if cache2<>nil then UnmapViewOfFile(cache2); ReleaseFiles; if compressedTempBuffer<>nil then freememandnil(compressedTempBuffer); if compressedPointerScanResult<>nil then freememandnil(compressedPointerScanResult); end; end.
unit DmRtcCustom; interface uses SysUtils, Classes, rtcFunction, rtcSrvModule, rtcInfo, rtcConn, rtcDataSrv, Generics.Collections, SQLTableProperties, Variants, uRtcDmList, DB, rtcSyncObjs, fbApiQuery, IB; type TRtcCustomDm = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } // FUserList: TRemoteUserList; FCs: TRtcCritSec; protected class var FRtcServer: TRtcDataServer; procedure RegisterRtcFunction(const aname: String; FExecute: TRtcFunctionCallEvent); function GetDefaultGroup: TRtcFunctionGroup; virtual; public { Public declarations } function GetDmMainUib(AConnection: TRtcConnection): TDataModule; // procedure AddUser(const AUserInfo:PUserInfo; ARtcConnect:TRtcConnection);virtual; // procedure DeleteUser(ARtcConnect:TRtcConnection);virtual; property CriticalSection: TRtcCritSec read FCs; procedure CsLock; procedure CsUnlock; function RTC_FBAPI2FIELD_TYPE(nType: Cardinal; nSubType: Integer; Scale: Integer): TRtcFieldTypes; procedure QueryToRtc(AQuery: TFbApiQuery; rtcDS: TRtcDataSet; ClearFieldDefs: boolean = True; OnlyDataFields: boolean = True); // procedure bindRtcServer(const Value: TRtcDataServer);virtual; procedure SetRtcServer(const Value: TRtcDataServer);virtual; end; // function GetDataSetFieldType(AResult:TSQlResult; AIndex: Integer):TFieldType; var RtcCustomDm: TRtcCustomDm; implementation {$R *.dfm} { TDmRtcCustom } { procedure TDmRtcCustom.AddUser(const AUserInfo:PUserInfo; ARtcConnect: TRtcConnection); var p:PUserListItem; begin FCs.Acquire; try New(p); p.RtcConnect := ArtcConnect; p.UserInfo := AUserInfo; FUserList.Add(p); finally FCs.Release; end; end; procedure TDmRtcCustom.DeleteUser(ARtcConnect:TRtcConnection); var i: Integer; begin for I := 0 to FUserList.Count-1 do begin if FUserList[i].RtcConnect=ARtcConnect then begin Dispose(FUserList[i].UserInfo); FUserList.Delete(i); Break; end; end; end; } procedure TRtcCustomDm.CsLock; begin FCs.Acquire; end; procedure TRtcCustomDm.CsUnlock; begin FCs.Release; end; procedure TRtcCustomDm.DataModuleCreate(Sender: TObject); begin FCs := TRtcCritSec.Create; if Assigned(FRtcServer) then SetRtcServer(FRtcServer); end; procedure TRtcCustomDm.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FCs); Inherited; end; function TRtcCustomDm.GetDefaultGroup: TRtcFunctionGroup; var component: TComponent; i: Integer; begin Result := nil; for i:=0 to ComponentCount-1 do begin component := Components[i]; if component is TRtcFunctionGroup then begin Result := TRtcFunctionGroup(component); Exit; end; end; end; function TRtcCustomDm.GetDmMainUib(AConnection: TRtcConnection): TDataModule; begin Result := RtcDmList.GetDmOnRtc(AConnection, TDataModule); end; procedure TRtcCustomDm.RegisterRtcFunction(const aname: String; FExecute: TRtcFunctionCallEvent); var mRtcFunction: TRtcFunction; begin mRtcFunction := TRtcFunction.Create(self); with mRtcFunction do begin FunctionName := aname; Group := GetDefaultGroup; OnExecute := FExecute; end; end; function TRtcCustomDm.RTC_FBAPI2FIELD_TYPE(nType: Cardinal; nSubType: Integer; Scale: Integer ): TRtcFieldTypes; begin case nType of SQL_VARYING, SQL_TEXT: Result := ft_String; SQL_DOUBLE, SQL_FLOAT: Result := ft_Float; SQL_LONG: Result := ft_Integer; SQL_SHORT: Result := ft_Smallint; SQL_TIMESTAMP: Result := ft_DateTime; SQL_BLOB: if nSubType=1 then Result := ft_Memo else Result := ft_Blob; SQL_D_FLOAT: Result := ft_BCD; SQL_ARRAY: Result := ft_Array; SQL_QUAD: Result := ft_Largeint; SQL_TYPE_TIME: Result := ft_Time; SQL_TYPE_DATE: Result := ft_Date; SQL_INT64: case Scale of 0: Result := ft_Largeint; -2: Result := ft_Currency; else Result := ft_Float; end; SQL_BOOLEAN: Result := ft_Boolean; // SQL_DATE: Result := ftDateTime; SQL_DECFLOAT16: Result := ft_BCD; SQL_DECFLOAT34: Result := ft_BCD; end; end; procedure TRtcCustomDm.SetRtcServer(const Value: TRtcDataServer); var i: Integer; begin if not Assigned(FRtcServer) then FRtcServer := Value; for i := 0 to ComponentCount-1 do begin if (Components[i] is TRtcDataServerLink) and (Components[i] <> self) then TRtcDataServerLink(Components[i]).Server := FRtcServer; end; end; procedure TRtcCustomDm.QueryToRtc(AQuery: TFbApiQuery; rtcDS: TRtcDataSet; ClearFieldDefs: boolean = True; OnlyDataFields: boolean = True); var flds: integer; fldname: string; //field: ISQLData; fstream: TStream; fbtype: Cardinal; FldType: TRtcFieldTypes; scale: Integer; begin if ClearFieldDefs then begin rtcDS.Clear; for flds := 0 to AQuery.FieldCount - 1 do begin fbtype := AQuery.FieldsMetadata[flds].SQLType; fldname := AQuery.FieldsMetadata[flds].Name; // field := AQuery.Fields[flds]; if fldname <> '' then begin FldType := RTC_FBAPI2FIELD_TYPE(fbtype, AQuery.FieldsMetadata[flds].SQLSubtype, AQuery.FieldsMetadata[flds].Scale); rtcDS.SetField(fldname, FldType, AQuery.FieldsMetadata[flds].Size); end; end; end; while not AQuery.EOF do begin rtcDS.Append; for flds := 0 to rtcDS.FieldCount - 1 do begin fbtype := AQuery.Fields[flds].SQLType; fldname := AQuery.Fields[flds].Name; scale := AQuery.Fields[flds].Scale; if (AQuery.Fields[flds].isNull) then rtcDS.asValue[fldname] := null else begin case fbtype of SQL_VARYING, SQL_TEXT: rtcDS.asWideString[fldname]:= AQuery.Fields[flds].AsVariant; SQL_DOUBLE, SQL_FLOAT: rtcDS.asFloat[fldname] := AQuery.Fields[flds].AsFloat; SQL_LONG: rtcDS.asInteger[fldname] := AQuery.Fields[flds].AsInteger; SQL_SHORT: rtcDS.asInteger[fldname] := AQuery.Fields[flds].AsShort; SQL_TIMESTAMP: rtcDS.asDatetime[fldname] := AQuery.Fields[flds].AsDateTime; SQL_BLOB: //if AQuery.Fields[flds].SQLSubtype = 1 then rtcDS.AsWideString[fldname] := AQuery.Fields[flds].AsBlob.AsString; // SQL_D_FLOAT: rtcDS.Value[fldName].AsBCD := AQuery.Fields[flds].AsBCD; // SQL_ARRAY: // rtcDS.asArray[fldname] := AQuery.Fields[flds].AsArray; SQL_QUAD: rtcDS.asLargeInt[fldname] := AQuery.Fields[flds].AsInt64; SQL_TYPE_TIME: rtcDS.asDateTime[fldname] := AQuery.Fields[flds].AsTime; SQL_TYPE_DATE: rtcDS.asDateTime[fldname] := AQuery.Fields[flds].AsDate; SQL_INT64: case Scale of 0: rtcDS.asLargeInt[fldname] := AQuery.Fields[flds].AsInt64; -2: rtcDS.asCurrency[fldname] := AQuery.Fields[flds].AsCurrency; else rtcDS.asFloat[fldname] := AQuery.Fields[flds].AsFloat; end; SQL_BOOLEAN: rtcDS.asBoolean[fldname] := AQuery.Fields[flds].AsBoolean; // SQL_DATE: Result := ftDateTime; // SQL_DECFLOAT16: rtcDS.Value[fldName].AsBCD := AQuery.Fields[flds].AsBCD; // SQL_DECFLOAT34: rtcDS.Value[fldName].AsBCD := AQuery.Fields[flds].AsBCD; end; end; end; AQuery.Next; end; end; end. procedure UIBQueryToRtc (AUibQuery: TUIBQuery; rtcDS: TRtcDataSet; ClearFieldDefs: boolean = True; OnlyDataFields: boolean = True); var flds: integer; fldname: string; field: TSQLDA; fstream: TStream; uibtype: TUIBFieldType; begin if ClearFieldDefs then begin rtcDS.Clear; for flds := 0 to AUibQuery.Fields.FieldCount - 1 do begin uibtype := AUibQuery.Fields.FieldType[flds]; fldname := AUibQuery.Fields.AliasName[flds]; if fldname <> '' then begin rtcDS.SetField(fldname, RTC_UIB2FIELD_TYPE(GetDataSetFieldType(uibtype) ), field.Size, field.Required); end; end; while not AUibQuery.EOF do begin rtcDS.Append; for flds := 0 to rtcDS.FieldCount - 1 do begin fldname := rtcDS.FieldName[flds]; if AUibQuery.Fields.isBlob[flds] then begin { begin fstream:=DelphiDS.CreateBlobStream(field,bmRead); try ( (field.DataType = ftGraphic) or (field.DataType = ftTypedBinary) ) then RtcSkipGraphicFieldHeader(fstream); rtcDS.NewByteStream(fldname).CopyFrom(fstream,fstream.Size-fstream.Position); finally fstream.Free; end; end else } end else begin case RTC_FIELD2VALUE_TYPES[rtcDS.FieldType[fldname]] of rtc_Currency: rtcDS.asCurrency[fldname] := AUibQuery.Fields.asCurrency[flds]; rtc_DateTime: rtcDS.AsDateTime[fldname] := AUibQuery.Fields.AsDateTime[flds]; rtc_String: rtcDS.AsString[fldname] := RtcString(AUibQuery.Fields.AsString[flds]); // rtc_Text: rtcDS.asText[fldname]:=field.AsWideString; else rtcDS.Value[fldname] := AUibQuery.Fields.AsVariant[flds]; end; end; end; end; AUibQuery.Next; end; end; procedure DelphiFieldsToRtc(const DelphiDS: TDataSet; const rtcDS: TRtcDataSet); var flds: integer; fldname: string; field: TField; begin for flds := 0 to DelphiDS.Fields.Count - 1 do begin field := DelphiDS.Fields[flds]; if assigned(field) then begin fldname := field.FieldName; if field.FieldKind = fkData then rtcDS.SetField(fldname, RTC_DB2FIELD_TYPE(field.DataType), field.Size, field.Required); end; end; end; procedure DelphiRowToRtc(const DelphiDS: TDataSet; const rtcDS: TRtcDataSet); var flds: integer; fldname: string; field: TField; fstream: TStream; begin rtcDS.Append; for flds := 0 to rtcDS.FieldCount - 1 do begin fldname := rtcDS.FieldName[flds]; field := DelphiDS.FindField(fldname); if assigned(field) then if (field.FieldKind = fkData) and not field.IsNull then if field.isBlob then begin fstream := DelphiDS.CreateBlobStream(field, bmRead); try if {$IFNDEF FPC} TBlobField(field).GraphicHeader and {$ENDIF} ((field.DataType = ftGraphic) or (field.DataType = ftTypedBinary)) then RtcSkipGraphicFieldHeader(fstream); rtcDS.NewByteStream(fldname).CopyFrom(fstream, fstream.Size - fstream.Position); finally fstream.Free; end; end else case RTC_FIELD2VALUE_TYPES[rtcDS.FieldType[fldname]] of rtc_Currency: rtcDS.asCurrency[fldname] := field.asCurrency; rtc_DateTime: rtcDS.AsDateTime[fldname] := field.AsDateTime; rtc_String: rtcDS.AsString[fldname] := RtcString(field.AsString); // rtc_Text: rtcDS.asText[fldname]:=field.AsWideString; else rtcDS.Value[fldname] := field.Value; end; end; end; function GetDataSetFieldType(AResult: TSQlResult; AIndex: integer): TFieldType; var i: integer; DataType: TFieldType; begin case AResult.FieldType[AIndex] of uftNumeric: begin case AResult.SQLType[i] of SQL_SHORT: begin DataType := ftBCD; end; SQL_LONG: begin DataType := ftFMTBcd end; SQL_INT64, SQL_QUAD: begin DataType := ftFMTBcd else // DataType := ftBCD; end; SQL_D_FLOAT, SQL_DOUBLE: DataType := ftFloat; // possible end; end; uftChar, uftCstring, uftVarchar: begin DataType := ftWideString; end; uftSmallint: DataType := ftSmallint; uftInteger: DataType := ftInteger; uftFloat, uftDoublePrecision: DataType := ftFloat; uftTimestamp: DataType := ftDateTime; uftBlob, uftBlobId: begin if AResult.IsBlobText[AIndex] then DataType := ftWideMemo else DataType := ftBlob; end; uftDate: DataType := ftDate; uftTime: DataType := ftTime; uftInt64: DataType := ftLargeint; uftBoolean: DataType := ftBoolean; else DataType := ftUnknown; end; end; finally end; end;
unit UnitWorkSpace; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, stdActns,BCEditor.Editor.Base, System.IniFiles, System.IOUtils, System.StrUtils; type TFormWorkspace = class(TForm) Label1: TLabel; Label2: TLabel; ComboBoxWorkspace: TComboBox; Browse: TButton; ButtonOK: TButton; ButtonCancel: TButton; Label3: TLabel; procedure ButtonCancelClick(Sender: TObject); procedure BrowseClick(Sender: TObject); procedure ButtonOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormWorkspace: TFormWorkspace; dir :string; myFile : TextFile; implementation uses UnitCodeGenerator; {$R *.dfm} procedure TFormWorkspace.BrowseClick(Sender: TObject); begin with TBrowseForFolder.Create(nil) do try RootDir := 'This PC'; if Execute then begin dir := Folder; ComboBoxWorkspace.Text := dir; end; finally Free; end; end; procedure TFormWorkspace.ButtonCancelClick(Sender: TObject); begin Self.Close; end; procedure TFormWorkspace.ButtonOKClick(Sender: TObject); var text : string; IsDup : Boolean; begin //check duplicate before save to file AssignFile(myFile, 'workspace.rany'); ReSet(myFile); IsDup := False; while not eof(myFile) do begin ReadLn(myFile, text); if text = ComboBoxWorkspace.Text then begin IsDup := True; break; end; end; if IsDup <> true then begin Append(myFile); Writeln(myFile, ComboBoxWorkspace.Text); end; //write the last selected workspace ProjectSetting.WriteString('Workspace', 'WorkspacePath', ComboBoxWorkspace.Text); EZCodeGenerator.TreeViewProjectExplorer.RootedAtFileSystemFolder := ProjectSetting.ReadString('Workspace', 'WorkspacePath', ''); CloseFile(myFile); //clear BCeditor and hide tab EZCodeGenerator.BCEditorCodePreview.Clear; EZCodeGenerator.BCEditorProjCode.Clear; EZCodeGenerator.RzPageControlMain.Visible := False; TDirectory.Copy(GetCurrentDir + '\Template\common', ComboBoxWorkspace.Text + '\common'); TDirectory.SetAttributes(ComboBoxWorkspace.Text + '\common',[TFileAttribute.faHidden, TFileAttribute.faReadOnly]); Self.Close; end; procedure TFormWorkspace.FormCreate(Sender: TObject); var text : string; begin //read workspace history from file AssignFile(myFile, 'workspace.rany'); ReSet(myFile); while not eof(myFile) do begin ReadLn(myFile, text); if TDirectory.Exists(text) then ComboBoxWorkspace.Items.Insert(0, text); end; ComboBoxWorkspace.ItemIndex := 0; CloseFile(myFile); end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. } { Description: base64 and base32 encoding/decond functions } unit helper_base64_32; interface uses sysutils,const_ares; function Encode3to4(const Value, Table: string): string; function EncodeBase64(const Value: string): string; function DecodeBase64(const Value: string): string; function Decode4to3Ex(const Value, Table: string): string; function EncodeBase32(strin:string):string; function DecodeBase32(strin:string):string; implementation function DecodeBase32(strin:string):string; var base32Chars,stringa:string; i,index,offset:integer; words:byte; begin if length(strin)<32 then exit; base32Chars:='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; for i:=1 to 20 do result:=result+CHRNULL; index:=0; offset:=1; for i:=1 to length(strin) do begin stringa:=strin[i]; words:=pos(uppercase(stringa),base32Chars); if words<1 then begin continue; end; dec(words); if (index <= 3) then begin index:= (index + 5) mod 8; if (index = 0) then begin result[offset]:=chr(byte(ord(result[offset]) or words)); inc(offset); end else result[offset]:=chr(ord(result[offset]) or byte(words shl (8 - index))); end else begin index:= (index + 5) mod 8; result[offset]:=chr(ord(result[offset]) or byte(words shr index)); inc(offset); result[offset]:=chr(ord(result[offset]) or byte(words shl (8 - index))); end; end; end; function EncodeBase32(strin:string):string; var i,index:integer; words:byte; base32Chars:string; begin if length(strin)<20 then exit; base32Chars:='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; index:=0; i:=1; while (i<=length(strin)) do begin if (index > 3) then begin words:= (ord(strin[i]) and ($FF shr index)); index:= (index + 5) mod 8; words:=words shl index; if (i < length(strin)) then words:=words or (ord(strin[i + 1]) shr (8 - index)); inc(i); end else begin words:= (ord(strin[i]) shr (8 - (index + 5))) and $1F; index:= (index + 5) mod 8; if (index = 0) then inc(i); end; result:=result+base32Chars[words+1]; end; end; function EncodeBase64(const Value: string): string; const TableBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; begin Result := Encode3to4(Value, TableBase64); end; function DecodeBase64(const Value: string): string; const ReTablebase64 = #$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$3E +#$40 +#$40 +#$40 +#$3F +#$34 +#$35 +#$36 +#$37 +#$38 +#$39 +#$3A +#$3B +#$3C +#$3D +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$00 +#$01 +#$02 +#$03 +#$04 +#$05 +#$06 +#$07 +#$08 +#$09 +#$0A +#$0B +#$0C +#$0D +#$0E +#$0F +#$10 +#$11 +#$12 +#$13 +#$14 +#$15 +#$16 +#$17 +#$18 +#$19 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$1A +#$1B +#$1C +#$1D +#$1E +#$1F +#$20 +#$21 +#$22 +#$23 +#$24 +#$25 +#$26 +#$27 +#$28 +#$29 +#$2A +#$2B +#$2C +#$2D +#$2E +#$2F +#$30 +#$31 +#$32 +#$33 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40; begin Result := Decode4to3Ex(Value, ReTableBase64); end; function Decode4to3Ex(const Value, Table: string): string; type TDconvert = record case byte of 0: (a0, a1, a2, a3: char); 1: (i: integer); end; var x, y, l, lv: Integer; d: TDconvert; dl: integer; c: byte; p: ^char; begin lv := Length(Value); SetLength(Result, lv); x := 1; dl := 4; d.i := 0; p := pointer(result); while x <= lv do begin y := Ord(Value[x]); if y in [33..127] then c := Ord(Table[y - 32]) else c := 64; Inc(x); if c > 63 then continue; d.i := (d.i shl 6) or c; dec(dl); if dl <> 0 then continue; p^ := d.a2; inc(p); p^ := d.a1; inc(p); p^ := d.a0; inc(p); d.i := 0; dl := 4; end; case dl of 1: begin d.i := d.i shr 2; p^ := d.a1; inc(p); p^ := d.a0; inc(p); end; 2: begin d.i := d.i shr 4; p^ := d.a0; inc(p); end; end; l := integer(p) - integer(pointer(result)); SetLength(Result, l); end; function Encode3to4(const Value, Table: string): string; var c: Byte; n, l: Integer; Count: Integer; DOut: array[0..3] of Byte; begin setlength(Result, ((Length(Value) + 2) div 3) * 4); l := 1; Count := 1; while Count <= Length(Value) do begin c := Ord(Value[Count]); Inc(Count); DOut[0] := (c and $FC) shr 2; DOut[1] := (c and $03) shl 4; if Count <= Length(Value) then begin c := Ord(Value[Count]); Inc(Count); DOut[1] := DOut[1] + (c and $F0) shr 4; DOut[2] := (c and $0F) shl 2; if Count <= Length(Value) then begin c := Ord(Value[Count]); Inc(Count); DOut[2] := DOut[2] + (c and $C0) shr 6; DOut[3] := (c and $3F); end else begin DOut[3] := $40; end; end else begin DOut[2] := $40; DOut[3] := $40; end; for n := 0 to 3 do begin Result[l] := Table[DOut[n] + 1]; Inc(l); end; end; end; end.
unit Unit4; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, DateTimePicker; type { TForm1 } TForm1 = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; blockers: TMemo; today: TMemo; yesterday: TMemo; scrumdate: TDateTimePicker; Label1: TLabel; Panel1: TPanel; procedure blockersExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure scrumdateChange(Sender: TObject); procedure todayChange(Sender: TObject); procedure todayExit(Sender: TObject); procedure yesterdayChange(Sender: TObject); procedure saveTheDay(); procedure yesterdayExit(Sender: TObject); private public end; var Form1: TForm1; indexPath: string; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin scrumdate.Date := Now; indexPath := GetUserDir() + '/.coder-toolbox/scrum/'; if not DirectoryExists(indexPath) then MkDir(indexPath); scrumdate.OnChange(Sender); end; procedure TForm1.scrumdateChange(Sender: TObject); var fname: string; rec: TStringList; begin fname := indexPath + IntToStr(DateTimeToTimeStamp(scrumdate.Date).Date) + '.day'; if FileExists(fname) then begin rec := TStringList.Create; rec.LineBreak := '5812@1@'; rec.LoadFromFile(fname); yesterday.Lines.Text := rec[0]; today.Lines.Text := rec[1]; blockers.Lines.Text := rec[2]; rec.Free; end else begin yesterday.Lines.Text := ''; today.Lines.Text := ''; blockers.Lines.Text := ''; end; end; procedure TForm1.blockersExit(Sender: TObject); begin saveTheDay(); end; procedure TForm1.todayChange(Sender: TObject); begin end; procedure TForm1.todayExit(Sender: TObject); begin saveTheDay(); end; procedure TForm1.saveTheDay(); var fname: string; rec: TStringList; begin rec := TStringList.Create; rec.LineBreak := '5812@1@'; rec.Add(yesterday.Lines.Text); rec.Add(today.Lines.Text); rec.add(blockers.Lines.Text); fname := indexPath + IntToStr(DateTimeToTimeStamp(scrumdate.Date).Date) + '.day'; rec.SaveToFile(fname); rec.Free; end; procedure TForm1.yesterdayExit(Sender: TObject); begin saveTheDay(); end; procedure TForm1.yesterdayChange(Sender: TObject); begin saveTheDay(); end; end.
unit teste.model.pedido; interface uses Windows, Classes, SysUtils, Dialogs, DB, DBClient, System.Generics.Collections, teste.Classes.pedido, teste.interfaces.mvc, ActiveX; type TModelPedidoFiltro = record numero: Integer; cliente: Integer; Data: TDateTime; end; IModelPedido = interface(IModel) ['{AF6827F9-E8CB-49B5-9F26-23FEF62995F3}'] // metodos obrigatorios da interface procedure Inicializar; procedure GravarPedido; procedure IniciarPedido; Procedure ExcluirPedido; procedure setItemPedido; procedure ExcluirItem; // metodos internos desta interface procedure Refresh; procedure RemoverFiltros; procedure SetPedido(numero: Integer); procedure FiltrarPedido(const Filtros: TModelPedidoFiltro); function getcdsPedido: TClientDataSet; procedure setcdsPedido(const value: TClientDataSet); function getPedidoClass: TpedidoClass; procedure setPedidoClass(const value: TpedidoClass); function getActiveItem: TpedidoItem; procedure setActiveItem(value: TpedidoItem); // propriedades property cdsPedido: TClientDataSet read getcdsPedido write setcdsPedido; property pedidoClass: TpedidoClass read getPedidoClass write setPedidoClass; property activeItem: TpedidoItem read getActiveItem write setActiveItem; end; TModelPedido = class(TInterfacedObject, IModelPedido) private FCdsPedido: TClientDataSet; FpedidoClass: TpedidoClass; FactiveItem: TpedidoItem; FFiltrando: Boolean; FFiltros: TModelPedidoFiltro; function getcdsPedido: TClientDataSet; procedure setcdsPedido(const value: TClientDataSet); function getPedidoClass: TpedidoClass; procedure setPedidoClass(const value: TpedidoClass); function getActiveItem: TpedidoItem; procedure setActiveItem(value: TpedidoItem); procedure cloneItem(dest: TpedidoItem); procedure sincronizarItem(); protected public destructor Destroy; override; procedure Inicializar; procedure GravarPedido; procedure IniciarPedido; Procedure ExcluirPedido; procedure setItemPedido; procedure ExcluirItem; procedure Refresh; procedure RemoverFiltros; procedure SetPedido(numero: Integer); procedure FiltrarPedido(const Filtros: TModelPedidoFiltro); property cdsPedido: TClientDataSet read getcdsPedido write setcdsPedido; property pedidoClass: TpedidoClass read getPedidoClass write setPedidoClass; property activeItem: TpedidoItem read getActiveItem write setActiveItem; end; implementation uses teste.dao.pedido; { TModelPedido } { ----------------------------------------------------------------------------- } procedure TModelPedido.cloneItem(dest: TpedidoItem); begin dest.Codigo := FactiveItem.Codigo; dest.CodigoProduto := FactiveItem.CodigoProduto; dest.DescricaoProduto := FactiveItem.DescricaoProduto; dest.Quantidade := FactiveItem.Quantidade; dest.ValorUnitario := FactiveItem.ValorUnitario; dest.ValorTotal := FactiveItem.ValorTotal; end; { ----------------------------------------------------------------------------- } destructor TModelPedido.Destroy; begin FreeAndNil(FCdsPedido); FreeAndNil(FpedidoClass); inherited; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.ExcluirItem(); var i: Integer; begin sincronizarItem(); for i := 0 to FpedidoClass.Itens.Count - 1 do begin if FactiveItem.Codigo = FpedidoClass.Itens[i].Codigo then break end; FpedidoClass.Itens.Delete(i); cdsPedido.Delete(); end; { ----------------------------------------------------------------------------- } procedure TModelPedido.ExcluirPedido; begin FpedidoClass.excluir; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.FiltrarPedido(const Filtros: TModelPedidoFiltro); var Sfiltro: string; begin FFiltrando := True; FFiltros := Filtros; try if FFiltros.numero > 0 then Sfiltro := 'AND codigo = ' + inttostr(FFiltros.numero); if FFiltros.cliente > 0 then Sfiltro := Sfiltro + #13#10 + ' AND codigo_cliente = ' + inttostr(FFiltros.cliente); if FFiltros.Data > 0 then Sfiltro := Sfiltro + #13#10 + ' AND data = ' + QuotedStr(FormatDateTime('YYY-MM-DD', FFiltros.Data)); { TO DO } finally FFiltrando := false; end; end; { ----------------------------------------------------------------------------- } function TModelPedido.getActiveItem: TpedidoItem; begin result := FactiveItem; end; { ----------------------------------------------------------------------------- } function TModelPedido.getcdsPedido: TClientDataSet; begin result := FCdsPedido; end; { ----------------------------------------------------------------------------- } function TModelPedido.getPedidoClass: TpedidoClass; begin result := FpedidoClass; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.GravarPedido; begin TdaoPedido.SetPedido(FpedidoClass); /// **/ end; { ----------------------------------------------------------------------------- } procedure TModelPedido.Inicializar; begin FCdsPedido := TClientDataSet.Create(nil); FCdsPedido.FieldDefs.Clear; FCdsPedido.FieldDefs.Add('codigo', ftInteger, 0, false); FCdsPedido.FieldDefs.Add('produto_codigo', ftInteger, 0, false); FCdsPedido.FieldDefs.Add('descricao', ftString, 60, false); FCdsPedido.FieldDefs.Add('quantidade', ftInteger, 0, false); FCdsPedido.FieldDefs.Add('valor_unitario', ftCurrency, 0, false); FCdsPedido.FieldDefs.Add('valor_total', ftCurrency, 0, false); FCdsPedido.IndexDefs.Add('idxcodigo', 'codigo', []); FCdsPedido.CreateDataSet; FCdsPedido.IndexName := 'idxcodigo'; FpedidoClass := TpedidoClass.Create(0); FactiveItem := TpedidoItem.Create; FFiltrando := false; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.IniciarPedido; begin FpedidoClass.limpar; cdsPedido.EmptyDataSet; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.setItemPedido(); var tmpItem: TpedidoItem; begin if FactiveItem.Codigo = 0 then begin cdsPedido.Insert; cdsPedido.FieldByName('codigo').AsInteger := FpedidoClass.Itens.Count + 1; cdsPedido.FieldByName('produto_codigo').AsInteger := FactiveItem.CodigoProduto; cdsPedido.FieldByName('descricao').AsString := FactiveItem.DescricaoProduto; cdsPedido.FieldByName('quantidade').AsInteger := FactiveItem.Quantidade; cdsPedido.FieldByName('valor_unitario').AsFloat := FactiveItem.ValorUnitario; cdsPedido.FieldByName('valor_total').AsFloat := FactiveItem.ValorTotal; cdsPedido.Post; tmpItem := TpedidoItem.Create; cloneItem(tmpItem); FpedidoClass.Itens.Add(tmpItem); end else begin if not cdsPedido.FindKey([inttostr(FactiveItem.Codigo)]) then raise Exception.Create('O item não foi encontrado'); cdsPedido.edit; cdsPedido.FieldByName('produto_codigo').AsInteger := FactiveItem.CodigoProduto; cdsPedido.FieldByName('descricao').AsString := FactiveItem.DescricaoProduto; cdsPedido.FieldByName('quantidade').AsInteger := FactiveItem.Quantidade; cdsPedido.FieldByName('valor_unitario').AsFloat := FactiveItem.ValorUnitario; cdsPedido.FieldByName('valor_total').AsFloat := FactiveItem.ValorTotal; cdsPedido.Post; end; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.Refresh; begin try FiltrarPedido(FFiltros); finally end; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.RemoverFiltros; begin FFiltrando := false; ZeroMemory(@FFiltros, SizeOf(FFiltros)); Refresh; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.setActiveItem(value: TpedidoItem); begin FactiveItem := value; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.setcdsPedido(const value: TClientDataSet); begin FCdsPedido := value; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.SetPedido(numero: Integer); var i: Integer; begin if assigned(FpedidoClass) then FreeAndNil(FpedidoClass); FpedidoClass := TpedidoClass.Create(numero); cdsPedido.EmptyDataSet; for i := 0 to FpedidoClass.Itens.Count - 1 do begin cdsPedido.Insert; cdsPedido.FieldByName('codigo').AsInteger := FpedidoClass.Itens[i].Codigo; cdsPedido.FieldByName('produto_codigo').AsInteger := FpedidoClass.Itens[i] .CodigoProduto; cdsPedido.FieldByName('descricao').AsString := FpedidoClass.Itens[i] .DescricaoProduto; cdsPedido.FieldByName('quantidade').AsInteger := FpedidoClass.Itens[i] .Quantidade; cdsPedido.FieldByName('valor_unitario').AsFloat := FpedidoClass.Itens[i] .ValorUnitario; cdsPedido.FieldByName('valor_total').AsFloat := FpedidoClass.Itens[i] .ValorTotal; cdsPedido.Post end; end; { ----------------------------------------------------------------------------- } procedure TModelPedido.setPedidoClass(const value: TpedidoClass); begin FpedidoClass := value; end; procedure TModelPedido.sincronizarItem; begin FactiveItem.Codigo := cdsPedido.FieldByName('codigo').AsInteger; FactiveItem.CodigoProduto := cdsPedido.FieldByName('produto_codigo') .AsInteger; FactiveItem.DescricaoProduto := cdsPedido.FieldByName('descricao').AsString; FactiveItem.Quantidade := cdsPedido.FieldByName('quantidade').AsInteger; FactiveItem.ValorUnitario := cdsPedido.FieldByName('valor_unitario').AsFloat; FactiveItem.ValorTotal := cdsPedido.FieldByName('valor_total').AsFloat; end; { ----------------------------------------------------------------------------- } end.
{ ID: a_zaky01 PROG: fence9 LANG: PASCAL } var n,m,p,ans:longint; fin,fout:text; function gcd(a,b:integer):integer; begin if a<b then gcd:=gcd(b,a) else if b=0 then gcd:=a else gcd:=gcd(b,a mod b); end; begin assign(fin,'fence9.in'); assign(fout,'fence9.out'); reset(fin); rewrite(fout); readln(fin,n,m,p); if n=0 then ans:=((p-1)*(m-1)+1-gcd(m,p)) div 2 else ans:=((n-1)*(m-1)+1-gcd(m,n)) div 2; if p<n then dec(ans,((m-1)*(n-p-1)+gcd(m,n-p)-1) div 2) else if (p>n) and (n>0) then inc(ans,(((m-1)*(p-n-1)-gcd(m,p-n)+1) div 2)+m-1); writeln(fout,ans); close(fin); close(fout); end.
{ Equivalent of standard lazarus TLabel but using BGRA Controls framework for text render. Functionality: - Customizable background (gradients etc.) - Customizable border (rounding etc.) - FontEx (shadow, word wrap, etc.) Copyright (C) 2012 Krzysztof Dibowski dibowski at interia.pl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit BCLabel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, BCBasectrls, BGRABitmap, BGRABitmapTypes, BCTypes, types; type { TCustomBCLabel } TCustomBCLabel = class(TBCStyleGraphicControl) private { Private declarations } {$IFDEF DEBUG} FRenderCount: Integer; {$ENDIF} FBackground: TBCBackground; FBGRA: TBGRABitmapEx; FBorder: TBCBorder; FFontEx: TBCFont; FInnerMargin: single; FRounding: TBCRounding; procedure Render; procedure SetInnerMargin(AValue: single); procedure SetRounding(AValue: TBCRounding); procedure UpdateSize; procedure SetBackground(AValue: TBCBackground); procedure SetBorder(AValue: TBCBorder); procedure SetFontEx(AValue: TBCFont); procedure OnChangeProperty(Sender: TObject; {%H-}Data: PtrInt); procedure OnChangeFont({%H-}Sender: TObject; {%H-}AData: PtrInt); protected procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; {%H-}WithThemeSpace: boolean); override; class function GetControlClassDefaultSize: TSize; override; procedure TextChanged; override; protected {$IFDEF DEBUG} function GetDebugText: String; override; {$ENDIF} procedure DrawControl; override; procedure RenderControl; override; function GetStyleExtension: String; override; protected { Protected declarations } property AutoSize default True; property Background: TBCBackground read FBackground write SetBackground; property Border: TBCBorder read FBorder write SetBorder; property FontEx: TBCFont read FFontEx write SetFontEx; property Rounding: TBCRounding read FRounding write SetRounding; property InnerMargin: single read FInnerMargin write SetInnerMargin; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateControl; override; // Called by EndUpdate public { Streaming } procedure SaveToFile(AFileName: string); procedure LoadFromFile(AFileName: string); procedure OnFindClass({%H-}Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); end; { TBCLabel } TBCLabel = class(TCustomBCLabel) published property Action; property Align; property Anchors; property AssignStyle; property AutoSize; property Background; property Border; property BorderSpacing; property Caption; property Cursor; property Enabled; property FontEx; property Height; property HelpContext; property HelpKeyword; property HelpType; property Hint; property InnerMargin; property Left; property PopupMenu; property Rounding; property ShowHint; property Tag; property Top; property Visible; property Width; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; end; procedure Register; implementation uses BCTools; procedure Register; begin {$I icons\bclabel_icon.lrs} RegisterComponents('BGRA Controls',[TBCLabel]); end; { TCustomBCLabel } procedure TCustomBCLabel.Render; var r: TRect; begin if (csCreating in FControlState) or IsUpdating then Exit; FBGRA.NeedRender := False; FBGRA.SetSize(Width, Height); FBGRA.Fill(BGRAPixelTransparent); // Clear; r := FBGRA.ClipRect; CalculateBorderRect(FBorder,r); RenderBackgroundAndBorder(FBGRA.ClipRect, FBackground, TBGRABitmap(FBGRA), FRounding, FBorder, FInnerMargin); RenderText(FBGRA.ClipRect, FFontEx, Caption, TBGRABitmap(FBGRA)); {$IFDEF DEBUG} FRenderCount += 1; {$ENDIF} end; procedure TCustomBCLabel.SetInnerMargin(AValue: single); begin if FInnerMargin=AValue then Exit; FInnerMargin:=AValue; RenderControl; Invalidate; end; procedure TCustomBCLabel.SetRounding(AValue: TBCRounding); begin if FRounding = AValue then Exit; FRounding.Assign(AValue); RenderControl; Invalidate; end; procedure TCustomBCLabel.UpdateSize; begin InvalidatePreferredSize; AdjustSize; end; procedure TCustomBCLabel.SetBackground(AValue: TBCBackground); begin FBackground.Assign(AValue); RenderControl; Invalidate; end; procedure TCustomBCLabel.SetBorder(AValue: TBCBorder); begin FBorder.Assign(AValue); RenderControl; Invalidate; end; procedure TCustomBCLabel.SetFontEx(AValue: TBCFont); begin FFontEx.Assign(AValue); RenderControl; Invalidate; end; procedure TCustomBCLabel.OnChangeProperty(Sender: TObject; Data: PtrInt); begin RenderControl; if (Sender = FBorder) and AutoSize then UpdateSize; Invalidate; end; procedure TCustomBCLabel.OnChangeFont(Sender: TObject; AData: PtrInt); begin RenderControl; UpdateSize; Invalidate; end; procedure TCustomBCLabel.CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: boolean); begin if (Parent = nil) or (not Parent.HandleAllocated) then Exit; CalculateTextSize(Caption, FFontEx, PreferredWidth, PreferredHeight); if AutoSize and (FBorder.Style<>bboNone) then begin Inc(PreferredHeight, 2 * FBorder.Width); Inc(PreferredWidth, 2 * FBorder.Width); end; end; class function TCustomBCLabel.GetControlClassDefaultSize: TSize; begin Result.cx := 100; Result.cy := 25; end; procedure TCustomBCLabel.TextChanged; begin inherited TextChanged; RenderControl; UpdateSize; Invalidate; end; {$IFDEF DEBUG} function TCustomBCLabel.GetDebugText: String; begin Result := 'R: '+IntToStr(FRenderCount); end; {$ENDIF} procedure TCustomBCLabel.DrawControl; begin inherited DrawControl; if FBGRA.NeedRender then Render; FBGRA.Draw(Self.Canvas,0,0,False); end; procedure TCustomBCLabel.RenderControl; begin inherited RenderControl; if FBGRA<>nil then FBGRA.NeedRender := True; end; function TCustomBCLabel.GetStyleExtension: String; begin Result := 'bclbl'; end; procedure TCustomBCLabel.UpdateControl; begin RenderControl; inherited UpdateControl; // invalidate end; procedure TCustomBCLabel.SaveToFile(AFileName: string); var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try WriteComponentAsTextToStream(AStream, Self); AStream.SaveToFile(AFileName); finally AStream.Free; end; end; procedure TCustomBCLabel.LoadFromFile(AFileName: string); var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try AStream.LoadFromFile(AFileName); ReadComponentFromTextStream(AStream, TComponent(Self), @OnFindClass); finally AStream.Free; end; end; procedure TCustomBCLabel.OnFindClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); begin if CompareText(AClassName, 'TBCLabel') = 0 then ComponentClass := TBCLabel; end; constructor TCustomBCLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF DEBUG} FRenderCount := 0; {$ENDIF} DisableAutoSizing; Include(FControlState, csCreating); BeginUpdate; try with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); FBGRA := TBGRABitmapEx.Create(Width, Height); FBackground := TBCBackground.Create(Self); FBorder := TBCBorder.Create(Self); FFontEx := TBCFont.Create(Self); ParentColor := True; FBackground.OnChange := @OnChangeProperty; FBorder.OnChange := @OnChangeProperty; FFontEx.OnChange := @OnChangeFont; FBackground.Style := bbsClear; FBorder.Style := bboNone; FRounding := TBCRounding.Create(Self); FRounding.OnChange := @OnChangeProperty; AutoSize := True; finally EnableAutoSizing; EndUpdate; Exclude(FControlState, csCreating); end; end; destructor TCustomBCLabel.Destroy; begin FBGRA.Free; FBackground.Free; FBorder.Free; FFontEx.Free; FRounding.Free; inherited Destroy; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [WMS_PARAMETRO] The MIT License Copyright: Copyright (C) 2016 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 WmsParametroVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('WMS_PARAMETRO')] TWmsParametroVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FHORA_POR_VOLUME: Integer; FPESSOA_POR_VOLUME: Integer; FHORA_POR_PESO: Integer; FPESSOA_POR_PESO: Integer; FITEM_DIFERENTE_CAIXA: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('HORA_POR_VOLUME', 'Hora Por Volume', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property HoraPorVolume: Integer read FHORA_POR_VOLUME write FHORA_POR_VOLUME; [TColumn('PESSOA_POR_VOLUME', 'Pessoa Por Volume', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property PessoaPorVolume: Integer read FPESSOA_POR_VOLUME write FPESSOA_POR_VOLUME; [TColumn('HORA_POR_PESO', 'Hora Por Peso', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property HoraPorPeso: Integer read FHORA_POR_PESO write FHORA_POR_PESO; [TColumn('PESSOA_POR_PESO', 'Pessoa Por Peso', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property PessoaPorPeso: Integer read FPESSOA_POR_PESO write FPESSOA_POR_PESO; [TColumn('ITEM_DIFERENTE_CAIXA', 'Item Diferente Caixa', 8, [ldGrid, ldLookup, ldCombobox], False)] property ItemDiferenteCaixa: String read FITEM_DIFERENTE_CAIXA write FITEM_DIFERENTE_CAIXA; //Transientes end; implementation initialization Classes.RegisterClass(TWmsParametroVO); finalization Classes.UnRegisterClass(TWmsParametroVO); end.
unit ParserSupport; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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 HL7 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 COPYRIGHT HOLDERS AND CONTRIBUTORS '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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. } interface Uses AdvObjects; type TSourceLocation = record line, col : integer; end; TSourceLocationObject = class (TAdvObject) public locationStart : TSourceLocation; locationEnd : TSourceLocation; end; const MAP_ATTR_NAME = 'B88BF977DA9543B8A5915C84A70F03F7'; function minLoc(src1, src2 : TSourceLocation) : TSourceLocation; function maxLoc(src1, src2 : TSourceLocation) : TSourceLocation; function nullLoc : TSourceLocation; function isNullLoc(src : TSourceLocation) : boolean; function locLessOrEqual(src1, src2 : TSourceLocation) : boolean; function locGreatorOrEqual(src1, src2 : TSourceLocation) : boolean; implementation function minLoc(src1, src2 : TSourceLocation) : TSourceLocation; begin if (src1.line < src2.line) then result := src1 else if (src2.line < src1.line) then result := src2 else if (src1.col < src2.col) then result := src1 else result := src2 end; function maxLoc(src1, src2 : TSourceLocation) : TSourceLocation; begin if (src1.line > src2.line) then result := src1 else if (src2.line > src1.line) then result := src2 else if (src1.col > src2.col) then result := src1 else result := src2 end; function nullLoc : TSourceLocation; begin result.line := -1; result.col := -1; end; function isNullLoc(src : TSourceLocation) : boolean; begin result := (src.line = -1) and (src.col = -1); end; function locLessOrEqual(src1, src2 : TSourceLocation) : boolean; begin if src1.line < src2.line then result := true else if src1.line > src2.line then result := false else result := src1.col <= src2.col; end; function locGreatorOrEqual(src1, src2 : TSourceLocation) : boolean; begin if src1.line > src2.line then result := true else if src1.line < src2.line then result := false else result := src1.col >= src2.col; end; end.
unit ImageEx; interface uses Windows, GDIPAPI, AvL, avlIStreamAdapter; type EImageEx = class (Exception) end; TImageEx = class(TImage) private FImageWidth, FImageHeight: Cardinal; procedure Resize(Sender: TObject); public constructor Create(Parent: TWinControl); procedure Clear; procedure LoadFromStream(Stream: TStream); end; implementation const SGDIPError = 'GDI+ Error (%d)'; function CheckStatus(Status: TStatus): Boolean; begin Result := Status = Ok; if not Result then raise EImageEx.CreateFmt(SGDIPError, [Integer(Status)]); end; { TImageEx } constructor TImageEx.Create(Parent: TWinControl); begin inherited; Style := Style or SS_REALSIZEIMAGE or SS_CENTERIMAGE; OnResize := Resize; end; procedure TImageEx.Clear; begin if BitmapHandle <> 0 then begin DeleteObject(BitmapHandle); BitmapHandle := 0; end; end; procedure TImageEx.LoadFromStream(Stream: TStream); var StreamAdapter: IStream; GDIPBitmap: Pointer; Bitmap: HBitmap; begin TIStreamAdapter.Create(Stream).GetInterface(IStream, StreamAdapter); GDIPBitmap := nil; if not CheckStatus(GdipCreateBitmapFromStream(StreamAdapter, GDIPBitmap)) then Exit; try Clear; if not CheckStatus(GdipCreateHBITMAPFromBitmap(GDIPBitmap, Bitmap, clBlack)) then Exit; GdipGetImageWidth(GDIPBitmap, FImageWidth); GdipGetImageHeight(GDIPBitmap, FImageHeight); BitmapHandle := Bitmap; SetSize(FImageWidth, FImageHeight); finally GdipDisposeImage(GDIPBitmap); end; end; procedure TImageEx.Resize(Sender: TObject); var ScrollInfo: TScrollInfo; begin with ScrollInfo do begin cbSize := SizeOf(ScrollInfo); fMask := SIF_PAGE or SIF_RANGE; nMin := 0; nMax := FImageHeight; nPage := ClientHeight; end; SetScrollInfo(Handle, SB_VERT, ScrollInfo, true); with ScrollInfo do begin nMax := FImageWidth; nPage := ClientWidth; end; SetScrollInfo(Handle, SB_HORZ, ScrollInfo, true); ScrollWindowEx(Handle, FImageWidth - ClientWidth, FImageHeight - ClientHeight, nil, nil, 0, nil, 0); end; end.
unit Unit7; { Fonte: https://showdelphi.com.br/executar-metodos-de-classe-pelo-nome-e-sem-precisar-dar-uses-da-unit/ https://stackoverflow.com/questions/8102255/delphi-dynamically-calling-different-functions } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, rtti; type { Classe de exemplo, normalmente estará em outra unit } TExemploClasse = class(TPersistent) class function Teste(ANumber: Integer): string; end; TForm7 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form7: TForm7; implementation {$R *.dfm} function ExecuteAwayMethod(ClassName, MethodName: string; MethosParams: array of TValue): TValue; var ctx: TRttiContext; lType: TRttiType; lMethod: TRttiMethod; vClass: TClass; begin ctx := TRttiContext.Create; vClass := FindClass(ClassName); lType := ctx.GetType(vClass); Result := nil; try if Assigned(lType) then begin lMethod := lType.GetMethod(MethodName); if Assigned(lMethod) then Result := lMethod.Invoke(vClass, MethosParams); end; finally lMethod.Free; lType.Free; ctx.Free; end; end; procedure TForm7.Button1Click(Sender: TObject); var vValue, vResult: TValue; begin vValue := 10; vResult := ExecuteAwayMethod('TExemploClasse', 'Teste', vValue); ShowMessage(vResult.AsString); end; { TExemploClasse } class function TExemploClasse.Teste(ANumber: Integer): string; begin Result := ANumber.ToString; end; { Para uso deste exemplo, a classe precisa estar registrada } initialization RegisterClass(TExemploClasse); end.
unit VisibleDSA.SortTestHelper; interface uses System.SysUtils; type TArray_int = TArray<integer>; TSortTestHelper = class public // 生成有n个元素的随机数组,每个元素的随机范围为[rangeL, rangeR] class function GenerateRandomArray(n, rangeL, rangeR: integer): TArray_int; // 生成一个近乎有序的数组 // 首先生成一个含有[0...n-1]的完全有序数组, 之后随机交换swapTimes对数据 // swapTimes定义了数组的无序程度: // swapTimes == 0 时, 数组完全有序 // swapTimes 越大, 数组越趋向于无序 class function GenerateNearlyOrderedArray(n, swapTimes: integer): TArray_int; // 打印arr数组的所有内容 class procedure PrintArray(arr: TArray_int); // 判断arr数组是否有序 class function IsSorted(arr: TArray_int): boolean; end; implementation { TSortTestHelper } class function TSortTestHelper.GenerateNearlyOrderedArray(n, swapTimes: integer): TArray_int; var arr: TArray_int; i, a, b, temp: integer; begin SetLength(arr, n); for i := low(arr) to High(arr) do arr[i] := i; Randomize; for i := 0 to swapTimes - 1 do begin a := Random(i); b := Random(i); temp := arr[a]; arr[a] := arr[b]; arr[b] := temp; end; Result := arr; end; class function TSortTestHelper.GenerateRandomArray(n, rangeL, rangeR: integer): TArray_int; var arr: TArray_int; i: integer; begin assert(rangeL <= rangeR); SetLength(arr, n); Randomize; for i := low(arr) to High(arr) do arr[i] := Random((rangeR - rangeL + 1) + rangeL); Result := arr; end; class function TSortTestHelper.IsSorted(arr: TArray_int): boolean; var i: integer; begin for i := 0 to Length(arr) - 2 do begin if arr[i] > arr[i + 1] then Exit(false); end; Result := true; end; class procedure TSortTestHelper.PrintArray(arr: TArray_int); var i: integer; begin for i := 0 to Length(arr) - 1 do begin Write(arr[i].ToString); Write(' '); end; Writeln; end; end.
unit WellPanelFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, ComCtrls, Well, StdCtrls, BaseObjects; type TfrmWellPanel = class(TfrmCommonFrame) redtWell: TRichEdit; private { Private declarations } function GetWell: TWell; protected procedure FillControls(ABaseObject: TIDObject); override; procedure ClearControls; override; public { Public declarations } property Well: TWell read GetWell; constructor Create(AOwner: TComponent); override; end; var frmWellPanel: TfrmWellPanel; implementation {$R *.dfm} { TfrmWellPanel } procedure TfrmWellPanel.ClearControls; begin redtWell.Clear; end; constructor TfrmWellPanel.Create(AOwner: TComponent); begin inherited; StatusBar.Visible := false; EditingClass := TSimpleWell; end; procedure TfrmWellPanel.FillControls(ABaseObject: TIDObject); begin inherited; redtWell.Lines.Clear; redtWell.Lines.Add(Well.List + '. ' + Well.Category.Name + '. ' + DateTimeToStr(Well.DtDrillingStart) + ' - ' + DateTimeToStr(Well.DtDrillingFinish)); redtWell.Lines.Add('Альтитуда: ' + Format('%.2f', [Well.Altitude])); redtWell.Lines.Add('Забой: ' + Format('%.2f', [Well.Depth])); end; function TfrmWellPanel.GetWell: TWell; begin Result := EditingObject as TWell; end; end.
unit Main; interface uses System.SysUtils, System.Variants, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.CheckLst, Vcl.Grids, Vcl.ValEdit, Data.DB, 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.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Phys.FBDef, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.DApt, Utils.IniFile, Vcl.ComCtrls; type TFrmMain = class(TForm) Panel: TPanel; ValueListEditor: TValueListEditor; chkTables: TCheckListBox; BtnMap: TButton; BtnAll: TButton; BtnNone: TButton; BtnCreateController: TButton; BtnConnection: TButton; BtnCreateEntity: TButton; BtnDisconnect: TButton; LblPathProject: TLabel; EdtPathProject: TEdit; BtnCreateModel: TButton; PageControl: TPageControl; TbsEntity: TTabSheet; MemoEntity: TMemo; TbsModel: TTabSheet; TbsiModel: TTabSheet; TbsController: TTabSheet; TbsiController: TTabSheet; MemoModel: TMemo; MemoiModel: TMemo; MemoController: TMemo; MemoiController: TMemo; EdtPathEntity: TEdit; EdtPathModel: TEdit; EdtPathiModel: TEdit; EdtPathController: TEdit; EdtPathiController: TEdit; BtnCreateiModel: TButton; BtnCreateiController: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnConnectionClick(Sender: TObject); procedure BtnDisconnectClick(Sender: TObject); procedure BtnMapClick(Sender: TObject); procedure BtnAllClick(Sender: TObject); procedure BtnNoneClick(Sender: TObject); procedure BtnCreateEntityClick(Sender: TObject); procedure BtnCreateModelClick(Sender: TObject); procedure BtnCreateiModelClick(Sender: TObject); procedure BtnCreateControllerClick(Sender: TObject); procedure BtnCreateiControllerClick(Sender: TObject); private procedure ReadInifile; procedure WriteInifile; procedure Connected; procedure MapDatabase; procedure CheckListBoxSelect(Selected : Boolean); procedure CreateEntity; procedure CreateModel; procedure CreateiModel; procedure CreateController; procedure CreateiController; function ClearNull(sTexto: String): String; function FirstLarge(Value: String): String; function FormatName(Nome: string): string; var FDConnection: TFDConnection; FQuery: TFDQuery; DirectoryEntity, DirectoryModel, DirectoryController: string; public end; var FrmMain: TFrmMain; implementation {$R *.dfm} procedure TFrmMain.FormCreate(Sender: TObject); begin FDConnection := TFDConnection.create(nil); FQuery := TFDQuery.create(nil); FQuery.Connection := FDConnection; EdtPathProject.Text := 'C:\'; end; procedure TFrmMain.FormShow(Sender: TObject); begin ReadInifile; end; procedure TFrmMain.BtnConnectionClick(Sender: TObject); begin Connected; if FDConnection.Connected then begin WriteInifile; BtnConnection.Enabled := False; BtnDisconnect.Enabled := True; BtnMap.Enabled := True; end; end; procedure TFrmMain.BtnDisconnectClick(Sender: TObject); begin Try FDConnection.Connected := False; BtnConnection.Enabled := True; BtnDisconnect.Enabled := False; BtnMap.Enabled := False; BtnAll.Enabled := False; BtnNone.Enabled := False; BtnCreateEntity.Enabled := False; BtnCreateModel.Enabled := False; BtnCreateiModel.Enabled := False; BtnCreateController.Enabled := False; BtnCreateiController.Enabled := False; chkTables.Clear; MemoEntity.Clear; MemoModel.Clear; MemoiModel.Clear; MemoController.Clear; MemoiController.Clear; EdtPathEntity.Text := ''; EdtPathModel.Text := ''; EdtPathiModel.Text := ''; EdtPathController.Text := ''; EdtPathiController.Text := ''; except ShowMessage('Houve um erro ao desconectar do banco de dados!'); End; end; procedure TFrmMain.BtnMapClick(Sender: TObject); begin Try MapDatabase; BtnAll.Enabled := True; BtnNone.Enabled := True; BtnCreateEntity.Enabled := True; BtnCreateModel.Enabled := True; BtnCreateiModel.Enabled := True; BtnCreateController.Enabled := True; BtnCreateiController.Enabled := True; except ShowMessage('Houve um erro ao mapear do banco de dados!'); End; end; procedure TFrmMain.BtnAllClick(Sender: TObject); begin CheckListBoxSelect(True); end; procedure TFrmMain.BtnNoneClick(Sender: TObject); begin CheckListBoxSelect(False); end; procedure TFrmMain.BtnCreateEntityClick(Sender: TObject); begin DirectoryEntity := EdtPathProject.Text + '\Model\Entity'; if not DirectoryExists(DirectoryEntity) then ForceDirectories(DirectoryEntity); CreateEntity; end; procedure TFrmMain.BtnCreateModelClick(Sender: TObject); begin DirectoryModel := EdtPathProject.Text + '\Model'; if not DirectoryExists(DirectoryModel) then ForceDirectories(DirectoryModel); CreateModel; end; procedure TFrmMain.BtnCreateiModelClick(Sender: TObject); begin DirectoryModel := EdtPathProject.Text + '\Model'; if not DirectoryExists(DirectoryModel) then ForceDirectories(DirectoryModel); CreateiModel; end; procedure TFrmMain.BtnCreateControllerClick(Sender: TObject); begin DirectoryController := EdtPathProject.Text + '\Controller'; if not DirectoryExists(DirectoryController) then ForceDirectories(DirectoryController); CreateController; end; procedure TFrmMain.BtnCreateiControllerClick(Sender: TObject); begin DirectoryController := EdtPathProject.Text + '\Controller'; if not DirectoryExists(DirectoryController) then ForceDirectories(DirectoryController); CreateiController; end; procedure TFrmMain.ReadIniFile(); begin ValueListEditor.Values['Hostname'] := IniFileConfig.DatabaseHostname; ValueListEditor.Values['Username'] := IniFileConfig.DatabaseUsername; ValueListEditor.Values['Password'] := IniFileConfig.DatabasePassword; ValueListEditor.Values['Port'] := IniFileConfig.DatabasePort; ValueListEditor.Values['Path'] := IniFileConfig.DatabasePath; EdtPathProject.Text := IniFileConfig.PathProject; end; procedure TFrmMain.WriteIniFile; begin IniFileConfig.DatabaseHostname := ValueListEditor.Values['Hostname']; IniFileConfig.DatabaseUsername := ValueListEditor.Values['Username']; IniFileConfig.DatabasePassword := ValueListEditor.Values['Password']; IniFileConfig.DatabasePort := ValueListEditor.Values['Port']; IniFileConfig.DatabasePath := ValueListEditor.Values['Path']; IniFileConfig.PathProject := EdtPathProject.Text; end; procedure TFrmMain.Connected; begin FDConnection.Params.Clear; FDConnection.Params.Add('Server=' + ValueListEditor.Values['Hostname']); FDConnection.Params.Add('User_Name=' + ValueListEditor.Values['Username']); FDConnection.Params.Add('Password=' + ValueListEditor.Values['Password']); FDConnection.Params.Add('Database=' + ValueListEditor.Values['Path']); FDConnection.Params.Add('Port=' + ValueListEditor.Values['Port']); FDConnection.Params.Add('DriverID=FB'); try FDConnection.Connected := True; FDConnection.ResourceOptions.AutoReconnect := True; except ShowMessage('Houve um erro ao tentar conectar com banco de dados!'); end; end; procedure TFrmMain.MapDatabase; var i: Integer; begin try FQuery := TFDQuery.create(nil); FQuery.Connection := FDConnection; FQuery.Close; FQuery.SQL.Clear; chkTables.Items.Clear(); with FQuery do begin SQL.Text := 'select rdb$relation_name from rdb$relations where rdb$system_flag = 0 order by rdb$relation_name;'; Open(); First(); while not Eof do begin chkTables.Items.Add(ClearNull(Fields[0].AsString)); Next(); end; end; for i := 0 to chkTables.Count - 1 do begin chkTables.Checked[i] := True; end; except ShowMessage('Houve um erro ao maperar banco de dados'); end; end; procedure TFrmMain.CheckListBoxSelect(Selected: Boolean); var i : Integer; begin for i := 0 to chkTables.Count - 1 do begin chkTables.Checked[i] := Selected; end; end; procedure TFrmMain.CreateEntity; var tabela, campo: string; i, j: Integer; begin try for j := 0 to chkTables.Count - 1 do begin Application.ProcessMessages; if chkTables.Checked[j] then begin tabela := chkTables.Items[j].Trim; FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('select * from ' + tabela); FQuery.Open; PageControl.ActivePage := TbsEntity; MemoEntity.lines.Clear; MemoEntity.lines.Add('unit Model.Entity.' + FormatName(tabela) + ';'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('interface'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('uses'); MemoEntity.lines.Add(' System.Classes,'); MemoEntity.lines.Add(' System.Generics.Collections,'); MemoEntity.lines.Add(' System.JSON,'); MemoEntity.lines.Add(' Rest.Json,'); MemoEntity.lines.Add(' SimpleAttributes;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('type'); MemoEntity.lines.Add(' [Tabela(' + QuotedStr(FormatName(tabela)) + ')]'); MemoEntity.lines.Add(' T' + FormatName(tabela) + ' = class'); MemoEntity.lines.Add(' private'); for i := 0 to FQuery.FieldCount - 1 do begin if FQuery.Fields[i].ClassName = 'TStringField' then campo := 'String;' else if FQuery.Fields[i].ClassName = 'TDateField' then campo := 'TDate;' else if FQuery.Fields[i].ClassName = 'TBooleanField' then campo := 'Boolean;' else if FQuery.Fields[i].ClassName = 'TIntegerField' then campo := 'Integer;' else campo := 'String;' + ' {' + FQuery.Fields[i].ClassName + '}'; MemoEntity.lines.Add(' F' + FormatName(FQuery.Fields[i].FieldName) + ': ' + campo); end; MemoEntity.lines.Add(''); MemoEntity.lines.Add(' public'); MemoEntity.lines.Add(' constructor Create;'); MemoEntity.lines.Add(' destructor Destroy; override;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add(' published'); for i := 0 to FQuery.FieldCount - 1 do begin if FQuery.Fields[i].ClassName = 'TStringField' then campo := 'String' else if FQuery.Fields[i].ClassName = 'TDateField' then campo := 'TDate' else if FQuery.Fields[i].ClassName = 'TBooleanField' then campo := 'Boolean' else if FQuery.Fields[i].ClassName = 'TIntegerField' then campo := 'Integer' else campo := 'String;' + ' {' + FQuery.Fields[i].ClassName + '}'; if i = 0 then MemoEntity.lines.Add(' [Campo(' + QuotedStr(FormatName(FQuery.Fields[i].FieldName)) + '), PK, AutoInc]') else MemoEntity.lines.Add(' [Campo(' + QuotedStr(FormatName(FQuery.Fields[i] .FieldName)) + ')]'); MemoEntity.lines.Add(' property ' + FormatName (FQuery.Fields[i].FieldName) + ': ' + campo + ' read F' + FormatName(FQuery.Fields[i].FieldName) + ' write F' + FormatName(FQuery.Fields[i] .FieldName) + ';'); end; MemoEntity.lines.Add(''); MemoEntity.lines.Add(' function ToJSONObject: TJsonObject;'); MemoEntity.lines.Add(' function ToJsonString: string;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add(' end;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('implementation'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('constructor T' + FormatName(tabela) + '.Create;'); MemoEntity.lines.Add('begin'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('end;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('destructor T' + FormatName (tabela) + '.Destroy;'); MemoEntity.lines.Add('begin'); MemoEntity.lines.Add(''); MemoEntity.lines.Add(' inherited;'); MemoEntity.lines.Add('end;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('function T' + FormatName(tabela) + '.ToJSONObject: TJsonObject;'); MemoEntity.lines.Add('begin'); MemoEntity.lines.Add(' Result := TJson.ObjectToJsonObject(Self);'); MemoEntity.lines.Add('end;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('function T' + FormatName(tabela) + '.ToJsonString: string;'); MemoEntity.lines.Add('begin'); MemoEntity.lines.Add(' result := TJson.ObjectToJsonString(self);'); MemoEntity.lines.Add('end;'); MemoEntity.lines.Add(''); MemoEntity.lines.Add('end.'); EdtPathEntity.Text := DirectoryEntity + '\Model.Entity.' + FormatName(tabela) + '.pas'; MemoEntity.lines.SaveToFile(EdtPathEntity.Text); end; end; ShowMessage('Criado arquivo com sucesso!'); except ShowMessage('Houve um erro ao criar arquivo!'); end; end; procedure TFrmMain.CreateModel; var tabela, campo: string; j: Integer; begin try for j := 0 to chkTables.Count - 1 do begin Application.ProcessMessages; if chkTables.Checked[j] then begin tabela := chkTables.Items[j].Trim; end; end; PageControl.ActivePage := TbsModel; MemoModel.lines.Clear; MemoModel.lines.Add('unit Model.' + tabela + ';'); MemoModel.lines.Add(''); MemoModel.lines.Add('interface'); MemoModel.lines.Add(''); MemoModel.lines.Add('uses'); MemoModel.lines.Add(' Data.DB,'); MemoModel.lines.Add(' SimpleDAO,'); MemoModel.lines.Add(' SimpleInterface,'); MemoModel.lines.Add(' SimpleQueryRestDW,'); MemoModel.lines.Add(' Model.Entity.' + tabela + ','); MemoModel.lines.Add(' Model.' + tabela + '.Interfaces;'); MemoModel.lines.Add(''); MemoModel.lines.Add('type'); MemoModel.lines.Add(' TModel' + tabela + ' = class(TInterfacedObject, iModel' + tabela + ')'); MemoModel.lines.Add(' private'); MemoModel.lines.Add(' FEntidade : T' + tabela + ';'); MemoModel.lines.Add(' FDAO : iSimpleDAO<T' + tabela + '>;'); MemoModel.lines.Add(' FDataSource : TDataSource;'); MemoModel.lines.Add(' public'); MemoModel.lines.Add(' constructor Create;'); MemoModel.lines.Add(' destructor Destroy; override;'); MemoModel.lines.Add(' class function New : iModel' + tabela + ';'); MemoModel.lines.Add(' function Entidade: T' + tabela + ';'); MemoModel.lines.Add(' function DAO: iSimpleDAO<T' + tabela + '>;'); MemoModel.lines.Add(' function DataSource(aDataSource: TDataSource): iModel' + tabela + ';'); MemoModel.lines.Add(' end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('implementation'); MemoModel.lines.Add(''); MemoModel.lines.Add('{ TModel' + tabela + ' }'); MemoModel.lines.Add(''); MemoModel.lines.Add('uses System.SysUtils;'); MemoModel.lines.Add(''); MemoModel.lines.Add('constructor TModel' + tabela + '.Create;'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' FEntidade := T' + tabela + '.Create;'); MemoModel.lines.Add(' FDAO := TSimpleDAO<T' + tabela + '>.New;'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('function TModel' + tabela + '.DAO: iSimpleDAO<T' + tabela + '>;'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' Result := FDAO;'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('function TModel' + tabela + '.DataSource(aDataSource: TDataSource): iModel' + tabela + ';'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' Result := Self;'); MemoModel.lines.Add(' FDataSource := aDataSource;'); MemoModel.lines.Add(' FDAO.DataSource(FDatasource);'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('destructor TModel' + tabela + '.Destroy;'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' Freeandnil(FEntidade);'); MemoModel.lines.Add(' inherited;'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('function TModel' + tabela + '.Entidade: T' + tabela + ';'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' Result := FEntidade;'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('class function TModel' + tabela + '.New : iModel' + tabela + ';'); MemoModel.lines.Add('begin'); MemoModel.lines.Add(' Result := Self.Create;'); MemoModel.lines.Add('end;'); MemoModel.lines.Add(''); MemoModel.lines.Add('end.'); EdtPathModel.Text := DirectoryModel + '\Model.' + FormatName(tabela) + '.pas'; MemoModel.lines.SaveToFile(EdtPathModel.Text); ShowMessage('Criado arquivo com sucesso!'); except ShowMessage('Houve um erro ao criar arquivo!'); end; end; procedure TFrmMain.CreateiModel; var tabela, campo: string; j: Integer; begin try for j := 0 to chkTables.Count - 1 do begin Application.ProcessMessages; if chkTables.Checked[j] then begin tabela := chkTables.Items[j].Trim; end; end; PageControl.ActivePage := TbsiModel; MemoiModel.lines.Clear; MemoiModel.lines.Add('unit Model.' + tabela + '.Interfaces;'); MemoiModel.lines.Add(''); MemoiModel.lines.Add('interface'); MemoiModel.lines.Add(''); MemoiModel.lines.Add('uses'); MemoiModel.lines.Add(' Data.DB,'); MemoiModel.lines.Add(' SimpleInterface,'); MemoiModel.lines.Add(' Model.Entity.' + tabela + ';'); MemoiModel.lines.Add(''); MemoiModel.lines.Add('type'); MemoiModel.lines.Add(' iModel' + tabela + ' = interface'); MemoiModel.lines.Add(' [gerar assinatura]'); MemoiModel.lines.Add(' function Entidade : T' + tabela + ';'); MemoiModel.lines.Add(' function DAO : iSimpleDAO<T' + tabela + '>;'); MemoiModel.lines.Add(' function DataSource(aDataSource : TDataSource) : iModel' + tabela + ';'); MemoiModel.lines.Add(' end;'); MemoiModel.lines.Add(''); MemoiModel.lines.Add('implementation'); MemoiModel.lines.Add(''); MemoiModel.lines.Add('end.'); EdtPathiModel.Text := DirectoryModel + '\Model.' + FormatName(tabela) + '.Interfaces.pas'; MemoiModel.lines.SaveToFile(EdtPathiModel.Text); ShowMessage('Criado arquivo com sucesso!'); except ShowMessage('Houve um erro ao criar arquivo!'); end; end; procedure TFrmMain.CreateController; var tabela, campo: string; j: Integer; begin try for j := 0 to chkTables.Count - 1 do begin Application.ProcessMessages; if chkTables.Checked[j] then begin tabela := chkTables.Items[j].Trim; end; end; PageControl.ActivePage := TbsController; MemoController.lines.Clear; MemoController.lines.Add('unit Controller.' + tabela + ';'); MemoController.lines.Add(''); MemoController.lines.Add('interface'); MemoController.lines.Add(''); MemoController.lines.Add('uses'); MemoController.lines.Add(' System.SysUtils,'); MemoController.lines.Add(' System.Json,'); MemoController.lines.Add(' System.Generics.Collections,'); MemoController.lines.Add(' REST.Json,'); MemoController.lines.Add(' Data.DB,'); MemoController.lines.Add(' SimpleRTTI,'); MemoController.lines.Add(' VCL.Forms,'); MemoController.lines.Add(' Model.Entity.' + tabela + ','); MemoController.lines.Add(' Model.' + tabela + '.Interfaces,'); MemoController.lines.Add(' Controller.' + tabela + '.Interfaces;'); MemoController.lines.Add(''); MemoController.lines.Add('type'); MemoController.lines.Add(' TController' + tabela + ' = class(TInterfacedObject, iController' + tabela + ')'); MemoController.lines.Add(' private'); MemoController.lines.Add(' FModel : iModel' + tabela + ';'); MemoController.lines.Add(' FDataSource : TDataSource;'); MemoController.lines.Add(' FList : TObjectList<T' + tabela + '>;'); MemoController.lines.Add(' FEntidade : T' + tabela + ';'); MemoController.lines.Add(' public'); MemoController.lines.Add(' constructor Create;'); MemoController.lines.Add(' destructor Destroy; override;'); MemoController.lines.Add(' class function New: iController' + tabela + ';'); MemoController.lines.Add (' function DataSource(aDataSource: TDataSource): iController' + tabela + '; overload;'); MemoController.lines.Add(' function DataSource : TDataSource; overload;'); MemoController.lines.Add(' function Buscar: iController' + tabela + '; overload;'); MemoController.lines.Add(' function Buscar(aID : integer) : iController' + tabela + '; overload;'); MemoController.lines.Add (' function Buscar(aFiltro : TJsonobject; aOrdem : string) : iController' + tabela + '; overload;'); MemoController.lines.Add(' function Buscar(aSQL : string) : iController' + tabela + '; overload;'); MemoController.lines.Add(' function Insert: iController' + tabela + ';'); MemoController.lines.Add(' function Delete: iController' + tabela + ';'); MemoController.lines.Add(' function Update: iController' + tabela + ';'); MemoController.lines.Add(' function Clear: iController' + tabela + ';'); MemoController.lines.Add(' function Ultimo(where : string) : iController' + tabela + ';'); MemoController.lines.Add(' function ' + tabela + ': T' + tabela + ';'); MemoController.lines.Add (' function FromJsonObject(aJson : TJsonObject) : iController' + tabela + ';'); MemoController.lines.Add(' function List : TObjectList<T' + tabela + '>;'); MemoController.lines.Add(' function ExecSQL(sql : string) : iController' + tabela + ';'); MemoController.lines.Add(' function BindForm(aForm : TForm) : iController' + tabela + ';'); MemoController.lines.Add(''); MemoController.lines.Add(' end;'); MemoController.lines.Add(''); MemoController.lines.Add('implementation'); MemoController.lines.Add(''); MemoController.lines.Add('{ TController' + tabela + ' }'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Buscar: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(''); MemoController.lines.Add(' if not Assigned(FList) then'); MemoController.lines.Add(' FList := TObjectList<T' + tabela + '>.Create;'); MemoController.lines.Add(''); MemoController.lines.Add(' FModel.DAO.Find(FList);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Buscar(aID: integer): iController' + tabela + ';'); MemoController.lines.Add('var aux : string;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(''); MemoController.lines.Add(' if Assigned(FEntidade) then'); MemoController.lines.Add(' Freeandnil(FEntidade);'); MemoController.lines.Add(''); MemoController.lines.Add(' FEntidade := FModel.DAO.Find(aID);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Buscar(aFiltro : TJsonobject; aOrdem : string) : iController' + tabela + ';'); MemoController.lines.Add('var'); MemoController.lines.Add(' Item: TJSONPair;'); MemoController.lines.Add(' sql : string;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' if not Assigned(FList) then'); MemoController.lines.Add(' FList := TObjectList<T' + tabela + '>.Create;'); MemoController.lines.Add(' try'); MemoController.lines.Add(' for Item in afiltro do'); MemoController.lines.Add(' begin'); MemoController.lines.Add(' if item.JsonString.Value = ''SQL'' then'); MemoController.lines.Add(' begin'); MemoController.lines.Add(' sql := (Item.JsonValue.Value);'); MemoController.lines.Add(' end'); MemoController.lines.Add(' else'); MemoController.lines.Add(' begin'); MemoController.lines.Add(' if sql <> '' then'); MemoController.lines.Add(' sql := sql + '' and '';'); MemoController.lines.Add(''); MemoController.lines.Add (' if UpperCase(Item.JsonString.Value) = ''DESCRICAO'' then // verificar o campo de descrição'); MemoController.lines.Add (' sql := sql + UpperCase(Item.JsonString.Value) + '' containing '' + Quotedstr(Item.JsonValue.Value)'); MemoController.lines.Add(' else'); MemoController.lines.Add (' sql := sql + UpperCase(Item.JsonString.Value) + '' = '' + Quotedstr(Item.JsonValue.Value);'); MemoController.lines.Add(' end;'); MemoController.lines.Add(' end;'); MemoController.lines.Add (' FModel.DAO.SQL.Where(sql).OrderBy(aOrdem).&End.Find(FList);'); MemoController.lines.Add(' finally'); MemoController.lines.Add(' Item.Free;'); MemoController.lines.Add(' end;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Buscar(aSQL : string) : iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' try'); MemoController.lines.Add(' FModel.DAO.Find(aSQL, FList);'); MemoController.lines.Add(' except'); MemoController.lines.Add(' end;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.BindForm(aForm: TForm): iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' Clear;'); MemoController.lines.Add(' TSimpleRTTI<' + tabela + '>.New(nil).BindFormToClass(aForm, FEntidade);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.' + tabela + ': T' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := FEntidade;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Clear: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' if Assigned(FEntidade) then'); MemoController.lines.Add(' Freeandnil(FEntidade);'); MemoController.lines.Add(' FEntidade := T' + tabela + '.Create;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('constructor TController' + tabela + '.Create;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' FModel := TModel.New.' + tabela + ';'); MemoController.lines.Add(' FList := TObjectList<T' + tabela + '>.Create;'); MemoController.lines.Add(' FEntidade := T' + tabela + '.Create;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.DataSource('); MemoController.lines.Add(' aDataSource: TDataSource): iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' FDataSource := aDataSource;'); MemoController.lines.Add(' FModel.DataSource(FDataSource);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.DataSource: TDataSource;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := FDataSource;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Delete: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' try'); MemoController.lines.Add(' FModel.DAO.Delete(FEntidade);'); MemoController.lines.Add(' except'); MemoController.lines.Add (' raise Exception.Create(''Erro ao excluir o registro'');'); MemoController.lines.Add(' end;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('destructor TController' + tabela + '.Destroy;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' if Assigned(FList) then'); MemoController.lines.Add(' Freeandnil(FList);'); MemoController.lines.Add(''); MemoController.lines.Add(' if Assigned(FEntidade) then'); MemoController.lines.Add(' Freeandnil(FEntidade);'); MemoController.lines.Add(''); MemoController.lines.Add(' inherited;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Insert: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' FModel.DAO.Insert(FEntidade);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.List : TObjectList<T' + tabela + '>;'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := FList;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('class function TController' + tabela + '.New: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self.Create;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.ExecSQL(sql : string): iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' FModel.DAO.ExecSQL(sql);'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Update: iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' FModel.DAO.Update(FEntidade);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.Ultimo(where : string) : iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' Result := Self;'); MemoController.lines.Add(' if not Assigned(FEntidade) then'); MemoController.lines.Add(' Freeandnil(FEntidade);'); MemoController.lines.Add(' if where = '' then'); MemoController.lines.Add(' where := '' xxx_CODIGO = (select max(xxx_CODIGO) from ' + tabela + ')'';'); MemoController.lines.Add(' FEntidade := FModel.DAO.Max(where);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('function TController' + tabela + '.FromJsonObject(aJson : TJsonObject) : iController' + tabela + ';'); MemoController.lines.Add('begin'); MemoController.lines.Add(' FEntidade := TJson.JsonToObject<T' + tabela + '>(aJson);'); MemoController.lines.Add('end;'); MemoController.lines.Add(''); MemoController.lines.Add('end.'); EdtPathController.Text := DirectoryController + '\Controller.' + FormatName(tabela) + '.pas'; MemoController.lines.SaveToFile(EdtPathController.Text); ShowMessage('Criado arquivo com sucesso!'); except ShowMessage('Houve um erro ao criar arquivo!'); end; end; procedure TFrmMain.CreateiController; var tabela, campo: string; j: Integer; begin try for j := 0 to chkTables.Count - 1 do begin Application.ProcessMessages; if chkTables.Checked[j] then begin tabela := chkTables.Items[j].Trim; end; end; PageControl.ActivePage := TbsiController; MemoiController.lines.Clear; MemoiController.lines.Add('unit Controller.' + tabela + '.Interfaces;'); MemoiController.lines.Add(''); MemoiController.lines.Add('interface'); MemoiController.lines.Add(''); MemoiController.lines.Add('uses'); MemoiController.lines.Add(''); MemoiController.lines.Add(' Data.DB,'); MemoiController.lines.Add(' System.JSON,'); MemoiController.lines.Add(' System.Generics.Collections,'); MemoiController.lines.Add(' VCL.Forms,'); MemoiController.lines.Add(' Model.Entity.' + tabela + ';'); MemoiController.lines.Add(''); MemoiController.lines.Add('type'); MemoiController.lines.Add(' iController' + tabela + ' = interface'); MemoiController.lines.Add(' [GERAR ASSINATURA]'); MemoiController.lines.Add (' function DataSource (aDataSource : TDataSource) : iController' + tabela + '; overload;'); MemoiController.lines.Add(' function DataSource : TDataSource; overload;'); MemoiController.lines.Add(' function Buscar : iController' + tabela + '; overload;'); MemoiController.lines.Add(' function Buscar(aID : integer) : iController' + tabela + '; overload;'); MemoiController.lines.Add (' function Buscar(aFiltro : TJsonobject; aOrdem : string) : iController' + tabela + '; overload;'); MemoiController.lines.Add(' function Buscar(aSQL : string) : iController' + tabela + '; overload;'); MemoiController.lines.Add(' function Insert : iController' + tabela + ';'); MemoiController.lines.Add(' function Delete : iController' + tabela + ';'); MemoiController.lines.Add(' function Update : iController' + tabela + ';'); MemoiController.lines.Add(' function Clear: iController' + tabela + ';'); MemoiController.lines.Add(' function Ultimo(where : string) : iController' + tabela + ';'); MemoiController.lines.Add(' function ' + tabela + ' : T' + tabela + ';'); MemoiController.lines.Add (' function FromJsonObject(aJson : TJsonObject) : iController' + tabela + ';'); MemoiController.lines.Add(' function List : TObjectList<T' + tabela + '>;'); MemoiController.lines.Add(' function ExecSQL(sql : string) : iController' + tabela + ';'); MemoiController.lines.Add(' function BindForm(aForm : TForm) : iController' + tabela + ';'); MemoiController.lines.Add(' end;'); MemoiController.lines.Add(''); MemoiController.lines.Add('implementation'); MemoiController.lines.Add(''); MemoiController.lines.Add('end.'); EdtPathiController.Text := DirectoryController + '\Controller.' + FormatName(tabela) +'.Interfaces.pas'; MemoiController.lines.SaveToFile(EdtPathiController.Text); ShowMessage('Criado arquivo com sucesso!'); except ShowMessage('Houve um erro ao criar arquivo!'); end; end; function TFrmMain.ClearNull(sTexto: String): String; var nPos: Integer; begin nPos := 1; while Pos(' ', sTexto) > 0 do begin nPos := Pos(' ', sTexto); Delete(sTexto, nPos, 1); end; Result := sTexto; end; function TFrmMain.FirstLarge(Value: String): String; var P: Integer; Word: String; begin Result := ''; Value := Trim(LowerCase(Value)); repeat P := Pos(' ', Value); if P <= 0 then begin P := length(Value) + 1; end; Word := UpperCase(Copy(Value, 1, P - 1)); if (length(Word) <= 2) or (Word = 'DAS') or (Word = 'DOS') then begin Result := Result + Copy(Value, 1, P - 1) end else begin Result := Result + UpperCase(Value[1]) + Copy(Value, 2, P - 2); end; Delete(Value, 1, P); if Value <> '' then begin Result := Result + ' '; end; until Value = ''; end; function TFrmMain.FormatName(Nome: string): string; begin Result := UpperCase(Copy(nome,1,1))+LowerCase(Copy(nome,2,Length(nome))); end; end.
{ ******************************************************* } { QSDK.Wechat.iOS 1.0 } { Interfaces for libWeChatSDK 1.7.1 } { Created by TU2(Ticr),and agree to share with QSDK } { ******************************************************* } unit qsdk.wechat.ios; interface uses Classes, Sysutils, System.ZLib {libz.dylib} , System.Sqlite {libsqlite3.0.dylib} , System.Net.UrlClient, iOSapi.Foundation, Macapi.ObjectiveC, iOSapi.UIKit, Macapi.Helpers, FMX.Platform, FMX.graphics, FMX.Platform.ios, iOSapi.SCNetworkReachability, iOSapi.CoreTelephony, qsdk.wechat, QString, System.Messaging; type BaseReq = interface; BaseResp = interface; SendAuthReq = interface; WXMediaMessage = interface; { I 'wxpay.inc' } /// <summary>微信Api接口函数对象</summary> WXApi = interface(NSObject) // 在这里声明对象方法(-) ['{D2B85162-56EC-49A1-8147-44FF05A43147}'] end; /// <summary>微信Api接口函数类</summary> WXApiClass = interface(NSObjectClass) // 在这里声明类方法(+) ['{1EFADA09-CB9B-4625-857D-733E00C5B266}'] /// <summary>向微信终端程序注册第三方应用。</summary> /// <param name="appid">微信开发者ID</param> /// <remarks>需要在每次启动第三方应用程序时调用。请保证在主线程中调用此函数。 /// 第一次调用后,会在微信的可用应用列表中出现。 /// iOS7及以上系统需要调起一次微信才会出现在微信的可用应用列表中。 /// </remarks> function registerApp(appid: NSString): Boolean; cdecl; /// <summary>向微信终端程序注册第三方应用。</summary> /// <param name="appid">微信开发者ID</param> /// <param name="appdesc">应用附加信息,长度不超过1024字节</param> /// <remarks>需要在每次启动第三方应用程序时调用。请保证在主线程中调用此函数。 /// 第一次调用后,会在微信的可用应用列表中出现。 /// iOS7及以上系统需要调起一次微信才会出现在微信的可用应用列表中。 /// </remarks> [MethodName('registerApp:withDescription:')] function registerAppwithDescription(appid, appdesc: NSString) : Boolean; cdecl; /// <summary>向微信终端程序注册应用支持打开的文件类型。</summary> /// <param name="typeFlag">应用支持打开的数据类型,enAppSupportContentFlag枚举类型 “|” 操作后结果</param> /// <remarks>需要在每次启动第三方应用程序时调用。调用后并第一次成功分享数据到微信后,会在微信的可用应用列表中出现。</remarks> procedure registerAppSupportContentFlag(typeFlag: UInt64); cdecl; /// <summary>处理微信通过URL启动App时传递的数据。</summary> /// <param name="url">微信启动第三方应用时传递过来的URL</param> /// <param name="delegate">WXApiDelegate对象,用来接收微信触发的消息</param> /// <remarks>需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。</remarks> function handleOpenURL(url: NSURL; delegate: Pointer): Boolean; cdecl; /// <summary>检查微信是否已被用户安装。</summary> function isWXAppInstalled: Boolean; cdecl; /// <summary>判断当前微信的版本是否支持OpenApi。</summary> function isWXAppSupportApi: Boolean; cdecl; /// <summary>获取微信的itunes安装地址。</summary> function getWXAppInstallUrl: NSString; cdecl; /// <summary>获取当前微信SDK的版本号。</summary> function getApiVersion: NSString; cdecl; /// <summary>打开微信。</summary> function openWXApp: Boolean; cdecl; /// <summary>发送请求到微信,等待微信返回onResp。</summary> /// <param name="req">具体的发送请求,在调用函数后,请自己释放</param> /// <remarks>函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。 /// 微信在异步处理完成后一定会调用onResp。支持SendAuthReq、SendMessageToWXReq、PayReq等</remarks> function sendReq(req: BaseReq): Boolean; cdecl; /// <summary>发送Auth请求到微信,支持用户没安装微信,等待微信返回onResp。</summary> /// <param name="req">具体的发送请求,在调用函数后,请自己释放</param> /// <param name="viewController">当前界面对象</param> /// <param name="delegate">WXApiDelegate对象,用来接收微信触发的消息</param> /// <remarks>函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。 /// 微信在异步处理完成后一定会调用onResp。支持SendAuthReq类型。</remarks> function SendAuthReq(req: SendAuthReq; viewController: UIViewController; delegate: Pointer): Boolean; cdecl; /// <summary>收到微信onReq的请求,发送对应的应答给微信,并切换到微信界面。</summary> /// <param name="resp">具体的应答内容,调用函数后,请自己释放</param> /// <remarks>函数调用后,会切换到微信的界面。第三方应用程序收到微信onReq的请求,异步处理该请求,完成后必须调用该函数。 /// 可能发送的相应有GetMessageFromWXResp、ShowMessageFromWXResp等。</remarks> function sendResp(resp: BaseResp): Boolean; cdecl; end; TWXApi = class(TOCGenericImport<WXApiClass, WXApi>) end; BaseReqClass = interface(NSObjectClass) ['{DB6C6725-1314-4E96-9800-E8837BEBA3CB}'] end; // ------------------------------------------------------------------------------ /// <summary>微信终端SDK所有请求消息的基类</summary> BaseReq = interface(NSObject) ['{2669AE3E-02DD-46B9-B1B8-7705A47FF5E6}'] /// <summary>请求类型</summary> [MethodName('type:')] function _type: Integer; cdecl; procedure setType(AType: Integer); cdecl; /// <summary>由用户微信号和AppID组成的唯一标识</summary> /// <remarks>发送请求时第三方程序必须填写,用于校验微信用户是否换号登录</remarks> function openID: NSString; cdecl; procedure setOpenID(openID: NSString); cdecl; end; TBaseReq = class(TOCGenericImport<BaseReqClass, BaseReq>) end; SendAuthReqClass = interface(BaseReqClass) ['{E39DB951-8E23-4AEC-9884-EA3356B7DC21}'] end; /// <summary>认证请求</summary> SendAuthReq = interface(BaseReq) ['{0719D7AB-B0CB-4D16-8A64-6E270D9D98A7}'] function scope: NSString; cdecl; /// <remarks>scope字符串长度不能超过1K</remarks> procedure setScope(scope: NSString); cdecl; function state: NSString; cdecl; /// <remarks>state字符串长度不能超过1K</remarks> procedure setState(state: NSString); cdecl; end; TSendAuthReq = class(TOCGenericImport<SendAuthReqClass, SendAuthReq>) end; PayReqClass = interface(BaseReqClass) ['{2E36C4EE-0050-4072-ABAF-DE2171F5FA64}'] end; /// <summary>支付请求</summary> PayReq = interface(BaseReq) ['{5B7DC0E5-386E-4B5F-AADE-EA646C8F40E5}'] /// <summary>商家向财付通申请的商家id</summary> function partnerId: NSString; cdecl; procedure setPartnerId(partnerId: NSString); cdecl; /// <summary>预支付订单id</summary> function prepayId: NSString; cdecl; procedure setPrepayId(prepayId: NSString); cdecl; /// <summary>随机串,防重发</summary> function nonceStr: NSString; cdecl; procedure setNonceStr(nonceStr: NSString); cdecl; /// <summary>时间戳,防重发</summary> function timeStamp: UInt32; cdecl; procedure setTimeStamp(timeStamp: UInt32); cdecl; /// <summary>商家根据财付通文档填写的数据和签名</summary> function package: NSString; cdecl; procedure setPackage(package: NSString); cdecl; /// <summary>商家根据微信开放平台文档对数据做的签名</summary> function sign: NSString; cdecl; procedure setSign(sign: NSString); cdecl; end; TPayReq = class(TOCGenericImport<PayReqClass, PayReq>) end; /// <summary>拆企业红包请求</summary> HBReq = interface(BaseReq) ['{F0886BC2-E740-48C2-8B24-99CC9357B081}'] /// <summary>随机串,防重发</summary> function nonceStr: NSString; cdecl; procedure setNonceStr(nonceStr: NSString); cdecl; /// <summary>时间戳,防重发</summary> function timeStamp: UInt32; cdecl; procedure setTimeStamp(timeStamp: UInt32); cdecl; /// <summary>商家根据微信企业红包开发文档填写的数据和签名</summary> function package: NSString; cdecl; procedure setPackage(package: NSString); cdecl; /// <summary>商家根据微信企业红包开发文档对数据做的签名</summary> function sign: NSString; cdecl; procedure setSign(sign: NSString); cdecl; end; /// <summary>发消息请求</summary> SendMessageToWXReq = interface(BaseReq) ['{97149A16-9975-406C-A992-4AEF5323CE7E}'] /// <summary>发送消息的文本内容</summary> /// <remarks>文本长度必须大于0且小于10K</remarks> function text: NSString; cdecl; procedure setText(text: NSString); cdecl; /// <summary>发送消息的多媒体内容</summary> function message: WXMediaMessage; cdecl; procedure setMessage(message: WXMediaMessage); cdecl; /// <summary>是否是文本消息</summary> function bText: Boolean; cdecl; procedure setBText(bText: Boolean); cdecl; /// <summary>目标场景(默认发送到会话)</summary> function scene: Integer; cdecl; procedure setScene(scene: Integer); cdecl; end; SendMessageToWXReqClass = interface(NSObjectClass) ['{25BA201D-4209-4987-8A0B-249A0D3D8ED3}'] end; TSendMessageToWXReq = class(TOCGenericImport<SendMessageToWXReqClass, SendMessageToWXReq>) end; /// <summary>打开临时会话请求</summary> OpenTempSessionReq = interface(BaseReq) ['{5E4F94F8-2526-471F-BAFE-CEECC7650822}'] /// <summary>需要打开的用户名(长度不能超过512字节)</summary> function username: NSString; cdecl; procedure setUsername(username: NSString); cdecl; /// <summary>开发者自定义参数,拉起临时会话后会发给开发者后台,可以用于识别场景(长度不能超过32位)</summary> function sessionFrom: NSString; cdecl; procedure setSessionFrom(sessionFrom: NSString); cdecl; end; /// <summary>打开指定网址请求</summary> OpenWebviewReq = interface(BaseReq) ['{D60EDE96-9B9A-4508-A68C-98C95C2972F1}'] /// <summary>需要打开的网页对应的Url(长度不能超过1024)</summary> function url: NSString; cdecl; procedure setUrl(url: NSString); cdecl; end; /// <summary>打开硬件排行榜请求</summary> OpenRankListReq = interface(BaseReq) ['{955D93EC-AA2F-4C4D-9193-D94EC81A1C37}'] end; /// <summary>打开指定微信公众号profile页面</summary> JumpToBizProfileReq = interface(BaseReq) ['{141D08FA-D6B2-4BCC-8114-09639561AD87}'] /// <summary>跳转到该公众号的profile(长度不能超过512字节)</summary> function username: NSString; cdecl; procedure setUsername(username: NSString); cdecl; /// <summary>如果用户加了该公众号为好友,extMsg会上传到服务器(长度不能超过1024字节)</summary> function extMsg: NSString; cdecl; procedure setExtMsg(extMsg: NSString); cdecl; /// <summary>跳转的公众号类型</summary> function profileType: Integer; cdecl; procedure setProfileType(profileType: Integer); cdecl; end; /// <summary>打开指定微信公众号profile网页版</summary> JumpToBizWebviewReq = interface(BaseReq) ['{3154F62A-9D93-4ABC-AE24-CA547B211249}'] /// <summary>跳转的网页类型,目前只支持广告页</summary> function webType: Integer; cdecl; procedure setWebType(webType: Integer); cdecl; /// <summary>跳转到该公众号的profile网页版(长度不能超过512字节)</summary> function tousrname: NSString; cdecl; procedure setTousrname(tousrname: NSString); cdecl; /// <summary>如果用户加了该公众号为好友,extMsg会上传到服务器(长度不能超过1024字节)</summary> function extMsg: NSString; cdecl; procedure setExtMsg(extMsg: NSString); cdecl; end; /// <summary>请求添加卡券</summary> AddCardToWXCardPackageReq = interface(BaseReq) ['{F7547572-9BD0-431F-8AAA-DE8FB0AB8814}'] /// <summary>卡列表(个数不能超过40个WXCardItem)</summary> function cardAry: NSArray; cdecl; procedure setCardAry(cardAry: NSArray); cdecl; end; /// <summary>请求选取卡券</summary> WXChooseCardReq = interface(BaseReq) ['{B9B20AC0-C4CC-4CB2-B3D5-EFC32EF56CCF}'] function appid: NSString; cdecl; procedure setAppID(appid: NSString); cdecl; function shopID: UInt32; cdecl; procedure setShopID(shopID: UInt32); cdecl; function canMultiSelect: UInt32; cdecl; procedure setCanMultiSelect(canMultiSelect: UInt32); cdecl; function cardType: NSString; cdecl; procedure setCardType(cardType: NSString); cdecl; function cardTpID: NSString; cdecl; procedure setCardTpID(cardTpID: NSString); cdecl; function signType: NSString; cdecl; procedure setSignType(signType: NSString); cdecl; function cardSign: NSString; cdecl; procedure setCardSign(cardSign: NSString); cdecl; function timeStamp: UInt32; cdecl; procedure setTimeStamp(timeStamp: UInt32); cdecl; function nonceStr: NSString; cdecl; procedure setNonceStr(nonceStr: NSString); cdecl; end; /// <summary>微信请求提供内容的消息</summary> GetMessageFromWXReq = interface(BaseReq) ['{A78D6373-B23A-4EAC-958B-F90F3304226D}'] function lang: NSString; cdecl; procedure setLang(lang: NSString); cdecl; function country: NSString; cdecl; procedure setCountry(country: NSString); cdecl; end; /// <summary>微信通知显示内容的消息</summary> ShowMessageFromWXReq = interface(BaseReq) ['{0AC5F853-9268-4223-85EA-E405F61BA277}'] /// <summary>第三方程序需处理的多媒体内容</summary> function message: WXMediaMessage; cdecl; procedure setMessage(message: WXMediaMessage); cdecl; function lang: NSString; cdecl; procedure setLang(lang: NSString); cdecl; function country: NSString; cdecl; procedure setCountry(country: NSString); cdecl; end; /// <summary>微信发送的打开命令消息(无需响应)</summary> LaunchFromWXReq = interface(BaseReq) ['{18AC138F-C24F-490B-8C6A-CAEAC8294241}'] /// <summary>第三方程序需处理的多媒体内容</summary> function message: WXMediaMessage; cdecl; procedure setMessage(message: WXMediaMessage); cdecl; function lang: NSString; cdecl; procedure setLang(lang: NSString); cdecl; function country: NSString; cdecl; procedure setCountry(country: NSString); cdecl; end; BaseRespClass = interface(NSObjectClass) ['{6D726818-BFCC-4C88-B7F0-23CDBA69CB84}'] end; // ------------------------------------------------------------------------------ /// <summary>该类为微信终端SDK所有响应消息的基类</summary> BaseResp = interface(NSObject) ['{535824F8-CAE8-4C73-A688-136A72745D38}'] /// <summary>错误码</summary> function errCode: Integer; cdecl; procedure setErrCode(errCode: Integer); cdecl; /// <summary>错误提示字符串</summary> function errStr: NSString; cdecl; procedure setErrStr(errStr: NSString); cdecl; /// <summary>响应类型</summary> [MethodName('type:')] function _type: Integer; cdecl; procedure setType(AType: Integer); cdecl; end; /// <summary>认证响应</summary> SendAuthResp = interface(BaseResp) ['{42C82024-4966-456A-98A4-164F7F1269A0}'] function code: NSString; cdecl; procedure setCode(code: NSString); cdecl; function state: NSString; cdecl; procedure setState(state: NSString); cdecl; function lang: NSString; cdecl; procedure setLang(lang: NSString); cdecl; function country: NSString; cdecl; procedure setCountry(country: NSString); cdecl; end; PayRespClass = interface(BaseRespClass) ['{EDBDFDF8-F5AA-4D22-8580-1CD2BA1DA473}'] end; /// <summary>支付响应</summary> PayResp = interface(BaseResp) ['{BD7E06A1-1EC0-4150-86D7-F83BE56BDA33}'] function returnKey: NSString; cdecl; procedure setReturnKey(returnKey: NSString); cdecl; end; TPayResp = class(TOCGenericImport<PayRespClass, PayResp>) end; /// <summary>拆企业红包响应</summary> HBResp = interface(BaseResp) ['{C702597C-8F91-4EA0-AA06-01BB91F71E4A}'] end; /// <summary>发消息响应</summary> SendMessageToWXResp = interface(BaseResp) ['{3F183020-33C1-469A-8689-DB9CE8C62F1C}'] function lang: NSString; cdecl; procedure setLang(lang: NSString); cdecl; function country: NSString; cdecl; procedure setCountry(country: NSString); cdecl; end; /// <summary>打开临时会话响应</summary> OpenTempSessionResp = interface(BaseResp) ['{8934A492-0051-4E83-B652-5D685ED573EE}'] end; /// <summary>打开指定网址响应</summary> OpenWebviewResp = interface(BaseResp) ['{E132F3B9-471C-4F6E-B5AA-89181CEF4069}'] end; /// <summary>打开硬件排行榜响应</summary> OpenRanklistResp = interface(BaseResp) ['{FC4635D7-8680-4526-94DD-9AFD6E1AD5A1}'] end; /// <summary>请求添加卡券响应</summary> AddCardToWXCardPackageResp = interface(BaseResp) ['{44A8BDC7-0366-4566-B52C-BCC0527090EA}'] /// <summary>卡列表(个数不能超过40个WXCardItem)</summary> function cardAry: NSArray; cdecl; procedure setCardAry(cardAry: NSArray); cdecl; end; /// <summary>请求选取卡券响应</summary> WXChooseCardResp = interface(BaseResp) ['{72913849-CE84-4964-81CC-643B7F110695}'] /// <summary>卡列表(个数不能超过40个WXCardItem)</summary> function cardAry: NSArray; cdecl; procedure setCardAry(cardAry: NSArray); cdecl; end; /// <summary>微信请求提供内容的响应</summary> GetMessageFromWXResp = interface(BaseResp) ['{59AA8D34-236E-4983-B27C-C0E252DCE551}'] /// <summary>向微信终端提供的文本内容</summary> /// <remarks>文本长度必须大于0且小于10K</remarks> function text: NSString; cdecl; procedure setText(text: NSString); cdecl; /// <summary>向微信终端提供的多媒体内容</summary> function message: WXMediaMessage; cdecl; procedure setMessage(message: WXMediaMessage); cdecl; /// <summary>是否是文本消息</summary> function bText: Boolean; cdecl; procedure setBText(bText: Boolean); cdecl; end; /// <summary>微信通知显示内容的响应</summary> ShowMessageFromWXResp = interface(BaseResp) ['{7C91EA04-C0A0-417F-9C61-07DF77091877}'] end; // ------------------------------------------------------------------------------ /// <summary>多媒体消息</summary> WXMediaMessage = interface(NSObject) ['{DBE9475E-43DE-4699-9D5F-41AC0D6666CA}'] /// <summary>标题(长度不能超过512字节)</summary> function title: NSString; cdecl; procedure setTitle(title: NSString); cdecl; /// <summary>描述内容(长度不能超过1K)</summary> function description: NSString; cdecl; procedure setDescription(description: NSString); cdecl; /// <summary>缩略图数据(大小不能超过32K)</summary> function thumbData: NSData; cdecl; procedure setThumbData(thumbData: NSData); cdecl; /// <summary>媒体标签名(长度不能超过64字节)</summary> function mediaTagName: NSString; cdecl; procedure setMediaTagName(mediaTagName: NSString); cdecl; function messageExt: NSString; cdecl; procedure setMessageExt(messageExt: NSString); cdecl; function messageAction: NSString; cdecl; procedure setMessageAction(messageAction: NSString); cdecl; /// <summary>多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等</summary> function mediaObject: Pointer; cdecl; procedure setMediaObject(mediaObject: Pointer); cdecl; /// <summary>设置消息缩略图(大小不能超过32K)</summary> procedure setThumbImage(image: UIImage); cdecl; end; WXMediaMessageClass = interface(NSObjectClass) ['{E47D92D1-ED26-419E-840A-CACFD7797FC4}'] function message: WXMediaMessage; cdecl; end; TWXMediaMessage = class(TOCGenericImport<WXMediaMessageClass, WXMediaMessage>) end; /// <summary>图片数据对象</summary> WXImageObject = interface(NSObject) ['{5A346557-3ABB-4BEE-9E0A-03ABA319737F}'] /// <summary>图片真实数据内容(大小不能超过10M)</summary> function imageData: NSData; cdecl; procedure setImageData(imageData: NSData); cdecl; end; WXImageObjectClass = interface(NSObjectClass) ['{57F80B15-17FF-4C18-977E-8706DE5BE724}'] [MethodName('object')] function _object: WXImageObject; cdecl; end; TWXImageObject = class(TOCGenericImport<WXImageObjectClass, WXImageObject>) end; /// <summary>音乐数据对象</summary> WXMusicObject = interface(NSObject) ['{9EFD0E25-7B2A-4044-ACB0-220EF151E0FC}'] /// <summary>音乐网页的url地址(长度不能超过10K)</summary> function musicUrl: NSString; cdecl; procedure setMusicUrl(musicUrl: NSString); cdecl; /// <summary>音乐lowband网页的url地址(长度不能超过10K)</summary> function musicLowBandUrl: NSString; cdecl; procedure setMusicLowBandUrl(musicLowBandUrl: NSString); cdecl; /// <summary>音乐数据url地址(长度不能超过10K)</summary> function musicDataUrl: NSString; cdecl; procedure setMusicDataUrl(musicDataUrl: NSString); cdecl; /// <summary>音乐lowband数据url地址(长度不能超过10K)</summary> function musicLowBandDataUrl: NSString; cdecl; procedure setMusicLowBandDataUrl(musicLowBandDataUrl: NSString); cdecl; end; WXMusicObjectClass = interface(NSObjectClass) ['{FF46237F-F8BC-4444-A96C-CC40901406D7}'] /// <summary>返回一个WXMusicObject对象(自动释放)</summary> [MethodName('object')] function _object: WXMusicObject; cdecl; end; TWXMusicObject = class(TOCGenericImport<WXMusicObjectClass, WXMusicObject>) end; /// <summary>视频数据对象</summary> WXVideoObject = interface(NSObject) ['{DF30900E-6A3E-4296-98A9-E1DE67D18703}'] /// <summary>视频网页的url地址(长度不能超过10K)</summary> function videoUrl: NSString; cdecl; procedure setVideoUrl(videoUrl: NSString); cdecl; /// <summary>视频lowband网页的url地址(长度不能超过10K)</summary> function videoLowBandUrl: NSString; cdecl; procedure setVideoLowBandUrl(videoLowBandUrl: NSString); cdecl; end; WXVideoObjectClass = interface(NSObjectClass) ['{BC4FA2FD-C81E-4D72-8626-C3BEAC1CDB6C}'] [MethodName('object')] function _object: WXVideoObject; cdecl; end; TWXVideoObject = class(TOCGenericImport<WXVideoObjectClass, WXVideoObject>) end; /// <summary>网页数据对象</summary> WXWebpageObject = interface(NSObject) ['{4A693270-7940-4D5E-A659-87A2867D72DE}'] /// <summary>网页的url地址(长度不能超过10K)</summary> function webpageUrl: NSString; cdecl; procedure setWebpageUrl(webpageUrl: NSString); cdecl; end; WXWebpageObjectClass = interface(NSObjectClass) ['{619F490C-4C0A-427D-B2EE-C5B924EBEDC9}'] [MethodName('object')] function _object: WXWebpageObject; cdecl; end; TWXWebpageObject = class(TOCGenericImport<WXWebpageObjectClass, WXWebpageObject>) end; /// <summary>App扩展数据对象</summary> WXAppExtendObject = interface(NSObject) ['{2AC0B025-CC2C-4B07-AF1A-57614450DC6F}'] /// <summary>若第三方程序不存在,微信终端会打开该url所指的App下载地址(长度不能超过10K)</summary> function url: NSString; cdecl; procedure setUrl(url: NSString); cdecl; /// <summary>第三方程序自定义简单数据,微信终端会回传给第三方程序处理(长度不能超过2K)</summary> function extInfo: NSString; cdecl; procedure setExtInfo(extInfo: NSString); cdecl; /// <summary>App文件数据,该数据发送给微信好友,微信好友需要点击后下载数据,微信终端会回传给第三方程序处理(不能超过10M)</summary> function fileData: NSData; cdecl; procedure setFileData(fileData: NSData); cdecl; end; WXAppExtendObjectClass = interface(NSObjectClass) ['{57D0899C-454D-4A97-B77E-3C1CAB515239}'] [MethodName('object')] function _object: WXAppExtendObject; cdecl; end; TWXAppExtendObject = class(TOCGenericImport<WXAppExtendObjectClass, WXAppExtendObject>) end; WXEmoticonObject = interface(NSObject) ['{468BA611-B5EC-4546-A8BD-56EC57F0931C}'] /// <summary>表情真实数据内容(不能超过10M)</summary> function emoticonData: NSData; cdecl; procedure setEmoticonData(emoticonData: NSData); cdecl; end; WXEmoticonObjectClass = interface(NSObjectClass) ['{CF96FDDA-4AE9-443A-903C-F7D76FA1DA5B}'] [MethodName('object')] function _object: WXEmoticonObject; cdecl; end; TWXEmoticonObject = class(TOCGenericImport<WXEmoticonObjectClass, WXEmoticonObject>) end; WXFileObject = interface(NSObject) ['{B8B681B2-5CA8-425B-B802-41F63A4C1A73}'] /// <summary>文件后缀名(长度不能超过64B)</summary> function fileExtension: NSString; cdecl; procedure setFileExtension(fileExtension: NSString); cdecl; /// <summary>文件真实数据内容(不能超过10M)</summary> function fileData: NSData; cdecl; procedure setFileData(fileData: NSData); cdecl; end; WXFileObjectClass = interface(NSObjectClass) ['{7FE49721-CC4B-4E0E-8B52-D3EF481FB642}'] [MethodName('object')] function _object: WXFileObject; cdecl; end; TWXFileObject = class(TOCGenericImport<WXFileObjectClass, WXFileObject>) end; WXLocationObject = interface(NSObject) ['{F2817744-0887-4BF6-B31E-8DF1CF2CA434}'] /// <summary>经度</summary> function lng: Double; cdecl; procedure setLng(lng: Double); cdecl; /// <summary>纬度</summary> function lat: Double; cdecl; procedure setLat(lat: Double); cdecl; end; WXLocationObjectClass = interface(NSObjectClass) ['{F3426D6B-0BDF-497B-8086-95DAF300D660}'] [MethodName('object')] function _object: WXLocationObject; cdecl; end; TWXLocationObject = class(TOCGenericImport<WXLocationObjectClass, WXLocationObject>) end; WXTextObject = interface(NSObject) ['{816ABB06-F0FA-4DF7-A7E8-90399C783806}'] /// <summary>文本内容</summary> function contentText: NSString; cdecl; procedure setContentText(contentText: NSString); cdecl; end; WXTextObjectClass = interface(NSObjectClass) ['{01B24EA7-9EFB-46A9-B470-A778AA87EDBC}'] [MethodName('object')] function _object: WXTextObject; cdecl; end; TWXTextObject = class(TOCGenericImport<WXTextObjectClass, WXTextObject>) end; /// <summary>卡券</summary> WXCardItem = interface(NSObject) ['{97C86C90-37A8-4B9D-A6A7-276DBB42A168}'] /// <summary>卡id(长度不能超过512字节)</summary> function cardId: NSString; cdecl; procedure setCardId(cardId: NSString); cdecl; /// <summary>ext信息(长度不能超过2024字节)</summary> function extMsg: NSString; cdecl; procedure setExtMsg(extMsg: NSString); cdecl; /// <summary>卡的状态,req不需要填(resp:0为未添加,1为已添加)</summary> function cardState: UInt32; cdecl; procedure setCardState(cardState: UInt32); cdecl; /// <remarks>req不需要填,chooseCard返回的</remarks> function encryptCode: NSString; cdecl; procedure setEncryptCode(encryptCode: NSString); cdecl; /// <remarks>req不需要填,chooseCard返回的</remarks> function appid: NSString; cdecl; procedure setAppID(appid: NSString); cdecl; end; WXCardItemClass = interface(NSObjectClass) ['{52B17245-F914-4970-B4F2-637948A15022}'] { class method declarations } end; TWXCardItem = class(TOCGenericImport<WXCardItemClass, WXCardItem>) end; WechatAuthSDK = interface(NSObject) ['{148DE279-2C4F-4777-A6FF-E7BCAEF953D2}'] /// <summary> WechatAuthAPIDelegate</summary> function delegate: Pointer; cdecl; procedure setDelegate(delegate: Pointer); cdecl; /// <summary>authSDK版本号</summary> function sdkVersion: NSString; cdecl; procedure setSdkVersion(sdkVersion: NSString); cdecl; /// <summary>发送登录请求,等待WechatAuthAPIDelegate回调</summary> /// <param name="appId">微信开发者ID</param> /// <param name="nonceStr">一个随机的尽量不重复的字符串,用来使得每次的signature不同</param> /// <param name="timeStamp">时间戳</param> /// <param name="scope">应用授权作用域,拥有多个作用域用逗号(,)分隔</param> /// <param name="signature">签名</param> /// <param name="schemeData">会在扫码后拼在scheme后</param> /// <remarks>该实现只保证同时只有一个Auth在运行,Auth未完成或未Stop再次调用Auth接口时会返回False</remarks> function Auth(appid, nonceStr, timeStamp, scope, signature, schemeData: NSString): Boolean; cdecl; /// <summary>暂停登录请求</summary> function StopAuth: Boolean; cdecl; end; WechatAuthSDKClass = interface(NSObjectClass) ['{14058241-BD3B-42C7-90D0-D3F0D2B6CF41}'] { class method declarations } end; TWechatAuthSDK = class(TOCGenericImport<WechatAuthSDKClass, WechatAuthSDK>) end; /// <summary>接收并处理来自微信终端程序的事件委托</summary> WXApiDelegate = interface(IObjectiveC) ['{892B17F1-1C38-497B-B6E6-12A451B09D6B}'] /// <summary>收到一个来自微信的请求</summary> /// <param name="req">具体请求内容,是自动释放的</param> /// <remarks>第三方应用程序异步处理完成后必须调用sendResp发送处理结果给微信。可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。</remarks> procedure onReq(req: BaseReq); cdecl; /// <summary>发送一个sendReq后,收到微信的回应</summary> /// <param name="resp">具体的回应内容,是自动释放的</param> /// <remarks>可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。</remarks> procedure onResp(resp: BaseResp); cdecl; end; WechatAuthAPIDelegate = interface(IObjectiveC) ['{44080D14-CDAE-4178-938A-268438059B7C}'] /// <summary>得到二维码</summary> procedure onAuthGotQrcode(image: UIImage); cdecl; /// <summary>二维码被扫描</summary> procedure onQrcodeScanned; cdecl; /// <summary>成功登录</summary> procedure onAuthFinish(errCode: Integer; authCode: NSString); cdecl; end; TiOSWechatRequest = class(TInterfacedObject, IWechatRequest) private function getOpenID: String; procedure setOpenID(const AValue: String); function getTansaction: String; procedure setTransaction(const AValue: String); property openID: String read getOpenID write setOpenID; property Transaction: String read getTansaction write setTransaction; public constructor Create(AReq: BaseReq); overload; end; TiOSWechatResponse = class(TInterfacedObject, IWechatResponse) private FType: Integer; FErrorMsg: String; FErrorCode: Integer; function getErrorCode: Integer; procedure setErrorCode(const acode: Integer); function getErrorMsg: String; procedure setErrorMsg(const AValue: String); function getRespType: Integer; property ErrorCode: Integer read getErrorCode write setErrorCode; property ErrorMsg: String read getErrorMsg write setErrorMsg; public constructor Create(const AUrl: TUri); end; TiWechatPayResponse = class(TiOSWechatResponse, IWechatPayResponse) private FReturnKey, FPrepayId, FExtData: String; FPayResult: TWechatPayResult; function getPrepayId: String; procedure setPrepayId(const AVal: String); function getReturnKey: String; procedure setReturnKey(const AVal: String); function getExtData: String; procedure setExtData(const AVal: String); function getPayResult: TWechatPayResult; public constructor Create(const AUrl: TUri); property returnKey: String read FReturnKey write setReturnKey; end; TiOSWechatService = class; TiOSWXApiDelegate = class(TOCLocal, WXApiDelegate) protected [weaked] FService: TiOSWechatService; public procedure onReq(req: BaseReq); cdecl; procedure onResp(resp: BaseResp); cdecl; end; TiOSWechatService = class(TInterfacedObject, IWechatService) private FScene: Integer; FAppId: String; FMchId: String; FDevId: String; FPayKey: String; FMsgId: Integer; FLastErrorMsg: String; FLastError: Integer; FSigner: IWechatSigner; FRegistered: Boolean; FOnRequest: TWechatRequestEvent; FOnResponse: TWechatResponseEvent; procedure DoReq(P1: BaseReq); cdecl; protected { WXApiDelegate } FDelegate: TiOSWXApiDelegate; function Registered: Boolean; procedure DoAppEvent(const Sender: TObject; const M: TMessage); function BitmapToNSData(ABitmap: TBitmap): NSData; public constructor Create; overload; procedure Unregister; function IsInstalled: Boolean; function getAppId: String; function OpenWechat: Boolean; function IsAPISupported: Boolean; function SendRequest(ARequest: IWechatRequest): Boolean; function SendResponse(AResp: IWechatResponse): Boolean; function getOnRequest: TWechatRequestEvent; procedure setOnRequest(const AEvent: TWechatRequestEvent); function getOnResponse: TWechatResponseEvent; procedure setOnResponse(const AEvent: TWechatResponseEvent); procedure setAppID(const AId: String); function OpenUrl(const AUrl: String): Boolean; function SendText(const atext: String; ASession: TWechatSession): Boolean; function ShareText(ATarget: TWechatSession; const S: String): Boolean; function ShareWebPage(ATarget: TWechatSession; const ATitle, AContent, AUrl: String; APicture: TBitmap): Boolean; function ShareBitmap(ATarget: TWechatSession; ABitmap: TBitmap): Boolean; function CreateObject(AObjId: TGuid): IWechatObject; function getMchId: String; procedure setMchId(const AId: String); function getDevId: String; procedure setDevId(const AId: String); function Pay(aprepayId, anonceStr, asign: String; atimeStamp: Integer): Boolean; procedure EnableSignCheck(ASigner: IWechatSigner); function getPayKey: String; procedure setPayKey(const AKey: String); end; const /// <summary>发送场景:聊天界面</summary> WXSceneSession = 0; /// <summary>发送场景:朋友圈</summary> WXSceneTimeline = 1; /// <summary>发送场景:收藏</summary> WXSceneFavorite = 2; /// <summary>跳转profile类型:普通公众号</summary> WXBizProfileType_Normal = 0; /// <summary>跳转profile类型:硬件公众号</summary> WXBizProfileType_Device = 1; /// <summary>跳转profile网页版类型:广告网页</summary> WXMPWebviewType_Ad = 0; /// <summary>成功</summary> WXSuccess = 0; /// <summary>普通错误类型</summary> WXErrCodeCommon = -1; /// <summary>用户点击取消并返回</summary> WXErrCodeUserCancel = -2; /// <summary>发送失败</summary> WXErrCodeSentFail = -3; /// <summary>授权失败</summary> WXErrCodeAuthDeny = -4; /// <summary>微信不支持</summary> WXErrCodeUnsupport = -5; WXAPISupportSession = 0; // 应用支持接收微信的文件类型 MMAPP_SUPPORT_NOCONTENT = $0; MMAPP_SUPPORT_TEXT = $1; MMAPP_SUPPORT_PICTURE = $2; MMAPP_SUPPORT_LOCATION = $4; MMAPP_SUPPORT_VIDEO = $8; MMAPP_SUPPORT_AUDIO = $10; MMAPP_SUPPORT_WEBPAGE = $20; // Suport File Type MMAPP_SUPPORT_DOC = $40; // doc MMAPP_SUPPORT_DOCX = $80; // docx MMAPP_SUPPORT_PPT = $100; // ppt MMAPP_SUPPORT_PPTX = $200; // pptx MMAPP_SUPPORT_XLS = $400; // xls MMAPP_SUPPORT_XLSX = $800; // xlsx MMAPP_SUPPORT_PDF = $1000; // pdf WechatAuth_Err_Ok = 0; // Auth成功 WechatAuth_Err_NormalErr = -1; // 普通错误 WechatAuth_Err_NetworkErr = -2; // 网络错误 WechatAuth_Err_GetQrcodeFailed = -3; // 获取二维码失败 WechatAuth_Err_Cancel = -4; // 用户取消授权 WechatAuth_Err_Timeout = -5; // 超时 ERR_OK = 0; ERR_COMM = -1; ERR_USER_CANCEL = -2; ERR_SENT_FAILED = -3; ERR_AUTH_DENIED = -4; ERR_UNSUPPORT = -5; ERR_BAN = -6; procedure RegisterWechatService; implementation {$IF DEFINED(IOS) AND DEFINED(CPUARM)} {$O-} const CoreTelephonyFwk = '/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony'; function WXApi_FakeLoader: WXApi; cdecl; external 'libWeChatSDK.a' name 'OBJC_CLASS_$_WXApi'; function CoreTelephonyFakeLoader: NSString; cdecl; external CoreTelephonyFwk name 'OBJC_CLASS_$_CTTelephonyNetworkInfo'; {$O+} {$ENDIF} { TiOSWechatService } function TiOSWechatService.BitmapToNSData(ABitmap: TBitmap): NSData; var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try ABitmap.SaveToStream(AStream); Result := TNSData.Wrap(TNSData.alloc.initWithBytes(AStream.Memory, AStream.Size)); finally FreeAndNil(AStream); end; end; constructor TiOSWechatService.Create; var ASvc: IFMXApplicationEventService; begin inherited Create; FDevId := 'APP'; FMsgId := TMessageManager.DefaultManager.SubscribeToMessage (TApplicationEventMessage, DoAppEvent); FDelegate := TiOSWXApiDelegate.Create; FDelegate.FService := Self; end; function TiOSWechatService.CreateObject(AObjId: TGuid): IWechatObject; begin end; procedure TiOSWechatService.DoAppEvent(const Sender: TObject; const M: TMessage); var AMsg: TApplicationEventMessage absolute M; AContext: TiOSOpenApplicationContext; AUri: TUri; AResp: PayResp; AValue: String; begin if Assigned(FOnResponse) then begin if AMsg.Value.Event = TApplicationEvent.OpenUrl then begin AContext := AMsg.Value.Context as TiOSOpenApplicationContext; AUri := TUri.Create(AContext.url); if AUri.Host = 'pay' then FOnResponse(TiWechatPayResponse.Create(AUri)) else FOnResponse(TiOSWechatResponse.Create(AUri)); end; end; end; function TiOSWechatService.getAppId: String; begin Result := FAppId; end; function TiOSWechatService.getDevId: String; begin Result := FDevId; end; function TiOSWechatService.getMchId: String; begin Result := FMchId; end; function TiOSWechatService.getOnRequest: TWechatRequestEvent; begin Result := FOnRequest; end; function TiOSWechatService.getOnResponse: TWechatResponseEvent; begin Result := FOnResponse; end; function TiOSWechatService.getPayKey: String; begin Result := FPayKey; end; function TiOSWechatService.IsAPISupported: Boolean; begin Result := TWXApi.OCClass.isWXAppSupportApi; end; function TiOSWechatService.IsInstalled: Boolean; begin Result := Registered and TWXApi.OCClass.isWXAppInstalled; end; procedure TiOSWechatService.DoReq(P1: BaseReq); begin if Assigned(FOnRequest) then FOnRequest(TiOSWechatRequest.Create(P1)); end; procedure TiOSWechatService.EnableSignCheck(ASigner: IWechatSigner); begin FSigner := ASigner; end; function TiOSWechatService.OpenUrl(const AUrl: String): Boolean; begin end; function TiOSWechatService.OpenWechat: Boolean; begin end; function TiOSWechatService.Pay(aprepayId, anonceStr, asign: String; atimeStamp: Integer): Boolean; const PrepayUrl = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; var AReq: PayReq; AExpectSign: String; begin AReq := TPayReq.Create; // AReq .appid := StringToJString(FAppId); AReq.setPartnerId(StrToNSStr(FMchId)); AReq.setPrepayId(StrToNSStr(aprepayId)); AReq.setPackage(StrToNSStr('Sign=WXPay')); AReq.setNonceStr(StrToNSStr(anonceStr)); AReq.setTimeStamp(atimeStamp); AReq.setSign(StrToNSStr(asign)); if Assigned(FSigner) then begin FSigner.Clear; FSigner.Add('appid', FAppId); FSigner.Add('partnerid', FMchId); FSigner.Add('prepayid', aprepayId); FSigner.Add('noncestr', anonceStr); FSigner.Add('package', 'Sign=WXPay'); FSigner.Add('timestamp', IntToStr(atimeStamp)); AExpectSign := FSigner.Sign; if AExpectSign <> ASign then raise Exception.CreateFmt(SSignMismatch, [ASign, AExpectSign]); end; Debugout('WXPay Start with PrepayId %s,NonceStr %s,Timestamp %d ,Sign %s', [aprepayId, anonceStr, atimeStamp, asign]); Result := Registered and TWXApi.OCClass.sendReq(AReq); end; function TiOSWechatService.Registered: Boolean; begin if not FRegistered then begin FRegistered := TWXApi.OCClass.registerApp(StrToNSStr(FAppId)); end; Result := FRegistered; end; function TiOSWechatService.SendRequest(ARequest: IWechatRequest): Boolean; begin end; function TiOSWechatService.SendResponse(AResp: IWechatResponse): Boolean; begin end; function TiOSWechatService.SendText(const atext: String; ASession: TWechatSession): Boolean; begin end; procedure TiOSWechatService.setAppID(const AId: String); begin FAppId := AId; end; procedure TiOSWechatService.setDevId(const AId: String); begin FDevId := AId; end; procedure TiOSWechatService.setMchId(const AId: String); begin FMchId := AId; end; procedure TiOSWechatService.setOnRequest(const AEvent: TWechatRequestEvent); begin FOnRequest := AEvent; end; procedure TiOSWechatService.setOnResponse(const AEvent: TWechatResponseEvent); begin FOnResponse := AEvent; end; procedure TiOSWechatService.setPayKey(const AKey: String); begin FPayKey := AKey; end; function TiOSWechatService.ShareBitmap(ATarget: TWechatSession; ABitmap: TBitmap): Boolean; var msg: WXMediaMessage; imgObj: WXImageObject; req: SendMessageToWXReq; begin imgObj := TWXImageObject.OCClass._object; imgObj.setImageData(BitmapToNSData(ABitmap)); msg := TWXMediaMessage.OCClass.message; msg.setMediaObject((imgObj as ILocalObject).GetObjectID); if Assigned(ABitmap) then msg.setThumbData(BitmapToNSData(ABitmap)) else msg.setThumbData(nil); req := TSendMessageToWXReq.Create; req.setBText(false); req.setMessage(msg); case ATarget of Session: req.setScene(WXSceneSession); Timeline: req.setScene(WXSceneTimeline); Favorite: req.setScene(WXSceneFavorite); end; Result := Registered and TWXApi.OCClass.sendReq(req); end; function TiOSWechatService.ShareText(ATarget: TWechatSession; const S: String): Boolean; var req: SendMessageToWXReq; begin req := TSendMessageToWXReq.Create; req.setBText(true); req.setText(StrToNSStr(S)); case ATarget of Session: req.setScene(WXSceneSession); Timeline: req.setScene(WXSceneTimeline); Favorite: req.setScene(WXSceneFavorite); end; Result := Registered and TWXApi.OCClass.sendReq(req); end; function TiOSWechatService.ShareWebPage(ATarget: TWechatSession; const ATitle, AContent, AUrl: String; APicture: TBitmap): Boolean; var msg: WXMediaMessage; webpage: WXWebpageObject; req: SendMessageToWXReq; begin webpage := TWXWebpageObject.OCClass._object; webpage.setWebpageUrl(StrToNSStr(AUrl)); msg := TWXMediaMessage.OCClass.message; msg.setTitle(StrToNSStr(ATitle)); msg.setDescription(StrToNSStr(AContent)); msg.setMediaObject((webpage as ILocalObject).GetObjectID); if Assigned(APicture) then msg.setThumbData(BitmapToNSData(APicture)) else msg.setThumbData(nil); req := TSendMessageToWXReq.Create; req.setBText(false); req.setMessage(msg); case ATarget of Session: req.setScene(WXSceneSession); Timeline: req.setScene(WXSceneTimeline); Favorite: req.setScene(WXSceneFavorite); end; Result := Registered and TWXApi.OCClass.sendReq(req); end; procedure TiOSWechatService.Unregister; begin end; procedure RegisterWechatService; begin TPlatformServices.Current.AddPlatformService(IWechatService, TiOSWechatService.Create); end; { TiOSWechatRequest } constructor TiOSWechatRequest.Create(AReq: BaseReq); begin inherited Create; end; function TiOSWechatRequest.getOpenID: String; begin end; function TiOSWechatRequest.getTansaction: String; begin end; procedure TiOSWechatRequest.setOpenID(const AValue: String); begin end; procedure TiOSWechatRequest.setTransaction(const AValue: String); begin end; { TiOSWechatResponse } constructor TiOSWechatResponse.Create(const AUrl: TUri); var I: Integer; begin inherited Create; for I := 0 to High(AUrl.Params) do begin if AUrl.Params[I].Name = 'ret' then begin FErrorCode := StrToIntDef(AUrl.Params[I].Value, 0); case FErrorCode of ERR_OK: FErrorMsg := '操作已成功完成'; ERR_COMM: FErrorMsg := '通讯错误'; ERR_USER_CANCEL: FErrorMsg := '用户已取消操作'; ERR_SENT_FAILED: FErrorMsg := '发送请求失败'; ERR_AUTH_DENIED: FErrorMsg := '认证失败'; ERR_UNSUPPORT: FErrorMsg := '不支持的操作'; ERR_BAN: FErrorMsg := '操作被阻止'; end; end; end; end; function TiOSWechatResponse.getErrorCode: Integer; begin Result := FErrorCode; end; function TiOSWechatResponse.getErrorMsg: String; begin Result := FErrorMsg; end; function TiOSWechatResponse.getRespType: Integer; begin Result := FType; end; procedure TiOSWechatResponse.setErrorCode(const acode: Integer); begin FErrorCode := acode; end; procedure TiOSWechatResponse.setErrorMsg(const AValue: String); begin FErrorMsg := AValue; end; { TiOSWXApiDelegate } procedure TiOSWXApiDelegate.onReq(req: BaseReq); begin FService.DoReq(req); end; procedure TiOSWXApiDelegate.onResp(resp: BaseResp); begin // Not used,use openurl direct end; { TiWechatPayResponse } constructor TiWechatPayResponse.Create(const AUrl: TUri); var APayResp: PayResp; I: Integer; const COMMAND_PAY_BY_WX = 5; begin inherited Create(AUrl); FType := COMMAND_PAY_BY_WX; for I := 0 to High(AUrl.Params) do begin if AUrl.Params[I].Name = 'returnKey' then begin FReturnKey := AUrl.Params[I].Value; break; end; end; if FReturnKey = '(null)' then FReturnKey := ''; case FErrorCode of ERR_OK: FPayResult := TWechatPayResult.wprOk; ERR_USER_CANCEL: FPayResult := TWechatPayResult.wprCancel else FPayResult := TWechatPayResult.wprError; end; end; function TiWechatPayResponse.getExtData: String; begin Result := FExtData; end; function TiWechatPayResponse.getPayResult: TWechatPayResult; begin Result := FPayResult; end; function TiWechatPayResponse.getPrepayId: String; begin Result := FPrepayId; // iOS 不支持 end; function TiWechatPayResponse.getReturnKey: String; begin Result := FReturnKey; end; procedure TiWechatPayResponse.setExtData(const AVal: String); begin FExtData := AVal; end; procedure TiWechatPayResponse.setPrepayId(const AVal: String); begin FPrepayId := AVal; end; procedure TiWechatPayResponse.setReturnKey(const AVal: String); begin FReturnKey := AVal; end; end.
unit MainForm; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses VirtualTrees, Types, Messages, Classes, Graphics, Controls, Forms, SysUtils, IniFiles, Dialogs, StdCtrls, ImgList, ExtCtrls, XPMan, {$Ifdef Win32}FileCtrl{$Endif}, ComCtrls, Menus; type rSettings = record SmartAdd : Boolean; ShowIcons : Boolean; SizeBinary : Boolean; ProgMkSquash : String; ProgUnSquash : String; ProgChmod : String; ParamMkSquash : String; ParamUnSquash : String; ParamChmod : String; SchemaFile : String; end; TfrmMain = class(TForm) imlFileTree: TImageList; pnlButtons: TPanel; btnCreate: TButton; opdFileAny: TOpenDialog; opdPXML: TOpenDialog; opdIcon: TOpenDialog; sadPND: TSaveDialog; grbLog: TGroupBox; redLog: TRichEdit; opdPND: TOpenDialog; menMain: TMainMenu; menMainFile: TMenuItem; menMainHelp: TMenuItem; menMainHelpAbout: TMenuItem; menMainFileOpen: TMenuItem; pomFiles: TPopupMenu; pomFilesOpen: TMenuItem; N1: TMenuItem; menMainHelpPXML: TMenuItem; menMainHelpPND: TMenuItem; grbFiles: TGroupBox; vstFiles: TVirtualStringTree; pnlFilesButtons: TPanel; btnFilesClear: TButton; btnFilesFolder: TButton; btnFilesFile: TButton; cbxRecursive: TCheckBox; pnlFilesInfo: TPanel; lblFilesSizeLbl: TLabel; lblFilesSize: TLabel; grbIcon: TGroupBox; edtIcon: TEdit; btnIconLoad: TButton; grbPXML: TGroupBox; btnPXMLLoad: TButton; edtPXML: TEdit; btnIconClear: TButton; btnPXMLClear: TButton; N2: TMenuItem; menMainFileOptions: TMenuItem; N3: TMenuItem; menMainFileExit: TMenuItem; btnPXMLEdit: TButton; pomFilesDelete: TMenuItem; procedure pomFilesDeleteClick(Sender: TObject); procedure edtPXMLChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure menMainFileOptionsClick(Sender: TObject); procedure menMainFileExitClick(Sender: TObject); procedure btnPXMLClearClick(Sender: TObject); procedure btnIconClearClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnPXMLEditClick(Sender: TObject); procedure grbLogDblClick(Sender: TObject); procedure menMainHelpPNDClick(Sender: TObject); procedure menMainHelpPXMLClick(Sender: TObject); procedure menMainHelpAboutClick(Sender: TObject); procedure vstFilesNodeMoving(Sender: TBaseVirtualTree; Node, Target: PVirtualNode; var Allowed: Boolean); procedure vstFilesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure pomFilesOpenClick(Sender: TObject); procedure vstFilesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure menMainFileOpenClick(Sender: TObject); procedure vstFilesStructureChange(Sender: TBaseVirtualTree; Node: PVirtualNode; Reason: TChangeReason); procedure vstFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCreateClick(Sender: TObject); procedure btnFilesFolderClick(Sender: TObject); procedure btnFilesFileClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure vstFilesGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstFilesHeaderClick(Sender: TVTHeader; Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure vstFilesCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure vstFilesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure vstFilesDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); procedure btnIconLoadClick(Sender: TObject); procedure btnPXMLLoadClick(Sender: TObject); procedure btnFilesClearClick(Sender: TObject); private { Copies the tree file-data (represented by the nodes) to the passed folder Uses CopyFileEx internally } procedure CopyTreeToFolder(Tree : TBaseVirtualTree; const TargetDir : String); { Extracts PXML and Icon data (if found) from an already open PND file stream and saves them to the passed filenames. Filenames are changed to '' if no file has been saved } procedure ExtractPNDMetaData(Stream : TFileStream; var PXML : String; var Icon : String); procedure ReadFormSettings(const Ini : TIniFile; Frm : TForm); procedure WriteFormSettings(Ini : TIniFile; const Frm : TForm); public Settings : rSettings; const PXML_PATH : String = 'PXML.xml'; const ICON_PATH : String = 'icon.png'; const PND_EXT : String = '.pnd'; const LOG_ERROR_COLOR : TColor = clRed; const LOG_WARNING_COLOR : TColor = $0000AAFF; const LOG_SUCCESS_COLOR : TColor = clGreen; procedure LogLine(const TextToAdd : String; const Color: TColor = clBlack); procedure OpenPND(const FileName : String); procedure SavePND(const FileName : String; const PXML : String; const Icon : String); procedure LoadSettings(const FileName : String; var S : rSettings); procedure SaveSettings(const FileName : String; const S : rSettings); end; const VERSION : String = '0.5.1'; BUILD_DATE : String = '26.01.2013'; UNSQUASHFS_PATH : String = 'tools\unsquashfs.exe'; MKSQUASH_PATH : String = 'tools\mksquashfs.exe'; // Path to mkquashfs CHMOD_PATH : String = 'tools\chmod.exe'; // Path to cygwin's chmod SETTINGS_PATH : String = 'settings.ini'; SCHEMA_PATH : String = 'tools\PXML_schema.xml'; SOURCE_VAR : String = '%source%'; TARGET_VAR : String = '%target%'; var frmMain: TfrmMain; implementation {$R *.dfm} // DONE: Graphical browser and editor for the PXML // TODO: Display icon // TODO: Ask for overwrite on copy // DONE: Open PND // DONE: Show total uncompressed size // DONE: Clear temp folder on exit and start // DONE: Check for write access on start // DONE: Function for proper conversion from Windows to Cygwin POSIX path // TODO: Pass all external paths to function for WinLin conversion // TODO: Add option for extraction behaviour (user path, program path, ask) uses VSTUtils, FormatUtils, FileUtils, OptionsForm, PXMLForm, CreatorForm, {$Ifdef Win32} VSTDragDrop_win, VSTIcons_win, ShellStuff_win, ControlHideFix; {$Else} {These files have yet to be created and the Windows code ported over} VSTDragDrop_lin, VSTIcons_lin, ShellStuff_lin; {$Endif} // --- Functions --------------------------------------------------------------- procedure TfrmMain.CopyTreeToFolder(Tree : TBaseVirtualTree; const TargetDir : String); var Source : String; Destination : String; begin CopyTreeData(Tree,Tree.GetFirst(),TargetDir,Source,Destination); if ShellCopyFile(Source,Destination,false) then begin LogLine('Copied all files to temporary directory '#13#10 + TargetDir, LOG_SUCCESS_COLOR); end else begin LogLine('An error occurred when copying the files to the temporary ' + 'folder ' + #13#10 + TargetDir + #13#10 + 'Check whether you have right access to it and no file is ' + 'currently in use by another application.' + #13#10 + 'The error code was: ' + IntToStr(GetLastError()), LOG_ERROR_COLOR); end; end; procedure TfrmMain.ExtractPNDMetaData(Stream : TFileStream; var PXML : String; var Icon : String); const Header : String = '<?xml'; FallbackHeader : String = '<PXML'; Footer : String = '</PXML>'; var OutputStream : TFileStream; Pos : Int64; NumRead, NumWrite : Integer; Buffer : Array [Word] of Byte; begin // find PXML data LogLine('Looking for PXML data...'); Pos := FindStringDataInStream(Header,Stream,0,true); if Pos = -1 then begin Pos := FindStringDataInStream(FallbackHeader,Stream,0,true); if Pos = -1 then begin LogLine('No PXML data found!',LOG_ERROR_COLOR); PXML := ''; Icon := ''; Exit; end else LogLine('PXML file missing proper xml header, you should fix ' + 'that, check the PXML specification for details', LOG_WARNING_COLOR); end; // write PXML data to a file LogLine('PXML data found, writing to file ' + PXML); OutputStream := TFileStream.Create(PXML,fmCreate); try Pos := FindStringDataInStream(Footer,Stream,Pos,false,OutputStream); finally OutputStream.Free; end; // search for PNG header and extract PNG data // TODO: Search for other image types, too Pos := FindStringDataInStream(Chr(137) + 'PNG',Stream,Pos); if Pos <> -1 then begin LogLine('Icon data found, writing to file ' + Icon); OutputStream := TFileStream.Create(Icon,fmCreate); try Stream.Seek(Pos,soFromBeginning); repeat NumRead := Stream.Read(Buffer,SizeOf(Buffer)); NumWrite := OutputStream.Write(Buffer,NumRead); until (NumRead = 0) OR (NumRead <> NumWrite); finally OutputStream.Free; end; end else begin LogLine('No icon data found in PND',LOG_WARNING_COLOR); Icon := ''; end; LogLine('PND metadata successfully extracted',LOG_SUCCESS_COLOR); end; procedure TfrmMain.LogLine(const TextToAdd : String; const Color: TColor = clBlack); var Count : Integer; begin Count := Length(redLog.Text); redLog.Lines.Add(TextToAdd); redLog.SelStart := count; redLog.SelLength := Length(redLog.Text) - redLog.SelStart; redLog.SelAttributes.Color := Color; redLog.SelLength := 0; end; procedure TfrmMain.OpenPND(const FileName: string); const TEMP_PATH : String = 'temp2'; // Relative path (from the .exe) to the temporary folder META_PATH : String = 'meta'; // Relative path to the meta folder (for PXML and Icon) var Stream : TFileStream; PXML, Icon, Prog, Param : String; temp : Boolean; begin // clean-up vstFiles.Clear; edtPXML.Clear; edtIcon.Clear; LogLine('Deleting old temporary files'); Param := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName) + META_PATH); PXML := Param + PXML_PATH; Icon := Param + ICON_PATH; ShellDeleteFile(PXML); ShellDeleteFile(Icon); Param := ExtractFilePath(Application.ExeName) + TEMP_PATH; ShellDeleteFile(Param); CreateDir(Param); CreateDir(ExtractFilePath(Application.ExeName) + META_PATH); // extract PXML and Icon Stream := TFileStream.Create(FileName,fmOpenRead); try ExtractPNDMetaData(Stream,PXML,ICON); finally Stream.Free; end; // Unsquash the PND LogLine('Extracting PND... this might take a while'); Prog := Settings.ProgUnSquash; Param := StringReplace(Settings.ParamUnSquash,SOURCE_VAR,ConvertPath(FileName),[rfReplaceAll]); Param := StringReplace(Param,TARGET_VAR,ConvertPath(TEMP_PATH),[rfReplaceAll]); LogLine('Calling program: ' + Prog + ' ' + Param); if not ExecuteProgram(Prog,Param) then begin MessageDlg('Encountered an error while extracting PND' + #13#10 + 'Error code: ' + IntToStr(GetLastError),mtError,[mbOK],0); Exit; end; LogLine('Adding files to tree, this might take a while...'); // add files to tree vstFiles.BeginUpdate; temp := Settings.SmartAdd; Settings.SmartAdd := false; try AddFolder(vstFiles,nil,ExtractFilePath(Application.ExeName) + TEMP_PATH,true); finally vstFiles.EndUpdate; end; Settings.SmartAdd := temp; vstFiles.SortTree(0,vstFiles.Header.SortDirection); edtPXML.Text := PXML; edtIcon.Text := Icon; if vstFiles.GetFirst = nil then LogLine('No files have been added, this most likely is due to an ' + 'error while extracting the PND.'#13#10 + 'The PND might use the ISO file-system, in which case you can '+ 'simply open it in a program like 7-zip or WinRAR.',LOG_ERROR_COLOR) else LogLine('PND successfully extracted to ' + ExtractFilePath(Application.ExeName) + TEMP_PATH,LOG_SUCCESS_COLOR); end; procedure TfrmMain.SavePND(const FileName : String; const PXML : String; const Icon : String); const TEMP_PATH : String = 'temp'; // Relative path (from the .exe) to the temporary folder var Prog, Param : String; PNDFile : TFileStream; Return : Integer; NoPXML : Boolean; begin NoPXML := false; if (PXML = '') OR (not FileExists(PXML)) then begin Return := MessageDlg('No PXML file was specified or the entered filename ' + 'could not be loaded!'#13#10 + 'This file is mandatory for the PND to work!', mtWarning,[mbAbort,mbIgnore],0); if Return = mrAbort then Exit; NoPXML := true; end; // temporary data handling Param := ExtractFilePath(Application.ExeName) + TEMP_PATH; LogLine('Deleting old temporary files'); ShellDeleteFile(Param); // clean-up LogLine('Copying new temporary files to folder ' + Param + ' - This may ' + 'take a while.'); CopyTreeToFolder(vstFiles,Param); // set corrent file flags to work on the Pandora Prog := Settings.ProgChmod; Param := StringReplace(Settings.ParamChmod,SOURCE_VAR,ConvertPath(TEMP_PATH),[rfReplaceAll]); LogLine('Calling program: ' + Prog + ' ' + Param); if not ExecuteProgram(Prog,Param) then begin MessageDlg('Encountered an error while trying to set file flags' + #13#10 + 'Error code: ' + IntToStr(GetLastError),mtError,[mbOK],0); Exit; end; // Make the squashFS filesystem from the temporary files Prog := Settings.ProgMkSquash; Param := StringReplace(Settings.ParamMkSquash,SOURCE_VAR,ConvertPath(TEMP_PATH),[rfReplaceAll]); Param := StringReplace(Param,TARGET_VAR,ConvertPath(FileName),[rfReplaceAll]); LogLine('Calling program: ' + Prog + ' ' + Param); if not ExecuteProgram(Prog,Param) then begin MessageDlg('Encountered an error while creating SquashFS archive' + #13#10 + 'Error code: ' + IntToStr(GetLastError),mtError,[mbOK],0); Exit; end; // append PXML and icon LogLine('Appending icon and PXML data (if found).'); PNDFile := TFileStream.Create(FileName,fmOpenReadWrite); try if not NoPXML then AppendDataToFileStream(PNDFile,PXML) else LogLine('Creating PND without PXML data (you should not do this!)', LOG_WARNING_COLOR); if (Icon <> '') AND FileExists(Icon) then AppendDataToFileStream(PNDFile,Icon) else LogLine('No icon found or icon could not be accessed', LOG_WARNING_COLOR); finally PNDFile.Free; end; LogLine('PND created successfully: ' + FileName,LOG_SUCCESS_COLOR); end; procedure TfrmMain.LoadSettings(const FileName: string; var S: rSettings); var Ini : TIniFile; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + FileName); try with S do begin SmartAdd := Ini.ReadBool('General','SmartAdd',true); ShowIcons := Ini.ReadBool('General','ShowIcons',true); SizeBinary := Ini.ReadBool('General','SizeBinary',false); ProgMkSquash := Ini.ReadString('Paths','MkSquash',MKSQUASH_PATH); ProgUnSquash := Ini.ReadString('Paths','UnSquash',UNSQUASHFS_PATH); ProgChmod := Ini.ReadString('Paths','Chmod',CHMOD_PATH); ParamMkSquash := Ini.ReadString('Params','MkSquash','"' + SOURCE_VAR + '" "' + TARGET_VAR + '" -nopad -no-recovery -noappend'); ParamUnSquash := Ini.ReadString('Params','UnSquash','-f -d "' + TARGET_VAR + '" "' + SOURCE_VAR + '"'); ParamChmod := Ini.ReadString('Params','Chmod','-R 755 "' + SOURCE_VAR + '"'); SchemaFile := Ini.ReadString('Paths','Schema',SCHEMA_PATH); end; ReadFormSettings(Ini,frmMain); ReadFormSettings(Ini,frmPXML); ReadFormSettings(Ini,frmCreator); finally Ini.Free; end; end; procedure TfrmMain.SaveSettings(const FileName: string; const S: rSettings); var Ini : TIniFile; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + FileName); try with S do begin Ini.WriteBool('General','SmartAdd',SmartAdd); Ini.WriteBool('General','ShowIcons',ShowIcons); Ini.WriteBool('General','SizeBinary',SizeBinary); Ini.WriteString('Paths','MkSquash',ProgMkSquash); Ini.WriteString('Paths','UnSquash',ProgUnSquash); Ini.WriteString('Paths','Chmod',ProgChmod); Ini.WriteString('Params','MkSquash',ParamMkSquash); Ini.WriteString('Params','UnSquash',ParamUnSquash); Ini.WriteString('Params','Chmod',ParamChmod); Ini.WriteString('Paths','Schema',SchemaFile); end; WriteFormSettings(Ini,frmMain); WriteFormSettings(Ini,frmPXML); WriteFormSettings(Ini,frmCreator); finally Ini.Free; end; end; procedure TfrmMain.ReadFormSettings(const Ini: TIniFile; Frm: TForm); begin with Frm do begin Width := Ini.ReadInteger(Name,'Width',Frm.Constraints.MinWidth); Height := Ini.ReadInteger(Name,'Height',Frm.Constraints.MinHeight); Left := Ini.ReadInteger(Name,'Left',100); Top := Ini.ReadInteger(Name,'Top',100); end; end; procedure TfrmMain.WriteFormSettings(Ini: TIniFile; const Frm: TForm); begin with Frm do begin Ini.WriteInteger(Name,'Width',Width); Ini.WriteInteger(Name,'Height',Height); Ini.WriteInteger(Name,'Left',Left); Ini.WriteInteger(Name,'Top',Top); end; end; // --- Menu -------------------------------------------------------------------- procedure TfrmMain.menMainFileExitClick(Sender: TObject); begin Close; end; procedure TfrmMain.menMainFileOpenClick(Sender: TObject); begin // error checking if not FileExists(ExtractFilePath(Application.ExeName) + UNSQUASHFS_PATH) then begin MessageDlg('The squashFS tools could not be found!'#13#10 + 'Please make sure they are located in the ''tools'' folder next to the ' + 'program executable.',mtError,[mbOK],0); Exit; end; if vstFiles.GetFirst <> nil then begin if MessageDlg('Opening a PND will clear your current file-tree. Proceed?', mtWarning,[mbYes,mbNo],0) = mrNo then Exit; end; if not opdPND.Execute then Exit; OpenPND(opdPND.FileName); end; procedure TfrmMain.menMainFileOptionsClick(Sender: TObject); begin frmOptions.Left := frmMain.Left + (frmMain.Width - frmOptions.Width) div 2; frmOptions.Top := frmMain.Top + (frmMain.Height - frmOptions.Height) div 2; if frmOptions.Execute(Settings) then Settings := frmOptions.Settings; end; procedure TfrmMain.menMainHelpAboutClick(Sender: TObject); begin MessageDlg('PNDTools' + #13#10 + 'Created by Janek Schäfer (foxblock)' + #13#10 + 'Using Cygwin and SquashFStools', mtInformation,[mbOk],0); end; procedure TfrmMain.menMainHelpPNDClick(Sender: TObject); begin ExecuteProgram('http://pandorawiki.org/PND_quickstart','','','open',false); end; procedure TfrmMain.menMainHelpPXMLClick(Sender: TObject); begin ExecuteProgram('http://pandorawiki.org/PXML_specification','','','open',false); end; // --- Popup Menu -------------------------------------------------------------- procedure TfrmMain.pomFilesDeleteClick(Sender: TObject); begin vstFiles.DeleteSelectedNodes; end; procedure TfrmMain.pomFilesOpenClick(Sender: TObject); var Node : PVirtualNode; PData : PFileTreeData; begin Node := vstFiles.GetFirstSelected(); PData := vstFiles.GetNodeData(Node); if IsFile(vstFiles,Node) then ExecuteProgram(PData.Name,'','','open',false) else ExecuteProgram(PData.Name,'','','explore',false); end; // --- Form -------------------------------------------------------------------- procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings(SETTINGS_PATH,Settings); end; procedure TfrmMain.FormCreate(Sender: TObject); const TEST_FILE_NAME : String = 'asdftestxyz.txt'; var dummy : TDragEvent; jummy : TButtonEvent; F : File; begin // Check for write access by writing dummy file try AssignFile(F,TEST_FILE_NAME); ReWrite(F); CloseFile(F); ShellDeleteFile(TEST_FILE_NAME); except on E : Exception do begin MessageDlg('You do not have permission to write files in the folder ' + 'the program is located in'#13#10 + 'This functionality is mandatory for the program to work ' + 'properly'#13#10#13#10 + 'You can either move the program to a directory you have ' + 'write-access to (any except for the Programs, ' + 'Windows and User-folder should work) or run the program ' + 'as Administrator (Right-click -> Run as Administrator).' + #13#10#13#10 + 'The Program will now exit.',mtError,[mbOk],1); Application.Terminate; end; end; vstFiles.NodeDataSize := sizeof(rFileTreeData); dummy := TDragEvent.Create; vstFiles.OnDragDrop := dummy.VSTDragDrop; dummy.Free; {$Ifdef Win32} KeyPreview := true; jummy := TButtonEvent.Create; OnKeyDown := jummy.KeyDown; jummy.Free; {$Endif} LoadSystemIcons(imlFileTree); Caption := Caption + ' [Version ' + VERSION + ' built ' + BUILD_DATE + ']'; end; procedure TfrmMain.FormShow(Sender: TObject); begin LoadSettings(SETTINGS_PATH,Settings); if ParamCount > 0 then if FileExists(ParamStr(1)) then OpenPND(ParamStr(1)); end; procedure TfrmMain.grbLogDblClick(Sender: TObject); var C : TControl; begin C := (Sender as TControl); if C.Height = C.Constraints.MinHeight then C.Height := C.Constraints.MaxHeight else C.Height := C.Constraints.MinHeight; C.Top := pnlButtons.Top - C.Height; end; // --- Misc. ------------------------------------------------------------------- procedure TfrmMain.edtPXMLChange(Sender: TObject); begin if Length(edtPXML.Text) = 0 then btnPXMLEdit.Caption := 'Create PXML' else btnPXMLEdit.Caption := 'Edit PXML' end; // --- Files Tree -------------------------------------------------------------- procedure TfrmMain.vstFilesCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var PData1, PData2 : PFileTreeData; begin PData1 := Sender.GetNodeData(Node1); PData2 := Sender.GetNodeData(Node2); if Column = 0 then begin if (PData1.Attr and faDirectory > 0) XOR (PData2.Attr and faDirectory > 0) then begin if (PData1.Attr and faDirectory > 0) then Result := -1 else Result := 1; end else {$Ifdef Win32} Result := CompareText(ExtractFileName(PData1.Name), ExtractFileName(PData2.Name)); {$Else} Result := CompareStr(ExtractFileName(PData1.Name), ExtractFileName(PData2.Name)); {$Endif} end else if Column = 1 then begin if PData1.Size > PData2.Size then Result := 1 else Result := -1 end; end; procedure TfrmMain.vstFilesDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := true; end; procedure TfrmMain.vstFilesGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var PData : PFileTreeData; begin if (Column <> 0) OR (Kind = ikOverlay) then Exit; PData := Sender.GetNodeData(Node); if Sender.Expanded[Node] then ImageIndex := PData.OpenIndex else ImageIndex := PData.ClosedIndex; end; procedure TfrmMain.vstFilesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var PData : PFileTreeData; begin PData := Sender.GetNodeData(Node); case Column of 0 : CellText := ExtractFileName(PData.Name); 1 : begin if (PData.Attr and faDirectory = 0) then CellText := SizeToStr(PData.Size,Settings.SizeBinary) else CellText := ''; end; 2 : CellText := PData.Name; end; end; procedure TfrmMain.vstFilesHeaderClick(Sender: TVTHeader; Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Sender.SortColumn = Column then begin if Sender.SortDirection=sdAscending then Sender.SortDirection:=sdDescending else Sender.SortDirection:=sdAscending; end else Sender.SortColumn := Column; Sender.Treeview.SortTree(Column,Sender.SortDirection,True); end; procedure TfrmMain.vstFilesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var PData : PFileTreeData; begin PData := Sender.GetNodeData(Node); if Settings.ShowIcons then begin PData.ClosedIndex := GetIconIndex(PData.Name,false); PData.OpenIndex := GetIconIndex(PData.Name,true); end else begin if (PData.Attr and faDirectory = 0) then begin PData.ClosedIndex := 0; PData.OpenIndex := 0; end else begin PData.ClosedIndex := 1; PData.OpenIndex := 1; end; end; end; procedure TfrmMain.vstFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of 46 : // Entf begin vstFiles.DeleteSelectedNodes; end; end; end; procedure TfrmMain.vstFilesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Node : PVirtualNode; begin if Button = mbRight then begin Node := (Sender as TBaseVirtualTree).GetNodeAt(X,Y); if Node <> nil then begin (Sender as TBaseVirtualTree).ClearSelection; (Sender as TBaseVirtualTree).Selected[Node] := true; pomFiles.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y); end; end; end; procedure TfrmMain.vstFilesNodeMoving(Sender: TBaseVirtualTree; Node, Target: PVirtualNode; var Allowed: Boolean); var PData : PFileTreeData; begin PData := Sender.GetNodeData(Node); Allowed := (CheckForExistance(Sender,Sender.GetFirstChild(Target), ExtractFileName(PData.Name)) = nil); end; procedure TfrmMain.vstFilesStructureChange(Sender: TBaseVirtualTree; Node: PVirtualNode; Reason: TChangeReason); begin lblFilesSize.Caption := SizeToStr(CalculateTotalSize(vstFiles),Settings.SizeBinary); end; // --- Buttons ----------------------------------------------------------------- procedure TfrmMain.btnCreateClick(Sender: TObject); begin // error checking if not FileExists(ExtractFilePath(Application.ExeName) + MKSQUASH_PATH) OR not FileExists(ExtractFilePath(Application.ExeName) + CHMOD_PATH) then begin MessageDlg('The squashFS or chmod tools could not be found!'#13#10 + 'Please make sure they are located in the ''tools'' folder next to the ' + 'program executable.',mtError,[mbOK],0); Exit; end; if vstFiles.GetFirst() = nil then begin MessageDlg('No files added to the PND!',mtError,[mbOK],0); Exit; end; if not sadPND.Execute then Exit; SavePND(sadPND.FileName,edtPXML.Text,edtIcon.Text); end; procedure TfrmMain.btnFilesClearClick(Sender: TObject); begin vstFiles.Clear; end; procedure TfrmMain.btnFilesFileClick(Sender: TObject); var I : Integer; begin if opdFileAny.Execute then begin for I := 0 to opdFileAny.Files.Count - 1 do AddItem(vstFiles,vstFiles.GetFirstSelected(false),opdFileAny.Files[I]); vstFiles.SortTree(0,vstFiles.Header.SortDirection); end; end; procedure TfrmMain.btnFilesFolderClick(Sender: TObject); var Dir : String; begin // TODO: Yeah I guess this is not exactly cross-platform safe... {$Ifdef Win32} SelectDirectory('Select a directory to add','',Dir); {$Else} MessageDlg('This function is not implemented yet, sorry :(',mtInformation,[mbOK],0); btnFilesFolder.Enabled := false; {$Endif} if Dir <> '' then begin vstFiles.BeginUpdate; try AddItem(vstFiles,vstFiles.GetFirstSelected(),Dir,cbxRecursive.Checked); finally vstFiles.EndUpdate; end; vstFiles.SortTree(0,vstFiles.Header.SortDirection); end; end; procedure TfrmMain.btnIconClearClick(Sender: TObject); begin edtIcon.Clear; end; procedure TfrmMain.btnIconLoadClick(Sender: TObject); begin if opdIcon.Execute then edtIcon.Text := opdIcon.FileName; end; procedure TfrmMain.btnPXMLClearClick(Sender: TObject); begin edtPXML.Clear; end; procedure TfrmMain.btnPXMLEditClick(Sender: TObject); var temp : Integer; begin if (edtPXML.Text <> '') then begin if FileExists(edtPXML.Text) then begin frmPXML.LoadFromFile(edtPXML.Text); end else begin if MessageDlg('The specified PXML file does not exist!' + #13#10 + 'Do you want to create a new one from scratch?', mtWarning,[mbYes,mbNo],0) = mrYes then begin edtPXML.Clear; edtPXML.Text := frmPXML.CreateNewFile; end; end; end else begin temp := MessageDlg('Do you want PNDTools to assist you in the creation of the PXML file?'#13#10 + 'Choosing ''yes'' will launch the PXML wizard, which is great for beginners and suffices in most use-cases.'#13#10 + 'Choosing ''no'' will give you a full xml editor allowing for more advanced edits, but also gives less guidance and help.'#13#10 + 'NOTE: In any case you should add all data files beforehand (using the controls above).', mtConfirmation,[mbYes,mbNo,mbCancel],0); if temp = mrYes then begin if frmCreator.Execute then begin edtPXML.Text := frmCreator.Filename; edtIcon.Text := frmCreator.IconFilename; end; end else if temp = mrNo then edtPXML.Text := frmPXML.CreateNewFile; end; end; procedure TfrmMain.btnPXMLLoadClick(Sender: TObject); begin if opdPXML.Execute then edtPXML.Text := opdPXML.FileName; end; end.
unit UsbRelay; interface uses System.Classes, System.SysUtils, usb_relay_device; type TUsbRelay = class(Tobject) private hHandle: integer; Fdevicetype: integer; Fopen: boolean; FSerial: string; Fdevicepath: string; status:cardinal; function Getstate(index: integer): boolean; procedure refresh; procedure Setopen(const Value: boolean); procedure Setstate(index: integer; const Value: boolean); public constructor create(aSerial:string;aDevicetype:integer;aDevicepath:string); procedure openallchannels; procedure closeallchannels; property serial:string read FSerial; property devicetype: integer read Fdevicetype; property devicepath: string read Fdevicepath; property open: boolean read Fopen write Setopen; // !! index is 1-based !! property state[index: integer]: boolean read Getstate write Setstate; end; var UsbRelays : TStringList; procedure FindUsbRelays; function GetUsbRelayType(id:string):integer; function SetUsbRelayPort(id:string;port:integer;state:boolean):integer; implementation var UsbRelayOpened:boolean; function GetUsbRelayType(id:string):integer; var i:integer; UsbRelay:TUsbRelay; begin if Not UsbRelayOpened then FindUsbRelays; i:=UsbRelays.IndexOf(id); if i>=0 then begin UsbRelay:=TUsbRelay(UsbRelays.Objects[i]); result:=UsbRelay.devicetype; end else begin result:=0; end; end; function SetUsbRelayPort(id:string;port:integer;state:boolean):integer; var i:integer; UsbRelay:TUsbRelay; begin if Not UsbRelayOpened then FindUsbRelays; i:=UsbRelays.IndexOf(id); if i>=0 then begin UsbRelay:=TUsbRelay(UsbRelays.Objects[i]); UsbRelay.open:=true; UsbRelay.state[port]:=state; UsbRelay.open:=false; result:=0; end else begin result:=-1; end; end; procedure ClearRelayDevices; var I: Integer; UsbRelay:TUsbRelay; begin for I := 0 to UsbRelays.Count-1 do begin UsbRelay:=TUsbRelay(UsbRelays.Objects[i]); UsbRelay.closeallchannels; UsbRelay.open:=False; UsbRelay.Free; end; UsbRelays.Clear; end; procedure ListDevices; var origin, deviceinfo : pusb_relay_device_info; UsbRelay:TUsbRelay; begin if UsbRelayOpened then begin origin:=usb_relay_device_enumerate; deviceinfo:=origin; while assigned(deviceinfo) do begin UsbRelay:=TUsbRelay.create(deviceinfo.serial_number,deviceinfo.device_type,deviceinfo.device_path); UsbRelays.AddObject(deviceinfo.serial_number,UsbRelay); deviceinfo:=deviceinfo^.next; end; usb_relay_device_free_enumerate(origin); end; end; procedure FindUsbRelays; begin if UsbRelayOpened then begin ClearRelayDevices; ListDevices; end else begin if usb_relay_deviceDLLLoaded then begin if usb_relay_init=0 then begin UsbRelayOpened:=true; ListDevices; end; end; end; end; { TUsbRelay } procedure TUsbRelay.closeallchannels; begin if hHandle<>0 then usb_relay_device_close_all_relay_channel(hHandle); refresh; end; constructor TUsbRelay.create(aSerial: string; aDevicetype: integer; aDevicepath: string); begin FSerial:=aSerial; Fdevicetype:=aDevicetype; Fdevicepath:=aDevicepath; end; function TUsbRelay.Getstate(index: integer): boolean; begin result:=((1 SHL (index-1)) and status)<> 0; end; procedure TUsbRelay.openallchannels; begin if hHandle<>0 then usb_relay_device_open_all_relay_channel(hHandle); refresh; end; procedure TUsbRelay.refresh; var tempstatus : cardinal; begin if hHandle<>0 then begin usb_relay_device_get_status(hHandle,@tempstatus); status:=tempstatus; end else status:=0; end; {$X+} procedure TUsbRelay.Setopen(const Value: boolean); var buffer:array[0..5] of ansichar; begin if UsbRelayOpened then begin if Value<>Fopen then begin if Value then begin StrPCopy(PansiChar(@buffer), AnsiString(Copy(Serial,1,5))); hHandle:=usb_relay_device_open_with_serial_number(@buffer,length(serial)); end else begin usb_relay_device_close(hHandle); hHandle:=0; status:=0; end; Fopen := hHandle<>0; end; refresh; end; end; procedure TUsbRelay.Setstate(index: integer; const Value: boolean); begin if hHandle<>0 then begin if Value then usb_relay_device_open_one_relay_channel(hHandle,index) else usb_relay_device_close_one_relay_channel(hHandle,index); refresh; end; end; initialization UsbRelays:=TStringList.Create; finalization if UsbRelayOpened then begin ClearRelayDevices; usb_relay_exit; end; UsbRelays.Free; end.
unit UI.Ani; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, System.Rtti, System.SyncObjs, FMX.Ani, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Platform, IOUtils; type /// <summary> /// 动画类型 /// </summary> TFrameAniType = (None, DefaultAni {默认}, FadeInOut {淡入淡出}, MoveInOut {移进移出}, BottomMoveInOut {底部弹进弹出}, LeftSlideMenu {左边栏菜单}, RightSlideMenu {右边栏菜单} ); TNotifyEventA = reference to procedure (Sender: TObject); TDelayExecute = class(TAnimation) protected procedure ProcessAnimation; override; procedure FirstFrame; override; public procedure Start; override; procedure Stop; override; end; TFrameAnimator = class private type TFrameAnimatorEvent = record OnFinish: TNotifyEvent; OnFinishA: TNotifyEventA; end; TAnimationDestroyer = class private FOnFinishs: TDictionary<Integer, TFrameAnimatorEvent>; procedure DoAniFinished(Sender: TObject); procedure DoAniFinishedEx(Sender: TObject; FreeSender: Boolean); public constructor Create(); destructor Destroy; override; procedure Add(Sender: TObject; AOnFinish: TNotifyEvent); overload; procedure Add(Sender: TObject; AOnFinish: TNotifyEventA); overload; end; private class var FDestroyer: TAnimationDestroyer; private class procedure CreateDestroyer; class procedure Uninitialize; public /// <summary> /// 延时执行任务 /// </summary> class procedure DelayExecute(const Owner: TFmxObject; AOnFinish: TNotifyEventA; Delay: Single = 1.0); class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; end; implementation { TFrameAnimator } class procedure TFrameAnimator.AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TColorAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TColorAnimation.Create(Target); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TColorAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TColorAnimation.Create(Target); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TFloatAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TFloatAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TIntAnimation; begin CreateDestroyer; TAnimator.StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TIntAnimation; begin CreateDestroyer; TAnimator.StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.CreateDestroyer; begin if FDestroyer = nil then FDestroyer := TAnimationDestroyer.Create; end; class procedure TFrameAnimator.DelayExecute(const Owner: TFmxObject; AOnFinish: TNotifyEventA; Delay: Single); var Animation: TDelayExecute; begin CreateDestroyer; Animation := TDelayExecute.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Owner; Animation.AnimationType := TAnimationType.In; Animation.Interpolation := TInterpolationType.Linear; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Delay; Animation.Delay := 0; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.Uninitialize; begin FreeAndNil(FDestroyer); end; { TFrameAnimator.TAnimationDestroyer } procedure TFrameAnimator.TAnimationDestroyer.Add(Sender: TObject; AOnFinish: TNotifyEvent); var Item: TFrameAnimatorEvent; begin if not Assigned(AOnFinish) then Exit; Item.OnFinish := AOnFinish; Item.OnFinishA := nil; FOnFinishs.Add(Sender.GetHashCode, Item); end; procedure TFrameAnimator.TAnimationDestroyer.Add(Sender: TObject; AOnFinish: TNotifyEventA); var Item: TFrameAnimatorEvent; begin if not Assigned(AOnFinish) then Exit; Item.OnFinishA := AOnFinish; Item.OnFinish := nil; FOnFinishs.AddOrSetValue(Sender.GetHashCode, Item); end; constructor TFrameAnimator.TAnimationDestroyer.Create; begin FOnFinishs := TDictionary<Integer, TFrameAnimatorEvent>.Create(13); end; destructor TFrameAnimator.TAnimationDestroyer.Destroy; begin FreeAndNil(FOnFinishs); inherited; end; procedure TFrameAnimator.TAnimationDestroyer.DoAniFinished(Sender: TObject); begin DoAniFinishedEx(Sender, True); end; procedure TFrameAnimator.TAnimationDestroyer.DoAniFinishedEx(Sender: TObject; FreeSender: Boolean); var Item: TFrameAnimatorEvent; Key: Integer; begin Key := Sender.GetHashCode; if FOnFinishs.ContainsKey(Key) then begin Item := FOnFinishs[Key]; FOnFinishs.Remove(Key); // UI操作,默认是单线程,不作同步处理 end else begin Item.OnFinish := nil; Item.OnFinishA := nil; end; if FreeSender then TAnimation(Sender).DisposeOf; try if Assigned(Item.OnFinish) then Item.OnFinish(Sender); if Assigned(Item.OnFinishA) then Item.OnFinishA(Sender); except end; end; { TDelayExecute } procedure TDelayExecute.FirstFrame; begin end; procedure TDelayExecute.ProcessAnimation; begin end; procedure TDelayExecute.Start; begin inherited Start; end; procedure TDelayExecute.Stop; begin inherited Stop; end; initialization finalization TFrameAnimator.Uninitialize; end.
unit Contatos.view.principal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TabControl, FMX.Edit, FMX.SearchBox, FMX.ListBox, FMX.MultiView, MeusContatos.Model.Configuracao.Interfaces, Data.Bind.Components, Data.Bind.ObjectScope, system.math, {$ifdef ANDROID} AndroidApi.JNI.OS, AndroidApi.JNI.GraphicsContentViewText, AndroidApi.Helpers, AndroidApi.JNIBridge, {$endif} FMX.Ani; type tOperacao = (tpNovo, tpAlterar, tpExibe, tplista); type TFormPrincipal = class(TForm) Estilos: TStyleBook; LayoutBarraPrincipal: TLayout; BarraPrincipal: TRectangle; SobraBarraPrincipal: TShadowEffect; BotaoMenu: TButton; imgMenu: TPath; TabPrincipal: TTabControl; TabLista: TTabItem; TabExibe: TTabItem; TabNovo: TTabItem; BotaoNovo: TButton; imgAddContato: TPath; BotaoEditar: TButton; imgEdit: TPath; BotaoApagar: TButton; imgdelete: TPath; BotaoOK: TButton; imgOK: TPath; BotaoVoltar: TButton; imgBack: TPath; LabelTitulo: TLabel; ListaDeContatos: TListBox; CaixaPesquisa: TSearchBox; LayoutPrincipal: TLayout; MenuPrincipal: TMultiView; LayoutSobre: TLayout; LabelSobre: TLabel; LayoutCofiguracoes: TLayout; RecConfigTitle: TRectangle; RecConfig1: TRectangle; LayoutConfig2: TLayout; ShadowEffect1: TShadowEffect; LabelConfigTitulo: TLabel; LabelServidor: TLabel; EdServidor: TEdit; LabelPorta: TLabel; EdPorta: TEdit; LayoutBarraConfig: TLayout; BotaoConfigOK: TButton; imgOK2: TPath; BotaoRefresh: TButton; imgRefresh: TPath; ImgSobre: TPath; LayExibeId: TLayout; LabelNome: TLabel; LNome: TLabel; Layout1: TLayout; LabelTelFixo: TLabel; LTelefone: TLabel; Layout2: TLayout; LabelTelCel: TLabel; LCelular: TLabel; Layout3: TLayout; LabelEmail: TLabel; Lemail: TLabel; Layout4: TLayout; Label1: TLabel; Layout5: TLayout; Label3: TLabel; Layout6: TLayout; Label5: TLabel; Layout7: TLayout; Label7: TLabel; EdNome: TEdit; EdTelefone: TEdit; EdCelular: TEdit; EdEmail: TEdit; LaySplash: TLayout; Rectangle1: TRectangle; Image1: TImage; LayImg: TLayout; LayImg2: TLayout; Label2: TLabel; AniSplash: TFloatAnimation; Label4: TLabel; AniSplashPre: TFloatAnimation; VertScrollBox1: TVertScrollBox; LaySec: TLayout; LaySemConexao: TLayout; LaySemConxao1: TLayout; ImgSemConexao: TPath; LaySemConexao2: TLayout; LabelSemConexao: TLabel; procedure FormCreate(Sender: TObject); procedure BotaoNovoClick(Sender: TObject); procedure BotaoEditarClick(Sender: TObject); procedure BotaoApagarClick(Sender: TObject); procedure BotaoVoltarClick(Sender: TObject); procedure BotaoConfigOKClick(Sender: TObject); procedure BotaoRefreshClick(Sender: TObject); procedure ListaDeContatosItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure BotaoOKClick(Sender: TObject); procedure AniSplashFinish(Sender: TObject); procedure TabPrincipalChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure AniSplashPreFinish(Sender: TObject); procedure EdNomeEnter(Sender: TObject); procedure FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure EdTelefoneKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure EdTelefoneChangeTracking(Sender: TObject); procedure EdCelularChangeTracking(Sender: TObject); procedure EdCelularKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure EdTelefoneEnter(Sender: TObject); procedure EdCelularEnter(Sender: TObject); procedure EdEmailEnter(Sender: TObject); procedure FormFocusChanged(Sender: TObject); procedure FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); private { Private declarations } FOperacao : toperacao; FId : integer; FKBBounds: TRectF; FNeedOffset: Boolean; procedure CalcContentBoundsProc(Sender: TObject; var ContentBounds: TRectF); procedure RestorePosition; procedure UpdateKBBounds; Procedure Navegacao(Operacao : tOperacao); public { Public declarations } fconfiguracao : iModelConfiguracao; Foco : Tcontrol; end; var FormPrincipal: TFormPrincipal; implementation uses MeusContatos.Model.Configuracao, MeusContatos.Controller.Contatos, MeusContatos.Controller.Contatos.Interfaces, system.maskUtils, Contatos.view.mensagem, MeusContatos.Model.ServidorAberto; {$R *.fmx} {$R *.iPhone4in.fmx IOS} {$R *.Windows.fmx MSWINDOWS} {$R *.NmXhdpiPh.fmx ANDROID} Procedure Vibrar (Tempo: integer); {$IFDEF Android} var Vibrar : JVibrator; {$ENDIF} begin {$IFDEF ANDROID} Vibrar := TJVibrator.Wrap((SharedActivityContext.getSystemService(TJcontext.JavaClass.VIBRATOR_SERVICE) as ILocalObject).GetObjectID); Vibrar.vibrate(tempo); {$ENDIF} end; Procedure MaskText (Const Aedit: TEdit; Const Mask: string); Var LAux: String; i: integer; begin if (Aedit.MaxLength <> mask.Length) then Aedit.MaxLength := mask.Length; LAux := Aedit.Text.Replace('.', ''); LAux := LAux.Replace('-', ''); LAux := LAux.Replace('/', ''); LAux := LAux.Replace('(', ''); LAux := LAux.Replace(')', ''); LAux := FormatMaskText(Mask+';0;_', LAux).Trim; for i := LAux.Length-1 downto 0 do if not CharInSet(LAux.Chars[i], ['0'..'9']) then Delete(LAux, i+1, 1) else Break; TEdit(Aedit).Text := LAux; TEdit(Aedit).GoToTextEnd; // if not CharInSet(LAux.Chars[i], ['0'..'9']) then end; Procedure Ajustar_scroll(); Begin With FormPrincipal do begin LaySec.Height := 90; VertScrollBox1.Margins.Bottom := 250; VertScrollBox1.ViewportPosition := PointF(VertScrollBox1.ViewportPosition.X, TControl(foco).Position.Y - 90); end; End; procedure TFormPrincipal.AniSplashFinish(Sender: TObject); begin LaySplash.Visible := False; end; procedure TFormPrincipal.AniSplashPreFinish(Sender: TObject); begin AniSplash.Start; end; procedure TFormPrincipal.BotaoApagarClick(Sender: TObject); var FControllerContatos : iControllerContatos; begin Vibrar(1500); FormMsg.Confirmar('Exclusão de contato', 'Você clicou em "Excluir Contato". Tem certeza de que deseja apagar este contato?', Procedure begin FControllerContatos := tControllerContatos.New; if FControllerContatos.Apagar(FId) = true then begin FormMsg.SimpleMsg('Contato apagado', 'Contato foi excluído com sucesso.'); Navegacao(tplista); FControllerContatos.Listar; end; end); end; procedure TFormPrincipal.BotaoConfigOKClick(Sender: TObject); var Resultado : boolean; begin Resultado := fconfiguracao .Servidor(EdServidor.Text) .Porta (EdPorta.Text) .GravaConfig; if Resultado = true then begin MenuPrincipal.HideMaster; FormMsg.SimpleMsg('Configurações salvas', 'As alterações efetuadas nas configurações foram salvas e aplicadas com sucesso.'); end; end; procedure TFormPrincipal.BotaoEditarClick(Sender: TObject); begin EdNome.Text := LNome.Text; EdTelefone.Text := LTelefone.Text; EdCelular.Text := LCelular.Text; EdEmail.Text := Lemail.Text; Navegacao(tpAlterar); end; procedure TFormPrincipal.BotaoNovoClick(Sender: TObject); begin Navegacao(tpNovo); end; procedure TFormPrincipal.BotaoOKClick(Sender: TObject); var FControllerContatos : iControllerContatos; begin case FOperacao of tpNovo: begin FControllerContatos := tControllerContatos.New.Novo; FormMsg.SimpleMsg('Contato cadastrado', 'Contato foi adicionado com sucesso.'); Navegacao(tplista); FControllerContatos := tControllerContatos.New.Listar; end; tpAlterar: begin FControllerContatos := tControllerContatos.New.Alterar(FId); FormMsg.SimpleMsg('Contato alterado', 'Contato foi alterado com sucesso.'); Navegacao(tplista); FControllerContatos := tControllerContatos.New.Listar; end; tpExibe: ; tplista: ; end; end; procedure TFormPrincipal.BotaoRefreshClick(Sender: TObject); var iConfig: imodelconfiguracao; FControllerContatos : iControllerContatos; begin iConfig := tConfiguracao.New; if TFuncoes.ServidorAtivo(strtoint(iConfig.Porta), iConfig.Servidor) = true then begin CaixaPesquisa.Visible := true; LaySemConexao.Visible := false; ListaDeContatos.Clear; BotaoNovo.Enabled := True; FControllerContatos := tControllerContatos.New.Listar; end else begin CaixaPesquisa.Visible := false; LaySemConexao.Visible := True; ListaDeContatos.Clear; BotaoNovo.Enabled := false; end; end; procedure TFormPrincipal.BotaoVoltarClick(Sender: TObject); begin case FOperacao of tpNovo : Navegacao(tplista); tpAlterar : Navegacao(tpExibe); tpExibe : Navegacao(tplista); end; end; procedure TFormPrincipal.CalcContentBoundsProc(Sender: TObject; var ContentBounds: TRectF); begin if FNeedOffset and (FKBBounds.Top > 0) then begin ContentBounds.Bottom := Max(ContentBounds.Bottom, 2 * ClientHeight - FKBBounds.Top); end; end; procedure TFormPrincipal.EdCelularChangeTracking(Sender: TObject); begin {$IFNDEF MSWINDOWS} MaskText(sender as Tedit, '(99)99999-9999'); {$ENDIF} end; procedure TFormPrincipal.EdCelularEnter(Sender: TObject); begin {$IFDEF ANDROID} // Foco := TControl(TEdit(sender).Parent); // Ajustar_scroll; {$ENDIF} end; procedure TFormPrincipal.EdCelularKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin {$IFDEF MSWINDOWS} MaskText(sender as Tedit, '(99)99999-9999'); {$ENDIF} end; procedure TFormPrincipal.EdEmailEnter(Sender: TObject); begin {$IFDEF ANDROID} // Foco := TControl(TEdit(sender).Parent); // Ajustar_scroll; {$ENDIF} end; procedure TFormPrincipal.EdNomeEnter(Sender: TObject); begin {$IFDEF ANDROID} // Foco := TControl(TEdit(sender).Parent); // Ajustar_scroll; {$ENDIF} end; procedure TFormPrincipal.EdTelefoneChangeTracking(Sender: TObject); begin {$IFNDEF MSWINDOWS} MaskText(sender as Tedit, '(99)9999-9999'); {$ENDIF} end; procedure TFormPrincipal.EdTelefoneEnter(Sender: TObject); begin {$IFDEF ANDROID} // Foco := TControl(TEdit(sender).Parent); // Ajustar_scroll; {$ENDIF} end; procedure TFormPrincipal.EdTelefoneKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin {$IFDEF MSWINDOWS} MaskText(sender as Tedit, '(99)9999-9999'); {$ENDIF} end; procedure TFormPrincipal.FormCreate(Sender: TObject); var FControllerContatos : iControllerContatos; begin BotaoVoltar.Visible := false; BotaoEditar.Visible := false; BotaoApagar.Visible := false; BotaoOK.Visible := false; BotaoMenu.Visible := True; BotaoNovo.Visible := true; TabPrincipal.TabPosition := TTabPosition.None; TabPrincipal.TabIndex := 0; fconfiguracao := tconfiguracao.New; EdServidor.Text := fconfiguracao.Servidor; EdPorta.Text := fconfiguracao.Porta; ReportMemoryLeaksOnShutdown := true; fConfiguracao := tConfiguracao.New; if TFuncoes.ServidorAtivo(strtoint(fConfiguracao.Porta), fConfiguracao.Servidor) = true then begin CaixaPesquisa.Visible := true; LaySemConexao.Visible := false; ListaDeContatos.Clear; BotaoNovo.Enabled := true; FControllerContatos := tControllerContatos.New.Listar; end else begin CaixaPesquisa.Visible := false; LaySemConexao.Visible := True; ListaDeContatos.Clear; BotaoNovo.Enabled := false; end; VertScrollBox1.OnCalcContentBounds := CalcContentBoundsProc; end; procedure TFormPrincipal.FormFocusChanged(Sender: TObject); begin UpdateKBBounds; end; procedure TFormPrincipal.FormShow(Sender: TObject); begin AniSplashPre.Start; FormMsg.MainLayout := LayoutPrincipal; end; procedure TFormPrincipal.FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin // VertScrollBox1.Margins.Bottom := 0; // LaySec.Height := 50; FKBBounds.Create(0, 0, 0, 0); FNeedOffset := False; RestorePosition; end; procedure TFormPrincipal.FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin FKBBounds := TRectF.Create(Bounds); FKBBounds.TopLeft := ScreenToClient(FKBBounds.TopLeft); FKBBounds.BottomRight := ScreenToClient(FKBBounds.BottomRight); UpdateKBBounds; end; Procedure TFormPrincipal.ListaDeContatosItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); var FControllerContatos : iControllerContatos; begin FId := Item.Tag; //ShowMessage(inttostr(fid)); FControllerContatos := tControllerContatos.New.Contato(Fid); Navegacao(tpExibe); ListaDeContatos.ItemIndex := -1; end; procedure TFormPrincipal.Navegacao(Operacao: tOperacao); begin FOperacao := operacao; case FOperacao of tpNovo: begin BotaoVoltar.Visible := true; BotaoEditar.Visible := false; BotaoApagar.Visible := false; BotaoOK.Visible := true; BotaoMenu.Visible := false; BotaoNovo.Visible := false; BotaoRefresh.Visible := false; EdNome.Text := ''; EdTelefone.Text := ''; EdCelular.Text := ''; EdEmail.Text := ''; tabPrincipal.GotoVisibleTab(2); EdNome.SetFocus; end; tpAlterar: begin BotaoVoltar.Visible := true; BotaoEditar.Visible := false; BotaoApagar.Visible := false; BotaoOK.Visible := true; BotaoMenu.Visible := false; BotaoNovo.Visible := false; BotaoRefresh.Visible := false; tabPrincipal.GotoVisibleTab(2); end; tpExibe: begin BotaoVoltar.Visible := true; BotaoEditar.Visible := true; BotaoApagar.Visible := true; BotaoOK.Visible := false; BotaoMenu.Visible := false; BotaoNovo.Visible := false; BotaoRefresh.Visible := false; tabPrincipal.GotoVisibleTab(1); end; tplista: begin BotaoVoltar.Visible := false; BotaoEditar.Visible := false; BotaoApagar.Visible := false; BotaoOK.Visible := false; BotaoMenu.Visible := True; BotaoNovo.Visible := true; BotaoRefresh.Visible := True; tabPrincipal.GotoVisibleTab(0); end; end; end; procedure TFormPrincipal.RestorePosition; begin VertScrollBox1.ViewportPosition := PointF(VertScrollBox1.ViewportPosition.X, 0); // MainLayout1.Align := TAlignLayout.Client; VertScrollBox1.RealignContent; end; procedure TFormPrincipal.TabPrincipalChange(Sender: TObject); begin if TabPrincipal.ActiveTab <> TabLista then MenuPrincipal.DrawerOptions.TouchAreaSize := -1 else MenuPrincipal.DrawerOptions.TouchAreaSize := 20; end; procedure TFormPrincipal.UpdateKBBounds; var LFocused : TControl; LFocusRect: TRectF; begin FNeedOffset := False; if Assigned(Focused) then begin LFocused := TControl(Focused.GetObject); LFocusRect := LFocused.AbsoluteRect; LFocusRect.Offset(VertScrollBox1.ViewportPosition); if (LFocusRect.IntersectsWith(TRectF.Create(FKBBounds))) and (LFocusRect.Bottom > FKBBounds.Top) then begin FNeedOffset := True; // MainLayout1.Align := TAlignLayout.Horizontal; VertScrollBox1.RealignContent; Application.ProcessMessages; VertScrollBox1.ViewportPosition := PointF(VertScrollBox1.ViewportPosition.X, LFocusRect.Bottom - FKBBounds.Top); end; end; if not FNeedOffset then RestorePosition; end; end.
unit my_Unit; interface function IsInt(ch : char) : Boolean; // функция IsInt проверяет, является ли символ // допустимым во время ввода целого числа function IsFloat(ch : char; st : string) : Boolean; // функция IsFloat проверяет, является ли символ // допустимым во время ввода дробного числа // ch - очередной символ // st - уже введенный символ procedure eFilterT_Metal(text: String); implementation uses DataModuleForm, DB, DBGrids, SysUtils; function IsInt(ch : char) : Boolean; begin if (ch >='0') and (ch <='9') // цифры then or (ch = #13) // Key <Enter> or (ch = #8) // Key <BackSpace> then IsInt :=True // символ допустимый else IsInt :=False; // недопустимый символ end; function IsFloat(ch : char; st : string) : Boolean; begin if (ch >='0') and (ch <='9') // цифры then or (ch = #13) // Key <Enter> or (ch = #8) // Key <BackSpace> then Begin IsFloat := True; // символ верный Exit; end; case ch of '-': if Length(st) = 0 then IsFloat:= True; ',': if (Pos(',',st) = 0) and (st[Length(st)] >= '0') and (st[Length(st)] <= '9') then IsFloat:=True; else IsFloat:=False; //en //это разделитель инициализации // он в данном случае не содержит инструкции end; end; procedure eFilterT_Metal(text: String); var filterText: string; begin if (Length(Trim(text)) > 0) and (text <> filterText) then begin DataModule.ds_Metal.Filtered := False; DataModule.ds_Metal.FilterOptions := [foCaseInsensitive]; DataModule.ds_Metal.Filter := 'TM_NAME LIKE ' + QuotedStr('%' + Trim(text) + '%'); DataModule.ds_Metal.Filtered := True; end; if Length(Trim(text)) = 0 then begin // eFilter.Clear; DataModule.ds_Metal.Filtered := False; DataModule.ds_SERV_S.ReopenLocate('SVS_NAME'); end; end; end.
unit Dsa; interface type HCkDsa = Pointer; HCkByteData = Pointer; HCkString = Pointer; function CkDsa_Create: HCkDsa; stdcall; procedure CkDsa_Dispose(handle: HCkDsa); stdcall; procedure CkDsa_getDebugLogFilePath(objHandle: HCkDsa; outPropVal: HCkString); stdcall; procedure CkDsa_putDebugLogFilePath(objHandle: HCkDsa; newPropVal: PWideChar); stdcall; function CkDsa__debugLogFilePath(objHandle: HCkDsa): PWideChar; stdcall; function CkDsa_getGroupSize(objHandle: HCkDsa): Integer; stdcall; procedure CkDsa_putGroupSize(objHandle: HCkDsa; newPropVal: Integer); stdcall; procedure CkDsa_getHash(objHandle: HCkDsa; outPropVal: HCkByteData); stdcall; procedure CkDsa_putHash(objHandle: HCkDsa; newPropVal: HCkByteData); stdcall; procedure CkDsa_getHexG(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__hexG(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getHexP(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__hexP(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getHexQ(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__hexQ(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getHexX(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__hexX(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getHexY(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__hexY(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getLastErrorHtml(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__lastErrorHtml(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getLastErrorText(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__lastErrorText(objHandle: HCkDsa): PWideChar; stdcall; procedure CkDsa_getLastErrorXml(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__lastErrorXml(objHandle: HCkDsa): PWideChar; stdcall; function CkDsa_getLastMethodSuccess(objHandle: HCkDsa): wordbool; stdcall; procedure CkDsa_putLastMethodSuccess(objHandle: HCkDsa; newPropVal: wordbool); stdcall; procedure CkDsa_getSignature(objHandle: HCkDsa; outPropVal: HCkByteData); stdcall; procedure CkDsa_putSignature(objHandle: HCkDsa; newPropVal: HCkByteData); stdcall; function CkDsa_getVerboseLogging(objHandle: HCkDsa): wordbool; stdcall; procedure CkDsa_putVerboseLogging(objHandle: HCkDsa; newPropVal: wordbool); stdcall; procedure CkDsa_getVersion(objHandle: HCkDsa; outPropVal: HCkString); stdcall; function CkDsa__version(objHandle: HCkDsa): PWideChar; stdcall; function CkDsa_FromDer(objHandle: HCkDsa; derData: HCkByteData): wordbool; stdcall; function CkDsa_FromDerFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_FromEncryptedPem(objHandle: HCkDsa; password: PWideChar; pemData: PWideChar): wordbool; stdcall; function CkDsa_FromPem(objHandle: HCkDsa; pemData: PWideChar): wordbool; stdcall; function CkDsa_FromPublicDer(objHandle: HCkDsa; derData: HCkByteData): wordbool; stdcall; function CkDsa_FromPublicDerFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_FromPublicPem(objHandle: HCkDsa; pemData: PWideChar): wordbool; stdcall; function CkDsa_FromXml(objHandle: HCkDsa; xmlKey: PWideChar): wordbool; stdcall; function CkDsa_GenKey(objHandle: HCkDsa; numBits: Integer): wordbool; stdcall; function CkDsa_GenKeyFromParamsDer(objHandle: HCkDsa; derBytes: HCkByteData): wordbool; stdcall; function CkDsa_GenKeyFromParamsDerFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_GenKeyFromParamsPem(objHandle: HCkDsa; pem: PWideChar): wordbool; stdcall; function CkDsa_GenKeyFromParamsPemFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_GetEncodedHash(objHandle: HCkDsa; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkDsa__getEncodedHash(objHandle: HCkDsa; encoding: PWideChar): PWideChar; stdcall; function CkDsa_GetEncodedSignature(objHandle: HCkDsa; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkDsa__getEncodedSignature(objHandle: HCkDsa; encoding: PWideChar): PWideChar; stdcall; function CkDsa_LoadText(objHandle: HCkDsa; path: PWideChar; outStr: HCkString): wordbool; stdcall; function CkDsa__loadText(objHandle: HCkDsa; path: PWideChar): PWideChar; stdcall; function CkDsa_SaveLastError(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_SaveText(objHandle: HCkDsa; strToSave: PWideChar; path: PWideChar): wordbool; stdcall; function CkDsa_SetEncodedHash(objHandle: HCkDsa; encoding: PWideChar; encodedHash: PWideChar): wordbool; stdcall; function CkDsa_SetEncodedSignature(objHandle: HCkDsa; encoding: PWideChar; encodedSig: PWideChar): wordbool; stdcall; function CkDsa_SetEncodedSignatureRS(objHandle: HCkDsa; encoding: PWideChar; encodedR: PWideChar; encodedS: PWideChar): wordbool; stdcall; function CkDsa_SetKeyExplicit(objHandle: HCkDsa; groupSizeInBytes: Integer; pHex: PWideChar; qHex: PWideChar; gHex: PWideChar; xHex: PWideChar): wordbool; stdcall; function CkDsa_SetPubKeyExplicit(objHandle: HCkDsa; groupSizeInBytes: Integer; pHex: PWideChar; qHex: PWideChar; gHex: PWideChar; yHex: PWideChar): wordbool; stdcall; function CkDsa_SignHash(objHandle: HCkDsa): wordbool; stdcall; function CkDsa_ToDer(objHandle: HCkDsa; outData: HCkByteData): wordbool; stdcall; function CkDsa_ToDerFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_ToEncryptedPem(objHandle: HCkDsa; password: PWideChar; outStr: HCkString): wordbool; stdcall; function CkDsa__toEncryptedPem(objHandle: HCkDsa; password: PWideChar): PWideChar; stdcall; function CkDsa_ToPem(objHandle: HCkDsa; outStr: HCkString): wordbool; stdcall; function CkDsa__toPem(objHandle: HCkDsa): PWideChar; stdcall; function CkDsa_ToPublicDer(objHandle: HCkDsa; outData: HCkByteData): wordbool; stdcall; function CkDsa_ToPublicDerFile(objHandle: HCkDsa; path: PWideChar): wordbool; stdcall; function CkDsa_ToPublicPem(objHandle: HCkDsa; outStr: HCkString): wordbool; stdcall; function CkDsa__toPublicPem(objHandle: HCkDsa): PWideChar; stdcall; function CkDsa_ToXml(objHandle: HCkDsa; bPublicOnly: wordbool; outStr: HCkString): wordbool; stdcall; function CkDsa__toXml(objHandle: HCkDsa; bPublicOnly: wordbool): PWideChar; stdcall; function CkDsa_UnlockComponent(objHandle: HCkDsa; unlockCode: PWideChar): wordbool; stdcall; function CkDsa_Verify(objHandle: HCkDsa): wordbool; stdcall; function CkDsa_VerifyKey(objHandle: HCkDsa): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkDsa_Create; external DLLName; procedure CkDsa_Dispose; external DLLName; procedure CkDsa_getDebugLogFilePath; external DLLName; procedure CkDsa_putDebugLogFilePath; external DLLName; function CkDsa__debugLogFilePath; external DLLName; function CkDsa_getGroupSize; external DLLName; procedure CkDsa_putGroupSize; external DLLName; procedure CkDsa_getHash; external DLLName; procedure CkDsa_putHash; external DLLName; procedure CkDsa_getHexG; external DLLName; function CkDsa__hexG; external DLLName; procedure CkDsa_getHexP; external DLLName; function CkDsa__hexP; external DLLName; procedure CkDsa_getHexQ; external DLLName; function CkDsa__hexQ; external DLLName; procedure CkDsa_getHexX; external DLLName; function CkDsa__hexX; external DLLName; procedure CkDsa_getHexY; external DLLName; function CkDsa__hexY; external DLLName; procedure CkDsa_getLastErrorHtml; external DLLName; function CkDsa__lastErrorHtml; external DLLName; procedure CkDsa_getLastErrorText; external DLLName; function CkDsa__lastErrorText; external DLLName; procedure CkDsa_getLastErrorXml; external DLLName; function CkDsa__lastErrorXml; external DLLName; function CkDsa_getLastMethodSuccess; external DLLName; procedure CkDsa_putLastMethodSuccess; external DLLName; procedure CkDsa_getSignature; external DLLName; procedure CkDsa_putSignature; external DLLName; function CkDsa_getVerboseLogging; external DLLName; procedure CkDsa_putVerboseLogging; external DLLName; procedure CkDsa_getVersion; external DLLName; function CkDsa__version; external DLLName; function CkDsa_FromDer; external DLLName; function CkDsa_FromDerFile; external DLLName; function CkDsa_FromEncryptedPem; external DLLName; function CkDsa_FromPem; external DLLName; function CkDsa_FromPublicDer; external DLLName; function CkDsa_FromPublicDerFile; external DLLName; function CkDsa_FromPublicPem; external DLLName; function CkDsa_FromXml; external DLLName; function CkDsa_GenKey; external DLLName; function CkDsa_GenKeyFromParamsDer; external DLLName; function CkDsa_GenKeyFromParamsDerFile; external DLLName; function CkDsa_GenKeyFromParamsPem; external DLLName; function CkDsa_GenKeyFromParamsPemFile; external DLLName; function CkDsa_GetEncodedHash; external DLLName; function CkDsa__getEncodedHash; external DLLName; function CkDsa_GetEncodedSignature; external DLLName; function CkDsa__getEncodedSignature; external DLLName; function CkDsa_LoadText; external DLLName; function CkDsa__loadText; external DLLName; function CkDsa_SaveLastError; external DLLName; function CkDsa_SaveText; external DLLName; function CkDsa_SetEncodedHash; external DLLName; function CkDsa_SetEncodedSignature; external DLLName; function CkDsa_SetEncodedSignatureRS; external DLLName; function CkDsa_SetKeyExplicit; external DLLName; function CkDsa_SetPubKeyExplicit; external DLLName; function CkDsa_SignHash; external DLLName; function CkDsa_ToDer; external DLLName; function CkDsa_ToDerFile; external DLLName; function CkDsa_ToEncryptedPem; external DLLName; function CkDsa__toEncryptedPem; external DLLName; function CkDsa_ToPem; external DLLName; function CkDsa__toPem; external DLLName; function CkDsa_ToPublicDer; external DLLName; function CkDsa_ToPublicDerFile; external DLLName; function CkDsa_ToPublicPem; external DLLName; function CkDsa__toPublicPem; external DLLName; function CkDsa_ToXml; external DLLName; function CkDsa__toXml; external DLLName; function CkDsa_UnlockComponent; external DLLName; function CkDsa_Verify; external DLLName; function CkDsa_VerifyKey; external DLLName; end.
unit TFlatSpinButtonUnit; interface {$I DFS.inc} uses Windows, Classes, StdCtrls, ExtCtrls, Controls, Messages, SysUtils, Forms, Graphics, Menus, Buttons, TFlatSpeedButtonUnit; const InitRepeatPause = 400; // pause before repeat timer (ms) RepeatPause = 100; // pause before hint window displays (ms) type TNumGlyphs = Buttons.TNumGlyphs; TTimerSpeedButton = class; { TFlatSpinButton } TSpinButton = class(TWinControl) private FUpButton: TTimerSpeedButton; FDownButton: TTimerSpeedButton; FFocusedButton: TTimerSpeedButton; FFocusControl: TWinControl; FOnUpClick: TNotifyEvent; FOnDownClick: TNotifyEvent; function CreateButton: TTimerSpeedButton; function GetUpGlyph: TBitmap; function GetDownGlyph: TBitmap; procedure SetUpGlyph(Value: TBitmap); procedure SetDownGlyph(Value: TBitmap); function GetUpNumGlyphs: TNumGlyphs; function GetDownNumGlyphs: TNumGlyphs; procedure SetUpNumGlyphs(Value: TNumGlyphs); procedure SetDownNumGlyphs(Value: TNumGlyphs); procedure BtnClick(Sender: TObject); procedure BtnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetFocusBtn(Btn: TTimerSpeedButton); procedure AdjustSize(var W, H: Integer); {$IFDEF DFS_COMPILER_4_UP} reintroduce; {$ENDIF} procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; protected procedure Loaded; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property DownGlyph: TBitmap read GetDownGlyph write SetDownGlyph; property DownNumGlyphs: TNumGlyphs read GetDownNumGlyphs write SetDownNumGlyphs default 1; property FocusControl: TWinControl read FFocusControl write FFocusControl; property UpGlyph: TBitmap read GetUpGlyph write SetUpGlyph; property UpNumGlyphs: TNumGlyphs read GetUpNumGlyphs write SetUpNumGlyphs default 1; property Enabled; property Visible; property OnDownClick: TNotifyEvent read FOnDownClick write FOnDownClick; property OnUpClick: TNotifyEvent read FOnUpClick write FOnUpClick; end; { TTimerSpeedButton } TTimeBtnState = set of (tbFocusRect, tbAllowTimer); TTimerSpeedButton = class(TFlatSpeedButton) private FRepeatTimer: TTimer; FTimeBtnState: TTimeBtnState; procedure TimerExpired(Sender: TObject); protected procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public destructor Destroy; override; property TimeBtnState: TTimeBtnState read FTimeBtnState write FTimeBtnState; end; implementation {$R FlatArrow} { TSpinButton } constructor TSpinButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] + [csFramed, csOpaque]; FUpButton := CreateButton; FDownButton := CreateButton; UpGlyph := nil; DownGlyph := nil; Width := 21; Height := 10; FFocusedButton := FUpButton; end; function TSpinButton.CreateButton: TTimerSpeedButton; begin Result := TTimerSpeedButton.Create(Self); Result.OnClick := BtnClick; Result.OnMouseDown := BtnMouseDown; Result.Visible := True; Result.Enabled := True; Result.TimeBtnState := [tbAllowTimer]; Result.Parent := Self; end; procedure TSpinButton.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FFocusControl) then FFocusControl := nil; end; procedure TSpinButton.AdjustSize(var W, H: Integer); begin if (FUpButton = nil) or (csLoading in ComponentState) then Exit; FUpButton.SetBounds(0, 0, 11, H); FDownButton.SetBounds(10, 0, 11, H); end; procedure TSpinButton.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var W, H: Integer; begin W := AWidth; H := AHeight; AdjustSize(W, H); inherited SetBounds(ALeft, ATop, W, H); end; procedure TSpinButton.WMSize(var Message: TWMSize); var W, H: Integer; begin inherited; // check for minimum size W := Width; H := Height; AdjustSize(W, H); if (W <> Width) or (H <> Height) then inherited SetBounds(Left, Top, W, H); Message.Result := 0; end; procedure TSpinButton.WMSetFocus(var Message: TWMSetFocus); begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState + [tbFocusRect]; FFocusedButton.Invalidate; end; procedure TSpinButton.WMKillFocus(var Message: TWMKillFocus); begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState - [tbFocusRect]; FFocusedButton.Invalidate; end; procedure TSpinButton.KeyDown(var Key: Word; Shift: TShiftState); begin case Key of VK_UP: begin SetFocusBtn(FUpButton); FUpButton.Click; end; VK_DOWN: begin SetFocusBtn(FDownButton); FDownButton.Click; end; VK_SPACE: FFocusedButton.Click; end; end; procedure TSpinButton.BtnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin SetFocusBtn(TTimerSpeedButton(Sender)); if (FFocusControl <> nil) and FFocusControl.TabStop and FFocusControl.CanFocus and (GetFocus <> FFocusControl.Handle) then FFocusControl.SetFocus else if TabStop and (GetFocus <> Handle) and CanFocus then SetFocus; end; end; procedure TSpinButton.BtnClick(Sender: TObject); begin if Sender = FUpButton then if Assigned(FOnUpClick) then FOnUpClick(Self); if Sender = FDownButton then if Assigned(FOnDownClick) then FOnDownClick(Self); end; procedure TSpinButton.SetFocusBtn(Btn: TTimerSpeedButton); begin if TabStop and CanFocus and (Btn <> FFocusedButton) then begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState - [tbFocusRect]; FFocusedButton := Btn; if (GetFocus = Handle) then begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState + [tbFocusRect]; Invalidate; end; end; end; procedure TSpinButton.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS; end; procedure TSpinButton.Loaded; var W, H: Integer; begin inherited Loaded; W := Width; H := Height; AdjustSize(W, H); if (W <> Width) or (H <> Height) then inherited SetBounds(Left, Top, Width, Height); end; function TSpinButton.GetUpGlyph: TBitmap; begin Result := FUpButton.Glyph; end; procedure TSpinButton.SetUpGlyph(Value: TBitmap); begin if Value <> nil then FUpButton.Glyph := Value else begin FUpButton.Glyph.Handle := LoadBitmap(HInstance, 'FlatUp'); FUpButton.NumGlyphs := 1; FUpButton.Margin := 2; FUpButton.Invalidate; FUpButton.Layout := blGlyphTop; end; end; function TSpinButton.GetUpNumGlyphs: TNumGlyphs; begin Result := FUpButton.NumGlyphs; end; procedure TSpinButton.SetUpNumGlyphs(Value: TNumGlyphs); begin FUpButton.NumGlyphs := Value; end; function TSpinButton.GetDownGlyph: TBitmap; begin Result := FDownButton.Glyph; end; procedure TSpinButton.SetDownGlyph(Value: TBitmap); begin if Value <> nil then FDownButton.Glyph := Value else begin FDownButton.Glyph.Handle := LoadBitmap(HInstance, 'FlatDown'); FDownButton.NumGlyphs := 1; FDownButton.Margin := 2; FDownButton.Invalidate; FDownButton.Layout := blGlyphBottom; end; end; function TSpinButton.GetDownNumGlyphs: TNumGlyphs; begin Result := FDownButton.NumGlyphs; end; procedure TSpinButton.SetDownNumGlyphs(Value: TNumGlyphs); begin FDownButton.NumGlyphs := Value; end; { TTimerSpeedButton } destructor TTimerSpeedButton.Destroy; begin if FRepeatTimer <> nil then FRepeatTimer.Free; inherited Destroy; end; procedure TTimerSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if tbAllowTimer in FTimeBtnState then begin if FRepeatTimer = nil then FRepeatTimer := TTimer.Create(Self); FRepeatTimer.OnTimer := TimerExpired; FRepeatTimer.Interval := InitRepeatPause; FRepeatTimer.Enabled := True; end; end; procedure TTimerSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if FRepeatTimer <> nil then FRepeatTimer.Enabled := False; end; procedure TTimerSpeedButton.TimerExpired(Sender: TObject); begin FRepeatTimer.Interval := RepeatPause; if (FState = bsDown) and MouseCapture then begin try Click; except FRepeatTimer.Enabled := False; raise ; end; end; end; end. 
unit txFilterSql; interface uses SysUtils, txDefs, txFilter, DataLank; type TtxSqlQueryFragments=class(TObject) private FItemType:TtxItemType; AliasCount,FParentID:integer; AddedWhere:boolean; DbCon:TDataConnection; function BuildSQL:string; function SqlStr(s:string):string; function Criterium(const El:TtxFilterElement; SubQryField, SubQryFrom: string; ParentsOnly, Reverse: boolean):string; public Limit:integer; Fields,Tables,Where,GroupBy,Having,OrderBy:string; EnvVars:array[TtxFilterEnvVar] of integer; constructor Create(ItemType: TtxItemType); destructor Destroy; override; procedure AddFilter(f:TtxFilter); procedure AddWhere(s:string); procedure AddWhereSafe(s:string); procedure AddOrderBy(s:string); procedure AddFrom(s:string); property SQL:string read BuildSQL; property ParentID:integer read FParentID; end; EtxSqlQueryError=class(Exception); TIdList=class(TObject) private idCount,idSize:integer; ids:array of integer; function GetList:string; function GetItem(Idx:integer):integer; procedure SetItem(Idx,Value:integer); public constructor Create; destructor Destroy; override; procedure Add(id:integer); procedure AddList(list:TIdList); procedure AddClip(id:integer; var Clip:integer); procedure Clear; function Contains(id:integer):boolean; property List:string read GetList; property Count:integer read idCount; property Item[Idx:integer]:integer read GetItem write SetItem; default; end; implementation uses txSession, Classes, Variants; { TtxSqlQueryFragments } constructor TtxSqlQueryFragments.Create(ItemType: TtxItemType); var t:string; fe:TtxFilterEnvVar; begin inherited Create; AliasCount:=0; Limit:=-1; FParentID:=0; FItemType:=ItemType; DbCon:=Session.DbCon; case FItemType of itObj: begin Fields:='Obj.id, Obj.pid, Obj.name, Obj."desc", Obj.weight, Obj.c_uid, Obj.c_ts, Obj.m_uid, Obj.m_ts, ObjType.icon, ObjType.name AS typename'; Tables:='Obj LEFT JOIN ObjType ON ObjType.id=Obj.objtype_id'#13#10; Where:=''; GroupBy:=''; Having:=''; OrderBy:='Obj.weight, Obj.name, Obj.c_ts'; end; itReport: begin Fields:='Rpt.id, Rpt.obj_id, Rpt."desc", Rpt.uid, Rpt.ts, Rpt.toktype_id, Rpt.reftype_id, Rpt.obj2_id,'+ ' Obj.name, Obj.pid, ObjType.icon, ObjType.name AS typename,'+ ' UsrObj.id AS usrid, UsrObj.name AS usrname, UsrObjType.icon AS usricon, UsrObjType.name AS usrtypename,'+ ' RelTokType.icon AS tokicon, RelTokType.name AS tokname, RelTokType.system AS toksystem,'+ ' RelRefType.icon AS reficon, RelRefType.name AS refname,'+ ' RelObj.name AS relname, RelObjType.icon AS relicon, RelObjType.name AS reltypename'; Tables:='Rpt'#13#10+ 'INNER JOIN Obj ON Obj.id=Rpt.obj_id'#13#10+ 'INNER JOIN ObjType ON ObjType.id=Obj.objtype_id'#13#10+ 'INNER JOIN Obj AS UsrObj ON UsrObj.id=Rpt.uid'#13#10+ 'INNER JOIN ObjType AS UsrObjType ON UsrObjType.id=UsrObj.objtype_id'#13#10+ 'LEFT OUTER JOIN Obj AS RelObj ON RelObj.id=Rpt.obj2_id'#13#10+ 'LEFT OUTER JOIN ObjType AS RelObjType ON RelObjType.id=RelObj.objtype_id'#13#10+ 'LEFT OUTER JOIN TokType AS RelTokType ON RelTokType.id=Rpt.toktype_id'#13#10+ 'LEFT OUTER JOIN RefType AS RelRefType ON RelRefType.id=Rpt.reftype_id'#13#10; Where:=''; GroupBy:=''; Having:=''; OrderBy:='Rpt.ts DESC'; end; else begin t:=txItemTypeTable[ItemType]; Fields:='*'; Tables:=t+#13#10; Where:=''; GroupBy:=''; Having:=''; OrderBy:=t+'.weight, '+t+'.name, '+t+'.c_ts'; end; end; if Use_ObjTokRefCache and (FItemType in [itObj,itReport]) then begin Fields:=Fields+', ObjTokRefCache.tokHTML, ObjTokRefCache.refHTML'; Tables:=Tables+'LEFT OUTER JOIN ObjTokRefCache ON ObjTokRefCache.id=Obj.id'#13#10; end; for fe:=TtxFilterEnvVar(0) to fe_Unknown do EnvVars[feMe]:=0; EnvVars[feMe]:=Session.UserID; end; destructor TtxSqlQueryFragments.Destroy; begin //clean-up DbCon:=nil; inherited; end; function CritDate(fx:TtxFilterElement):string; begin case fx.IDType of dtNumber: //Result:='{d '''+FormatDate('yyyy-mm-dd',Date-StrToInt(fx.ID))+'''}'; Result:=FloatToStr(Date-StrToInt(fx.ID));//SQLite allows storing Delphi date-as-float //TODO else raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(fx.Idx1)); end; end; function CritTime(fx:TtxFilterElement):string; var dy,dm,dd,th,tm,ts,tz:word; d:TDateTime; i,l:integer; procedure Next(var vv:word;max:integer); var j:integer; begin vv:=0; j:=i+max; while (i<=l) and (i<j) and (AnsiChar(fx.ID[i]) in ['0'..'9']) do begin vv:=vv*10+(byte(fx.ID[i]) and $0F); inc(i); end; while (i<=l) and not(AnsiChar(fx.ID[i]) in ['0'..'9']) do inc(i); end; begin case fx.IDType of dtNumber,dtSystem: begin //defaults dy:=1900; dm:=1; dd:=1; th:=0; tm:=0; ts:=0; tz:=0; l:=Length(fx.ID); i:=1; while (i<=l) and not(AnsiChar(fx.ID[i]) in ['0'..'9']) do inc(i); if i<=l then begin Next(dy,4);//year if i<=l then begin Next(dm,2);//month if i<=l then begin Next(dd,2);//day Next(th,2);//hours Next(tm,2);//minutes Next(ts,2);//seconds Next(tz,3);//milliseconds end; end; end; d:=EncodeDate(dy,dm,dd)+EncodeTime(th,tm,ts,tz); //Result:='{ts '''+FormatDate('yyyy-mm-dd hh:nn:ss.zzz',d)+'''}'; Result:=FloatToStr(d);//SQLite allows storing Delphi date-as-float end; //TODO else raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(fx.Idx1)); end; end; procedure TtxSqlQueryFragments.AddFilter(f: TtxFilter); var i,j,k:integer; s,t:string; qr:TQueryResult; fx:TtxFilter; fq:TtxSqlQueryFragments; procedure LocalPrefetch; begin with TIdList.Create do try qr:=TQueryResult.Create(Session.DbCon,s,[]); try while qr.Read do Add(qr.GetInt(0)); finally qr.Free; end; s:=List; finally Free; end; end; const RefBSel:array[boolean] of string=('1','2'); begin //TODO: when FItemType<>itObj for i:=0 to f.Count-1 do with f[i] do begin //check global para count? for j:=1 to ParaOpen do Where:=Where+'('; //no para's when not AddedWhere? AddedWhere:=false; case Action of faChild: //dummy check: if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then AddWhere('1=1')//match all else AddWhere('Obj.pid'+Criterium(f[i],'Obj.id','',true,false)); faObj: AddWhere('Obj.id'+Criterium(f[i],'Obj.id','',false,false)); faObjType: if (f[i].IDType=dtNumber) and (f[i].ID='0') then if f[i].Descending then AddWhere('1=1')//match all else AddWhere('0=1')//match none else AddWhere('ObjType.id'+Criterium(f[i],'DISTINCT ObjType.id','',false,false)); faTokType: //dummy check: if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then AddWhere('EXISTS (SELECT id FROM Tok WHERE obj_id=Obj.id)') else begin inc(AliasCount); t:='ttSQ'+IntToStr(AliasCount); s:='SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i], 'DISTINCT '+t+'.toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false); if Parameters<>'' then begin fx:=TtxFilter.Create; try fx.FilterExpression:=Parameters; for j:=0 to fx.Count-1 do case fx[j].Action of faModified: s:=s+' AND Tok.m_ts<'+CritDate(fx[j]); faFrom: s:=s+' AND Tok.m_ts>='+CritTime(fx[j]); faTill: s:=s+' AND Tok.m_ts<='+CritTime(fx[j]) else raise EtxSqlQueryError.Create('Unexpected tt parameter at position '+IntToStr(fx[j].Idx1)); end; //TODO: fx[j].Operator finally fx.Free; end; end; if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faRefType: //dummy check: if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then AddWhere('EXISTS (SELECT id FROM Ref WHERE obj1_id=Obj.id)') else begin inc(AliasCount); t:='rtSQ'+IntToStr(AliasCount); s:='SELECT DISTINCT Ref.obj1_id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i], 'DISTINCT '+t+'.reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj1_id=Obj.id',false,false); if Parameters<>'' then begin fx:=TtxFilter.Create; try fx.FilterExpression:=Parameters; for j:=0 to fx.Count-1 do case fx[j].Action of faModified: s:=s+' AND Ref.m_ts<'+CritDate(fx[j]); faFrom: s:=s+' AND Ref.m_ts>='+CritTime(fx[j]); faTill: s:=s+' AND Ref.m_ts<='+CritTime(fx[j]); else raise EtxSqlQueryError.Create('Unexpected rt parameter at position '+IntToStr(fx[j].Idx1)); end; //TODO: fx[j].Operator finally fx.Free; end; end; if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faRef,faBackRef: begin s:=''; if Parameters<>'' then begin fx:=TtxFilter.Create; try fx.FilterExpression:=Parameters; for j:=0 to fx.Count-1 do case fx[j].Action of faRefType: begin inc(AliasCount); t:='rxSQ'+IntToStr(AliasCount); s:=s+' AND Ref.reftype_id'+Criterium(fx[j], 'DISTINCT '+t+'.id','RIGHT JOIN Ref AS '+t+' ON '+t+'.ref_obj'+RefBSel[Action=faBackRef]+'_id=Obj.id',false,false); end; faModified: s:=s+' AND Ref.m_ts<'+CritDate(fx[j]); faFrom: s:=s+' AND Ref.m_ts>='+CritTime(fx[j]); faTill: s:=s+' AND Ref.m_ts<='+CritTime(fx[j]); else raise EtxSqlQueryError.Create('Unexpected rx parameter at position '+IntToStr(Idx1)); end; //TODO: fx[j].Operator finally fx.Free; end; end; AddWhere('Obj.id IN (SELECT Ref.obj'+RefBSel[Action=faRef]+'_id FROM Ref WHERE Ref.obj'+RefBSel[Action=faBackRef]+'_id'+Criterium(f[i], 'Obj.id','',false,false)+s+')'); end; faParent: case IDType of dtNumber:FParentID:=StrToInt(ID); //TODO //dtSystem:; //dtSubQuery:; //dtEnvironment:; else raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(Idx1)); end; faModified: AddWhere('Obj.m_ts<'+CritDate(f[i])); faFrom: AddWhere('Obj.m_ts>='+CritTime(f[i])); faTill: AddWhere('Obj.m_ts<='+CritTime(f[i])); faFilter: begin if Descending then raise EtxSqlQueryError.Create('Descending into filter not supported'); fx:=TtxFilter.Create; try //TODO: detect loops? qr:=TQueryResult.Create(Session.DbCon,'SELECT Flt.expression FROM Flt WHERE Flt.id'+Criterium(f[i],'','',false,false)+' LIMIT 1',[]); try if qr.EOF then raise EtxSqlQueryError.Create('Filter not found at position '+IntToStr(Idx1)); fx.FilterExpression:=qr.GetStr(0); finally qr.Free; end; if fx.ParseError<>'' then raise EtxSqlQueryError.Create( 'Invalid filter at position '+IntToStr(Idx1)+': '+fx.ParseError); if Prefetch then begin fq:=TtxSqlQueryFragments.Create(FItemType); try fq.AddFilter(fx); fq.Fields:='Obj.id'; fq.OrderBy:=''; s:=fq.SQL; LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); finally fq.Free; end; end else AddFilter(fx); finally fx.Free; end; end; faName: begin AddWhere('Obj.name='+SqlStr(ID)); OrderBy:='Obj.m_ts, Obj.weight, Obj.name'; end; faDesc: begin AddWhere('Obj."desc" LIKE '+SqlStr(ID)); OrderBy:='Obj.m_ts, Obj.weight, Obj.name'; end; faSearchName: begin AddWhere('Obj.name LIKE '+SqlStr(ID));//parentheses? OrderBy:='Obj.m_ts, Obj.weight, Obj.name'; end; faSearch: begin //parameters? k:=1; s:=''; while k<=Length(ID) do begin j:=k; while (k<=Length(ID)) and not(AnsiChar(ID[k]) in [#0..#32]) do inc(k); if k-j<>0 then begin if s<>'' then s:=s+' AND '; s:=s+'(Obj.name LIKE '+SqlStr('%'+Copy(ID,j,k-j)+'%')+' OR Obj."desc" LIKE '+SqlStr('%'+Copy(ID,j,k-j)+'%')+')'; end; inc(k); end; if s='' then s:='0=1';//match none? match all? AddWhere(s);//parentheses? OrderBy:='Obj.m_ts, Obj.weight, Obj.name'; end; faSearchReports: begin AddFrom('INNER JOIN Rpt ON Rpt.obj_id=Obj.id'); //parameters? k:=1; s:=''; while k<=Length(ID) do begin j:=k; while (k<=Length(ID)) and not(AnsiChar(ID[k]) in [#0..#32]) do inc(k); if k-j<>1 then begin if s<>'' then s:=s+' AND '; s:=s+'Rpt."desc" LIKE '+SqlStr('%'+Copy(ID,j,k-j)+'%'); end; inc(k); end; if s='' then s:='0=1';//match none? match all? AddWhere('('+s+')'); //OrderBy:=//assert already Rpt.ts desc end; faTerm: begin AddFrom('INNER JOIN Trm ON Trm.obj_id=Obj.id'); //parameters? k:=1; s:=''; while k<=Length(ID) do begin j:=k; while (k<=Length(ID)) and not(AnsiChar(ID[k]) in [#0..#32]) do inc(k); if k-j<>1 then begin if s<>'' then s:=s+' OR ';//AND? //s:=s+'Trm.term LIKE '+SqlStr('%'+Copy(ID,j,k-j)+'%'); s:=s+'Trm.term='+SqlStr(Copy(ID,j,k-j)); end; inc(k); end; if s='' then s:='0=1';//match none? match all? AddWhere('('+s+')'); end; faAlwaysTrue: if (ParaClose=0) and (i<>f.Count-1) then case Operator of foAnd:;//skip foAndNot:Where:=Where+'NOT '; else AddWhere('1=1'); end else AddWhere('1=1'); faAlwaysFalse: if (ParaClose=0) and (i<>f.Count-1) then case Operator of foOr:;//skip foOrNot:Where:=Where+'NOT '; else AddWhere('0=1'); end else AddWhere('0=1'); faSQL: begin AddWhereSafe(ID); AddWhereSafe(Parameters); end; faExtra:;//TODO: filterparameters faPath: AddWhere('Obj.id'+Criterium(f[i],'Obj.pid','',false,true)); //descending? faPathObjType: AddWhere('Obj.objtype_id'+Criterium(f[i],'DISTINCT ObjType.pid','',false,true)); faPathTokType: begin inc(AliasCount); t:='ptSQ'+IntToStr(AliasCount); s:='SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i], 'DISTINCT '+t+'.toktype_pid','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,true); if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faPathRefType: begin inc(AliasCount); t:='prSQ'+IntToStr(AliasCount); s:='SELECT DISTINCT Ref.obj1_id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i], 'DISTINCT '+t+'.reftype_pid','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj1_id=Obj.id',false,true); if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faCreated: AddWhere('Obj.c_uid'+Criterium(f[i],'Obj.id','',false,false)); faTokCreated: begin s:='SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.c_uid'+Criterium(f[i],'Obj.id','',false,false); if Parameters<>'' then begin fx:=TtxFilter.Create; try fx.FilterExpression:=Parameters; for j:=0 to fx.Count-1 do case fx[j].Action of faModified: s:=s+' AND Tok.m_ts<'+CritDate(fx[j]); faFrom: s:=s+' AND Tok.m_ts>='+CritTime(fx[j]); faTill: s:=s+' AND Tok.m_ts<='+CritTime(fx[j]); else raise EtxSqlQueryError.Create('Unexpected ttr parameter at position '+IntToStr(fx[j].Idx1)); end; //TODO: fx[j].Operator finally fx.Free; end; end; if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faRefCreated,faBackRefCreated: begin s:=''; if Parameters<>'' then begin fx:=TtxFilter.Create; try fx.FilterExpression:=Parameters; for j:=0 to fx.Count-1 do case fx[j].Action of faRefType: begin inc(AliasCount); t:='urSQ'+IntToStr(AliasCount); s:=s+' AND Ref.reftype_id'+Criterium(fx[j],'DISTINCT '+t+'.id','RIGHT JOIN Ref AS '+t+' ON '+t+ '.ref_obj'+RefBSel[fx[j].Action=faBackRefCreated]+'_id=Obj.id',false,false); end; faModified: s:=s+' AND Ref.m_ts<'+CritDate(fx[j]); faFrom: s:=s+' AND Ref.m_ts>='+CritTime(fx[j]); faTill: s:=s+' AND Ref.m_ts<='+CritTime(fx[j]); else raise EtxSqlQueryError.Create('Unexpected rtr parameter at position '+IntToStr(fx[j].Idx1)); end; //TODO: fx[j].Operator finally fx.Free; end; end; s:='SELECT DISTINCT Ref.obj'+RefBSel[Action=faBackRefCreated]+'_id FROM Ref WHERE Ref.c_uid'+ Criterium(f[i],'Obj.id','',false,false)+s; if Prefetch then LocalPrefetch; AddWhere('Obj.id IN ('+s+')'); end; faRecentObj: begin AddWhere('Obj.id'+Criterium(f[i],'Obj.id','',false,false)); AddOrderBy('Obj.m_ts DESC'); end; faRecentTok: begin AddFrom('INNER JOIN Tok ON Obj.id=Tok.obj_id'); AddOrderBy('Tok.m_ts DESC'); inc(AliasCount); t:='ttSQ'+IntToStr(AliasCount); if Prefetch then begin s:='SELECT DISTINCT Tok.id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i], 'DISTINCT '+t+'toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false); LocalPrefetch; AddWhere('Tok.ID IN ('+s+')'); end else AddWhere('Tok.toktype_id'+Criterium(f[i], 'DISTINCT '+t+'toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false)); end; faRecentRef,faRecentBackRef: begin AddFrom('INNER JOIN Ref ON Ref.obj'+RefBSel[Action=faRecentBackRef]+'_id=Obj.id'); AddOrderBy('Ref.m_ts DESC'); inc(AliasCount); t:='rtSQ'+IntToStr(AliasCount); if Prefetch then begin s:='SELECT DISTINCT Ref.id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i], 'DISTINCT '+t+'reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj'+ RefBSel[Action=faRecentBackRef]+'_id=Obj.id',false,false); LocalPrefetch; AddWhere('Ref.ID IN ('+s+')'); end else AddWhere('Ref.reftype_id'+Criterium(f[i], 'DISTINCT '+t+'.reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj'+ RefBSel[Action=faRecentBackRef]+'_id=Obj.id',false,false)); end; faUser: begin AddFrom('INNER JOIN Usr ON Usr.uid=Obj.id'); AddWhere('Obj.id'+Criterium(f[i],'Usr.uid','',false,false)); end; faRealm: AddWhere('Obj.rlm_id'+Criterium(f[i],'Rlm.id','',false,false)); faUnread: begin if Session.IsAdmin('logins') and not((f[i].IDType=dtNumber) and ((f[i].ID='0') or (f[i].ID=''))) then s:=Criterium(f[i],'Obj.id','',false,false) else s:='='+IntToStr(Session.UserID); AddWhere('EXISTS (SELECT Obx.id FROM Obx'+ ' LEFT OUTER JOIN Urx ON Urx.uid'+s+ ' AND Obx.id BETWEEN Urx.id1 AND Urx.id2'+ ' WHERE Obx.obj_id=Obj.id AND Urx.id IS NULL)'); end; else raise EtxSqlQueryError.Create('Unsupported filter action at position '+IntToStr(Idx1)); end; //check global para count? for j:=1 to ParaClose do Where:=Where+')'; if (i<>f.Count-1) and AddedWhere then Where:=Where+' '+txFilterOperatorSQL[Operator]+' '; end; end; function TtxSqlQueryFragments.BuildSQL: string; var s:TStringStream; procedure Add(t,u:string); begin if u<>'' then begin s.WriteString(t); s.WriteString(u); end; end; begin s:=TStringStream.Create(''); try s.WriteString('SELECT '); s.WriteString(Fields); s.WriteString(#13#10'FROM '); s.WriteString(Tables);//assert ends in #13#10 Add('WHERE ',Where); Add(#13#10'GROUP BY ',GroupBy); Add(#13#10'HAVING ',Having); Add(#13#10'ORDER BY ',OrderBy); if Limit<>-1 then s.WriteString(#13#10'LIMIT '+IntToStr(Limit)); //MySql: s.WriteString(' LIMIT '+IntToStr(Limit)+',0'); Result:=s.DataString; finally s.Free; end; end; procedure TtxSqlQueryFragments.AddWhere(s: string); begin Where:=Where+s; AddedWhere:=true; end; procedure TtxSqlQueryFragments.AddWhereSafe(s: string); var i,j:integer; begin j:=0; for i:=1 to Length(s) do case s[i] of '''':inc(j); ';':if (j and 1)=0 then raise EtxSqlQueryError.Create('Semicolon in external SQL not allowed'); //TODO: detect and refuse comment? '--' and '/*' end; if (j and 1)=1 then raise EtxSqlQueryError.Create('Unterminated string in external SQL detected'); Where:=Where+s; AddedWhere:=true; end; procedure TtxSqlQueryFragments.AddFrom(s: string); begin if s<>'' then if Pos(s,Tables)=0 then Tables:=Tables+s+#13#10; end; function TtxSqlQueryFragments.SqlStr(s: string): string; begin Result:=''''+StringReplace(s,'''','''''',[rfReplaceAll])+''''; end; function TtxSqlQueryFragments.Criterium(const El:TtxFilterElement; SubQryField, SubQryFrom: string; ParentsOnly, Reverse: boolean): string; const idGrow=$1000; var ItemType:TtxItemType; idSQL,t:string; ids,ids1:TIdList; i,j,l:integer; fe:TtxFilterEnvVar; f:TtxFilter; fq:TtxSqlQueryFragments; qr:TQueryResult; begin ItemType:=txFilterActionItemType[El.Action]; idSQL:=''; ids:=TIdList.Create; try t:=txItemTypeTable[ItemType]; case El.IDType of dtNumber: ids.Add(StrToInt(El.ID)); dtNumberList: begin i:=1; l:=Length(El.ID); while (i<=l) and not(AnsiChar(El.ID[i]) in ['0'..'9']) do inc(i); while (i<=l) do begin j:=0; while (i<=l) and (AnsiChar(El.ID[i]) in ['0'..'9']) do begin j:=j*10+(byte(El.ID[i]) and $F); inc(i); end; ids.Add(j); while (i<=l) and not(AnsiChar(El.ID[i]) in ['0'..'9']) do inc(i); end; end; dtSystem: //TODO: realms? case ItemType of itObj: idSQL:='SELECT Obj.id FROM Obj WHERE Obj.name LIKE '+SqlStr(El.ID); itObjType,itTokType,itRefType,itRealm: idSQL:='SELECT '+t+'.id FROM '+t+' WHERE '+t+'.system='+SqlStr(El.ID); itFilter: idSQL:='SELECT Flt.id FROM Flt WHERE Flt.name='+SqlStr(El.ID); itUser: idSQL:='SELECT Usr.uid FROM Usr WHERE Usr.login='+SqlStr(El.ID); else raise EtxSqlQueryError.Create('String search on '+txItemTypeName[ItemType]+' is not allowed'); end; dtSubQuery: begin f:=TtxFilter.Create; fq:=TtxSqlQueryFragments.Create(ItemType); try f.FilterExpression:=El.ID; if f.ParseError<>'' then raise EtxSqlQueryError.Create('Error in sub-query :'+f.ParseError); fq.AddFilter(f); fq.Fields:=SubQryField; fq.AddFrom(SubQryFrom); fq.OrderBy:=''; idSQL:=fq.BuildSQL; //TODO: realms? finally f.Free; fq.Free; end; end; dtEnvironment: begin fe:=TtxFilter.GetFilterEnvVar(El.ID); case fe of feUs:idSQL:='SELECT Obj.id FROM Obj WHERE Obj.pid='+IntToStr(EnvVars[feMe]); fe_Unknown:raise EtxSqlQueryError.Create('Unknown Filter Environment Variable: '+El.ID); else ids.Add(EnvVars[fe]); end; end; else raise EtxSqlQueryError.Create('Unsupported IDType at position '+IntToStr(El.Idx1)); end; if (El.Descending or El.Prefetch) and (idSQL<>'') then begin qr:=TQueryResult.Create(Session.DbCon,idSQL,[]); try while qr.Read do ids.Add(qr.GetInt(0)); finally qr.Free; end; idSQL:=''; end; if El.Descending then begin if Reverse then if Use_ObjPath and (ItemType=itObj) then if idSQL='' then if ids.Count=1 then idSQL:='SELECT pid FROM ObjPath WHERE oid='+IntToStr(ids[0]) else idSQL:='SELECT pid FROM ObjPath WHERE oid IN ('+ids.List+')' else idSQL:='SELECT pid FROM ObjPath WHERE oid IN ('+idSQL+')' else begin i:=0; while i<ids.Count do begin qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.pid FROM '+t+' WHERE '+t+'.id='+IntToStr(ids[i]),[]); try while qr.Read do ids.Add(qr.GetInt(0)); finally qr.Free; end; inc(i); end; end else if ParentsOnly then begin if Use_ObjPath and (ItemType=itObj) then if idSQL='' then if ids.Count=1 then idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid='+IntToStr(ids[0]) else idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid IN ('+ids.List+')' else idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid IN ('+idSQL+')' else begin ids1:=TIdList.Create; try ids1.AddList(ids); ids.Clear; i:=0; while i<ids1.Count do begin //only add those with children qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.id FROM '+t+' WHERE '+t+'.pid='+IntToStr(ids1[i]),[]); try if not qr.EOF then ids.Add(ids1[i]); while qr.Read do ids1.AddClip(qr.GetInt(0),i); finally qr.Free; end; inc(i); end; finally ids1.Free; end; end; end else begin //full expand if Use_ObjPath and (ItemType=itObj) then if idSQL='' then if ids.Count=1 then idSQL:='SELECT oid FROM ObjPath WHERE pid='+IntToStr(ids[0]) else idSQL:='SELECT oid FROM ObjPath WHERE pid IN ('+ids.List+')' else idSQL:='SELECT oid FROM ObjPath WHERE pid IN ('+idSQL+')' else begin i:=0; while i<ids.Count do begin qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.id FROM '+t+' WHERE '+t+'.pid='+IntToStr(ids[i]),[]); try while qr.Read do ids.Add(qr.GetInt(0)); finally qr.Free; end; inc(i); end; end; end; end else if Reverse then //one level up for i:=0 to ids.Count-1 do begin qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.pid FROM '+t+' WHERE '+t+'.id='+IntToStr(ids[i]),[]); try ids[i]:=qr.GetInt(0); finally qr.Free; end; end; if idSQL='' then case ids.Count of 0:Result:='=-1'; 1:Result:='='+IntToStr(ids[0]); else Result:=' IN ('+ids.List+')'; end else Result:=' IN ('+idSQL+')'; finally ids.Free; end; end; procedure TtxSqlQueryFragments.AddOrderBy(s: string); begin if s<>'' then if OrderBy='' then OrderBy:=s else if Pos(s,OrderBy)=0 then OrderBy:=s+', '+OrderBy; end; { TIdList } constructor TIdList.Create; begin inherited Create; Clear; end; destructor TIdList.Destroy; begin SetLength(ids,0); inherited; end; const IdListGrow=$1000; procedure TIdList.Add(id: integer); begin if idCount=idSize then begin inc(idSize,IdListGrow); SetLength(ids,idSize); end; ids[idCount]:=id; inc(idCount); end; procedure TIdList.AddList(list: TIdList); var l:integer; begin l:=List.Count; while (idSize<idCount+l) do inc(idSize,IdListGrow); SetLength(ids,idSize); Move(list.ids[0],ids[idCount],l*4); inc(idCount,l); end; procedure TIdList.AddClip(id:integer; var Clip:integer); var i:integer; begin //things before Clip no longer needed i:=Clip div IdListGrow; if i<>0 then begin i:=i*IdListGrow; //shrink? keep data for re-use (idSize) Move(ids[i],ids[0],i*4); dec(Clip,i); dec(idCount,i); end; Add(id); end; procedure TIdList.Clear; begin idCount:=0; idSize:=0; //SetLength(ids,idSize);//keep allocated data for re-use end; function TIdList.GetList: string; var i:integer; s:TStringStream; begin if idCount=0 then Result:='' else begin s:=TStringStream.Create(''); try s.WriteString(IntToStr(ids[0])); for i:=1 to idCount-1 do s.WriteString(','+IntToStr(ids[i])); Result:=s.DataString; finally s.Free; end; end; end; function TIdList.GetItem(Idx: integer): integer; begin Result:=ids[Idx]; end; procedure TIdList.SetItem(Idx, Value: integer); begin ids[Idx]:=Value; end; function TIdList.Contains(id:integer):boolean; var i:integer; begin i:=0; while (i<idCount) and (ids[i]<>id) do inc(i); Result:=i<idCount; end; end.
// The bulk of this code came from: // http://stackoverflow.com/questions/1297773/check-java-is-present-before-installing // function RequireJava(MinimalVersion: string): Boolean; // Both DecodeVersion and CompareVersion functions where taken from the inno setup wiki procedure DecodeVersion(verstr: String; var verint: array of Integer); var i,p: Integer; s: string; begin // initialize array verint := [0,0,0,0]; i := 0; while ((Length(verstr) > 0) and (i < 4)) do begin p := pos ('.', verstr); if p > 0 then begin if p = 1 then s:= '0' else s:= Copy (verstr, 1, p - 1); verint[i] := StrToInt(s); i := i + 1; verstr := Copy (verstr, p+1, Length(verstr)); end else begin verint[i] := StrToInt (verstr); verstr := ''; end; end; end; function CompareVersion(ver1, ver2: String): Integer; var verint1, verint2: array of Integer; i: integer; begin SetArrayLength (verint1, 4); DecodeVersion (ver1, verint1); SetArrayLength (verint2, 4); DecodeVersion (ver2, verint2); Result := 0; i := 0; while ((Result = 0) and ( i < 4 )) do begin if verint1[i] > verint2[i] then Result := 1 else if verint1[i] < verint2[i] then Result := -1 else Result := 0; i := i + 1; end; end; function RequireJava(MinimalVersion: string): Boolean; var ErrorCode: Integer; JavaVersion: String; begin RegQueryStringValue(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', JavaVersion); if Length(JavaVersion) > 0 then begin if CompareVersion(JavaVersion, MinimalVersion) >= 0 then begin Result := true; Exit; end; end; if MsgBox('This tool requires Java Runtime Environment (JRE) ' + MinimalVersion + ' or newer to run. Please download and install JRE and run this setup again.' + #13#10#13#10 + 'Do you want to open the download page now?', mbConfirmation, MB_YESNO) = idYes then begin ShellExec('open', 'http://www.oracle.com/technetwork/java/javase/downloads/', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode); end; Result := false; end;
unit NovusVersionUtils; interface uses Windows, sysutils, Forms, NovusUtilities; type { Translation record } TTranslation = record { Language identifier } Language, { Character-set identifier } CharSet: Word; end; PTranslations = ^TTranslations; TTranslations = array[0..65535] of TTranslation; TNovusVersionUtils = class(TNovusUtilities) class function GetFixedFileInfo(FileInfo: Pointer): PVSFixedFileInfo; class function GetFullVersionNumber: string; class function GetReleaseNumber: String; class function GetMagMinVersionNumber: String; class function CreateFileInfo(aFileName: String): Pointer; class procedure FreeFileInfo(FileInfo: Pointer); class function GetProductName: String; class function GetLegalCopyright: String; class function GetTranslationCount(FileInfo: Pointer): UINT; class function GetTranslation(FileInfo: Pointer; i: UINT): TTranslation; class function GetFileInfoString(FileInfo: Pointer; Translation: TTranslation; StringName: string): string; class function GetBuildNumber: String; end; implementation { Return pointer to fixed file version info } class function TNovusVersionUtils.GetFixedFileInfo(FileInfo: Pointer): PVSFixedFileInfo; var Len: UINT; begin if not VerQueryValue(FileInfo, '\', Pointer(Result), Len) then raise Exception.Create('Fixed file info not available'); end; class function TNovusVersionUtils.GetBuildNumber: String; var FileInfo: Pointer; begin FileInfo := CreateFileInfo(Application.ExeName); Result := Format('%d', [LoWord(GetFixedFileInfo(FileInfo).dwFileVersionLS)]); FreeFileInfo(FileInfo); end; class function TNovusVersionUtils.GetFullVersionNumber; var FileInfo: Pointer; begin FileInfo := CreateFileInfo(Application.ExeName); Result := Format('%d.%d.%d.%d', [ HiWord(GetFixedFileInfo(FileInfo).dwFileVersionMS), LoWord(GetFixedFileInfo(FileInfo).dwFileVersionMS), HiWord(GetFixedFileInfo(FileInfo).dwFileVersionLS), LoWord(GetFixedFileInfo(FileInfo).dwFileVersionLS)]); FreeFileInfo(FileInfo); end; class function TNovusVersionUtils.GetReleaseNumber; var FileInfo: Pointer; begin FileInfo := CreateFileInfo(Application.ExeName); Result := Format('%d', [ HiWord(GetFixedFileInfo(FileInfo).dwFileVersionLS)]); FreeFileInfo(FileInfo); end; class function TNovusVersionUtils.GetMagMinVersionNumber; var FileInfo: Pointer; begin FileInfo := CreateFileInfo(Application.ExeName); Result := Format('%d.%d.%d', [ HiWord(GetFixedFileInfo(FileInfo).dwFileVersionMS), LoWord(GetFixedFileInfo(FileInfo).dwFileVersionMS), HiWord(GetFixedFileInfo(FileInfo).dwFileVersionLS), LoWord(GetFixedFileInfo(FileInfo).dwFileVersionLS)]); FreeFileInfo(FileInfo); end; { Return pointer to file version info block } class function TNovusVersionUtils.CreateFileInfo(aFileName: String): Pointer; var lpVerInfo: pointer; rVerValue: PVSFixedFileInfo; dwInfoSize: cardinal; dwValueSize: cardinal; dwDummy: cardinal; lpstrPath: pchar; begin lpstrPath := pchar(aFilename); dwInfoSize := GetFileVersionInfoSize(lpstrPath, dwDummy); if dwInfoSize = 0 then begin Result := 0; Exit; end; GetMem(lpVerInfo, dwInfoSize); GetFileVersionInfo(lpstrPath, 0, dwInfoSize, lpVerInfo); VerQueryValue(lpVerInfo, '\', pointer(rVerValue), dwValueSize); Result := lpVerInfo; //FreeMem(lpVerInfo, dwInfoSize); (* { Get file version info block size } Size := GetFileVersionInfoSize(PChar(FileName), Handle); { If size is valid } if Size > 0 then begin { Allocate memory for file version info block } GetMem(Result, Size); { Get file version info block } if not GetFileVersionInfo(PChar(FileName), Handle, Size, Result) then begin { Free allocated memory if failed } FreeMem(Result); Result := nil; end; end else Result := nil; *) end; { Free file version info block memory } class procedure TNovusVersionUtils.FreeFileInfo(FileInfo: Pointer); begin { Free allocated memory } if FileInfo <> nil then FreeMem(FileInfo); end; class function TNovusVersionUtils.GetLegalCopyright; var FileInfo: Pointer; Translation: TTranslation; begin FileInfo := CreateFileInfo(Application.ExeName); result := ''; if GetTranslationCount(FileInfo) > 0 then begin Translation := GetTranslation(FileInfo, 0); Result := GetFileInfoString(FileInfo, Translation, 'LegalCopyright'); end; FreeFileInfo(FileInfo); end; class function TNovusVersionUtils.GetProductName; var FileInfo: Pointer; Translation: TTranslation; begin FileInfo := CreateFileInfo(Application.ExeName); result := ''; if GetTranslationCount(FileInfo) > 0 then begin Translation := GetTranslation(FileInfo, 0); Result := GetFileInfoString(FileInfo, Translation, 'ProductName'); end; FreeFileInfo(FileInfo); end; { Return number of available file version info translations } class function TNovusVersionUtils.GetTranslationCount(FileInfo: Pointer): UINT; var P: PTranslations; Len: UINT; begin if not VerQueryValue(FileInfo, '\VarFileInfo\Translation', Pointer(P), Len) then raise Exception.Create('File info translations not available'); Result := Len div 4; end; { Return i-th translation in the file version info translation list } class function TNovusVersionUtils.GetTranslation(FileInfo: Pointer; i: UINT): TTranslation; var P: PTranslations; Len: UINT; begin if not VerQueryValue(FileInfo, '\VarFileInfo\Translation', Pointer(P), Len) then raise Exception.Create('File info translations not available'); if i * SizeOf(TTranslation) >= Len then raise Exception.Create('Specified translation not available'); Result := P[i]; end; { Return the value of the specified file version info string using the specified translation } class function TNovusVersionUtils.GetFileInfoString(FileInfo: Pointer; Translation: TTranslation; StringName: string): string; var P: PChar; Len: UINT; begin if not VerQueryValue(FileInfo, PChar('\StringFileInfo\' + IntToHex(Translation.Language, 4) + IntToHex(Translation.CharSet, 4) + '\' + StringName), Pointer(P), Len) then raise Exception.Create('Specified file info string not available'); SetString(Result, P, Len); end; end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit fileutils; interface uses baseunix; type TFileData = record Start: Pointer; Length: size_t; procedure Destroy(); end; function ReadFile(const FileName: AnsiString): TFileData; // This is efficient function ReadTextFile(const FileName: AnsiString): UTF8String; // This is not function IsEmptyDirectory(const Path: AnsiString): Boolean; implementation uses exceptions, sysutils; function ReadFile(const FileName: AnsiString): TFileData; var FileDescriptor: CInt; StatInfo: Stat; MapResult: Pointer; begin FileDescriptor := fpOpen(FileName, O_RDONLY); if (FileDescriptor < 0) then raise EKernelError.Create(fpGetErrNo); if (fpFStat(FileDescriptor, StatInfo) <> 0) then // $DFA- for StatInfo raise EKernelError.Create(fpGetErrNo); MapResult := fpMMap(nil, StatInfo.st_size+1, PROT_READ, MAP_PRIVATE, FileDescriptor, 0); // $R- {$PUSH} {$WARNINGS OFF} {$HINTS OFF} if (PtrInt(MapResult) < 0) then raise EKernelError.Create(fpGetErrNo); {$POP} fpClose(FileDescriptor); Result.Length := StatInfo.st_size; // $R- Result.Start := Pointer(MapResult); end; procedure TFileData.Destroy(); begin if (fpMUnMap(Self.Start, Self.Length) <> 0) Then raise EKernelError.Create(fpGetErrNo); end; function ReadTextFile(const FileName: AnsiString): UTF8String; var Source: TFileData; begin Source := ReadFile(FileName); if (Source.Length > High(Length(Result))) then raise Exception.Create('text file too big'); SetLength(Result, Source.Length); Move(Source.Start^, Result[1], Source.Length); // $R- Source.Destroy(); end; function IsEmptyDirectory(const Path: AnsiString): Boolean; var FileRecord: TSearchRec; GotOneDot, GotTwoDots, GotOther: Boolean; begin if (DirectoryExists(Path)) then begin GotOneDot := False; GotTwoDots := False; GotOther := False; if (FindFirst(Path + '/*', faDirectory, FileRecord) = 0) then repeat if (FileRecord.Name = '.') then GotOneDot := True else if (FileRecord.Name = '..') then GotTwoDots := True else begin GotOther := True; break; end; until (FindNext(FileRecord) <> 0); Result := GotOneDot and GotTwoDots and not GotOther; FindClose(FileRecord); end else Result := False; end; end.
unit SlottingWell; interface uses Well, Classes, SlottingPlacement; type TSlottingWell = class(TWell) private FCorePresence: Single; function GetBoxes: TBoxes; protected procedure AssignTo(Dest: TPersistent); override; public property CorePresence: Single read FCorePresence write FCorePresence; property Boxes: TBoxes read GetBoxes; end; TSlottingWells = class(TWells) private function GetItems(Index: integer): TSlottingWell; function GetCoreWellCount: integer; public property CoreWellCount: integer read GetCoreWellCount; property Items[Index: integer]: TSlottingWell read GetItems; constructor Create; override; end; implementation uses Facade, SlottingWellPoster; { TSlottingWells } constructor TSlottingWells.Create; begin inherited; FObjectClass := TSlottingWell; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSlottingWellDataPoster]; OwnsObjects := true; end; function TSlottingWells.GetCoreWellCount: integer; var i: integer; begin Result := 0; for i := 0 to Count - 1 do if Items[i].CorePresence > 0 then Result := Result + 1; end; function TSlottingWells.GetItems(Index: integer): TSlottingWell; begin Result := inherited Items[Index] as TSlottingWell; end; { TSlottingWell } procedure TSlottingWell.AssignTo(Dest: TPersistent); begin inherited; (Dest as TSlottingWell).CorePresence := CorePresence; end; function TSlottingWell.GetBoxes: TBoxes; begin Result := Slottings.Boxes; end; end.
unit ViewModel.Standard; interface uses ViewModel ; type TViewModel = record class function Create: IViewModel; static; end; implementation uses DataModel.Standard , ViewModel.ViewModel.Standard ; class function TViewModel.Create: IViewModel; begin Result := nil; Result := ViewModel.ViewModel.Standard.TViewModel.Create( TDataModel.Create ); end; end.
unit unitArchivos; interface Uses Crt; Type tCliente = record nombre : String[60]; edad : Byte; dni : LongInt; domicilio : String[60]; ciudad : String[60]; provincia : String[60]; codigoPostal: String[60]; celular : LongInt; email : String[60]; fechaNac : String[16]; estado : String[20]; activo : Boolean; formaDeCont: String[30] end; t_provincia= record denominacion: String[60]; codigo_provincia: Integer; tel_de_contacto_por_covid19: Integer end; tEstadisticas = record id : LongInt; dni : LongInt; cod_prov : LongInt; estado : String[60]; formaCont : String[60] end; tArchivo = File of tCliente; tArchProv = File of t_provincia; tArchEst = File of tEstadisticas; VAR archivo : tArchivo; archProvincia : tArchProv; archEstadisticas: tArchEst; posicion : LongInt; registro : tCliente; regProvincia : t_provincia; regEstadisticas : tEstadisticas; bol : boolean; Procedure Cargar(var reg : tCliente; var arch : tArchivo); Procedure CargarProv(var reg : t_provincia; var arch : tArchProv); Procedure CargarEstadisticas(var arch : tArchivo; var archProv : tArchProv; var archEst : tArchEst; var regEst : tEstadisticas); Procedure GuardarEst(var arch : tArchEst; var reg : tEstadisticas; pos : LongInt); Procedure Guardar(var arch : tArchivo; var reg : tCliente; var pos : LongInt); Procedure LeerArch(var arch : tArchivo; var reg : tCliente; pos : LongInt); Procedure LeerProvincia(var arch : tArchProv; var reg : t_provincia; pos : Integer); Procedure LeerArchEst(var arch : tArchEst; var reg : tEstadisticas; pos : LongInt); Procedure Listar(var arch : tArchivo; reg : tCliente); Procedure ListarPorProv(var arch : tArchivo; reg : tCliente; nomProvincia : String); Procedure ListarProvincias(var arch : tArchProv; reg : t_provincia); Procedure ListarEstadisticas(var arch : tArchEst; var reg : tEstadisticas); Procedure Mostrar (var arch : tArchivo; reg : tCliente; pos : LongInt); Procedure MostrarProv(var arch : tArchProv; reg : t_provincia; pos : Integer); Procedure MostrarEst(var arch : tArchEst; reg : tEstadisticas; pos : LongInt); Procedure ordenBurbuja(var arch : tArchivo); Procedure Burbuja2(var arch : tArchivo); Function BusquedaBinaria(var arch : tArchivo; buscado : LongInt): LongInt; implementation Procedure Guardar(var arch : tArchivo; var reg : tCliente; var pos : LongInt); begin Seek(arch, pos); Write(arch, reg); end; Procedure LeerArch(var arch : tArchivo; var reg : tCliente; pos : LongInt); begin Seek(arch, pos); Read(arch, reg); end; Procedure LeerProvincia(var arch : tArchProv; var reg : t_provincia; pos : Integer); begin Seek(arch, pos); Read(arch, reg); end; Procedure LeerArchEst(var arch : tArchEst; var reg : tEstadisticas; pos : LongInt); begin Seek(arch, pos); Read(arch, reg); end; Procedure GuardarEst(var arch : tArchEst; var reg : tEstadisticas; pos : LongInt); begin Seek(arch, pos); Write(arch, reg); end; Procedure Cargar(var reg : tCliente; var arch : tArchivo); Var auxDni : LongInt; begin Seek(arch, filesize(arch)); With reg do begin Writeln('Ingrese el nombre del infectado'); Readln(nombre); while nombre <> '' do begin Writeln('Ingrese DNI'); Repeat Readln(dni); Burbuja2(arch); auxDni:= BusquedaBinaria(arch, dni); if auxDni <> -1 then begin Writeln('El DNI ya existe, ingrese otro'); end; Until auxDni = -1; Writeln('Ingrese la edad'); Readln(edad); Writeln('Ingrese domicilio (calle, numero y piso)'); Readln(domicilio); Writeln('Ingrese la ciudad'); Readln(ciudad); Writeln('Ingrese la provincia'); Readln(Provincia); Writeln('Ingrese el codigo postal'); Readln(codigoPostal); Writeln('Ingrese el numero de telefono'); Readln(celular); Writeln('Ingrese su e-mail'); Readln(email); Writeln('Ingrese fecha de nacimiento (dd/mm/a)'); Readln(fechaNac); Writeln('Ingrese metodo de contagio (directo, transmision comunitaria, desconocido)'); Readln(formaDeCont); activo := true; Writeln('Ingrese el estado (activo, recuperado, fallecido)'); Readln(estado); Write(arch, reg); // Write(archivo, registro) guarda las variables en el registro Writeln('Ingrese el nombre del cliente'); Readln(nombre); end; end; end; Procedure CargarProv(var reg : t_provincia; var arch : tArchProv); begin Seek(arch, filesize(arch)); With reg do begin Writeln('Ingrese denominacion de la Provincia'); Readln(denominacion); while denominacion <> '' do begin Writeln('Codigo de la provincia'); Readln(codigo_provincia); Writeln('Telefono contacto por Covid19'); Readln(tel_de_contacto_por_covid19); Write(arch, reg); // Write(archivo, registro) guarda las variables en el registro Writeln('Ingrese el nombre del cliente'); Readln(denominacion); end; end; end; Procedure CargarEstadisticas(var arch : tArchivo; var archProv : tArchProv; var archEst : tArchEst; var regEst : tEstadisticas); Var reg : tCliente; regProv : t_provincia; i, j : LongInt; begin i := 0; regEst.id := 0; while not EOF(arch) do begin j := 0; LeerArch(arch, reg, i); regEst.id := i + 1; regEst.dni := reg.dni; repeat LeerProvincia(archProv, regProv, j); j := j +1; until reg.provincia = regProv.denominacion; regEst.cod_prov := regProv.codigo_provincia; regEst.estado := reg.estado; regEst.formaCont := reg.formaDeCont; GuardarEst(archEst, regEst, i); i := i + 1; end; end; // Proceso que muestra una lista de cada registro que puede volver al registro anterior o continuar dependiendo // la tecla que se presione Procedure Listar(var arch : tArchivo; reg : tCliente); Var i : LongInt; eleccion : Char; begin i := 0; eleccion := 'a'; While not EOF(arch) and (eleccion <> #27) do begin ClrScr; LeerArch(arch, reg, i); // Leemos desde el primer registro en el archivo if reg.activo then // Condicional para que sólo muestre el registro si el campo activo es true begin Mostrar(arch, reg, i); Writeln('Activo: ', reg.activo); Writeln(); Writeln('1: Anterior 2: Siguiente ESC: Salir'); repeat // Repeat para que la eleccion sea 1: anterior 2: siguiente 3 salir eleccion := Readkey; until (eleccion = '1') or (eleccion = '2') or (eleccion = #27); if (eleccion = '2') and (not EOF(arch))then i := i +1 else if (eleccion = '1') and (i > 0) then i := i -1; end // Final del if else if not reg.activo and (eleccion = '2') then i := i + 1 else if not reg.activo and (eleccion = '1') and (i >= 1) then i := i - 1 else i := i + 1; end; end; Procedure ListarPorProv(var arch : tArchivo; reg : tCliente; nomProvincia : String); Var i : LongInt; eleccion : Char; begin i := 0; eleccion := 'a'; While not EOF(arch) and (eleccion <> #27) do begin ClrScr; LeerArch(arch, reg, i); if (reg.activo) and (nomProvincia = reg.provincia) then // Condicional para que sólo muestre el registro si el campo activo es true begin Mostrar(arch, reg, i); Writeln(); Writeln('1: Anterior 2: Siguiente ESC: Salir'); repeat // Repeat para que la eleccion sea 1: anterior 2: siguiente 3 salir eleccion := Readkey; until (eleccion = '1') or (eleccion = '2') or (eleccion = #27); if (eleccion = '2') and (not EOF(arch))then i := i +1 else if (eleccion = '1') and (i > 0) then i := i -1; end // Final del if else if not reg.activo and (eleccion = '2') then i := i + 1 else if not reg.activo and (eleccion = '1') and (i >= 1) then i := i - 1 else i := i + 1; end; end; Procedure ListarEstadisticas(var arch : tArchEst; var reg : tEstadisticas); Var i : LongInt; eleccion : char; begin i := 0; Writeln('1'); eleccion := 'a'; LeerArchEst(arch, reg, i); While not EOF(arch) and (eleccion <> #27) do begin ClrScr; MostrarEst(arch, reg, i); Writeln(); Writeln('1: Anterior 2: Siguiente ESC: Salir'); repeat // Repeat para que la eleccion sea 1: anterior 2: siguiente 3 salir eleccion := Readkey; until (eleccion = '1') or (eleccion = '2') or (eleccion = #27); if (eleccion = '2') and (not EOF(arch))then i := i +1 else if (eleccion = '1') and (i > 0) then i := i -1; end; end; Procedure MostrarEst(var arch : tArchEst; reg : tEstadisticas; pos : LongInt); begin LeerArchEst(arch, reg, pos); Writeln('ID: ', reg.id); Writeln('DNI: ', reg.dni); Writeln('Codigo de Provincia: ', reg.cod_prov); Writeln('Estado: ', reg.estado); Writeln('Forma de contagio: ', reg.formaCont); end; Procedure Mostrar (var arch : tArchivo; reg : tCliente; pos : LongInt); begin LeerArch(arch, reg, pos); Writeln('Nombre: ', reg.nombre); Writeln('DNI: ', reg.dni); Writeln('Domicilio: ', reg.domicilio); Writeln('Ciudad: ', reg.ciudad); Writeln('Provincia: ', reg.provincia); Writeln('Codigo Postal: ', reg.codigoPostal); Writeln('Celular: ', reg.celular); Writeln('E-mail: ', reg.email); Writeln('Estado: ', reg.estado); Writeln('Fecha de nacimiento: ', reg.fechaNac); Writeln('Forma de contagio: ', reg.formaDeCont); end; Procedure ListarProvincias(var arch : tArchProv; reg : t_provincia); Var i : LongInt; eleccion : Char; begin i := 0; eleccion := 'a'; While not EOF(arch) and (eleccion <> #27) do begin ClrScr; LeerProvincia(arch, reg, i); MostrarProv(arch, reg, i); Writeln(); Writeln('1: Anterior 2: Siguiente ESC: Salir'); repeat eleccion := Readkey; until (eleccion = '1') or (eleccion = '2') or (eleccion = #27); if (eleccion = '2') and (not EOF(arch))then i := i +1 else if (eleccion = '1') and (i > 0) then i := i -1 end; end; Procedure MostrarProv(var arch : tArchProv; reg : t_provincia; pos : Integer); begin LeerProvincia(arch, reg, pos); Writeln('Denominacion: ', reg.denominacion); Writeln('Codigo de Provincia: ', reg.codigo_provincia); Writeln('Numero de Contacto por Covid19: ', reg.tel_de_contacto_por_covid19); end; Procedure ordenBurbuja(var arch : tArchivo); Var reg1, reg2 : tCliente; lim, i, j : LongInt; begin lim := filesize(arch)-1; For i := 1 to lim -1 do For j := 0 to lim - i do begin LeerArch(arch, reg1, j); LeerArch(arch, reg2, j+1); If reg1.nombre > reg2.nombre then begin Seek(arch, j+1); Write(arch, reg1); Seek(arch, j); Write(arch, reg2); end; end; end; Procedure Burbuja2(var arch : tArchivo); // Ordenamiento por DNI para la búsqueda Var reg1, reg2 : tCliente; lim, i, j : LongInt; begin lim := filesize(arch)-1; For i := 1 to lim -1 do For j := 0 to lim - i do begin LeerArch(arch, reg1, j); LeerArch(arch, reg2, j+1); If reg1.dni > reg2.dni then begin Seek(arch, j+1); Write(arch, reg1); Seek(arch, j); Write(arch, reg2); end; end; end; Function BusquedaBinaria(var arch : tArchivo; buscado : LongInt): LongInt; Var reg : tCliente; pri, med, ult, pos : LongInt; encontrado : boolean; begin encontrado := false; pri := 0; ult := filesize(arch)-1; pos := -1; While (pos = -1) and (pri <= ult) do begin med := (pri + ult) div 2; LeerArch(arch, reg, med); if reg.dni = buscado then begin encontrado := true; pos := med; end else if reg.dni > buscado then ult := med-1 else pri := med + 1; end; if encontrado then BusquedaBinaria := pos else BusquedaBinaria := -1; end; END.
{******************************************************************************* 作者: dmzn@163.com 2011-5-25 描述: MCGS实时数据库采集管理器 *******************************************************************************} unit UMgrMCGS; {$I Link.Inc} interface uses Windows, SysUtils, Classes, ActiveX, ComObj, Variants, IniFiles, UWaitItem, ULibFun, UMgrSync, USysConst; type TMCGSSyncType = (stData, stWarnHint, stNoRun); //同步类型:数据,提示,未运行 TMCGSItemStatus = (isNone, isAdd, isUpdate); //状态:未知,添加,更新 TMCGSItemData = record FCH,FDH: string; //场号,栋号 FSerial: Word; //栋号顺序 FStatus: TMCGSItemStatus; //状态 FLastUpdate: TDateTime; //上次更新 end; //栋对象数据 PMCGSParamItem = ^TMCGSParamItem; TMCGSParamItem = record FCH,FDH: string[32]; //场号,栋号 FSerial: Word; //栋号顺序 Fw1,Fw2,Fw3,Fw4: Double; //温度 Fs1,Fs2,Fs3,Fs4: Double; //湿度 Ffj1,Ffj2,Ffj3,Ffj4,Ffj5: Word; //风机 Ffjo,Ffjc: Word; //风机起停 Ftfjb: Word; //通风级别 Ftfbj: Word; //通风报警 Frs1,Frs2,Frs3,Frs4:Word; //热水 Frld,Frlh: Double; //日龄 Fllt,Fllk: Double; //料量 Frll: Double; //日料量 Fslt,fslk: Word; //水量 Fsww: Double; //室外温度 Fcold: Word; //凉 Fhot: Word; //热 Fweight:Double; //体重 Fmw: Double; //目标温度 Faq: Double; //氨气 Ffy1,Ffy2: Double; //负压 Fslkd: Double; //水帘开度 Fslb:Double; //水帘泵 Fccl,Fccr:Double; //侧窗 end; //每栋需采集参数体 TMCGSParamItems = array of TMCGSParamItem; //参数组 TMCGSManager = class; TMCGSReader = class(TThread) private FOwner: TMCGSManager; //父对象 FWaiter: TWaitObject; //等待对象 FDataCenter: OleVariant; //数据中心 protected procedure DoExecute; procedure Execute; override; //线程体 procedure HintMsg(const nStr: string); //错误提示 function ReadParam(const nDH: Integer; var nItem: TMCGSParamItem): Boolean; //读取参数 public constructor Create(AOwner: TMCGSManager); destructor Destroy; override; //创建释放 procedure Stop; //终止线程 end; TMCGSOnItem = procedure (const nItem: TMCGSItemData) of Object; TMCGSOnData = procedure (const nData: TMCGSParamItem) of Object; //事件 TMCGSManager = class(TObject) private FCH: string; //场号 FDH: array of TMCGSItemData; //栋号列表 FInterval: Integer; //采集频率 FReader: TMCGSReader; //采集线程 FSyncer: TDataSynchronizer; //同步对象 FOnItem: TMCGSOnItem; FOnData: TMCGSOnData; FOnDataSync: TMCGSOnData; //事件相关 protected procedure DoSync(const nData: Pointer; const nSize: Cardinal); procedure DoSyncFree(const nData: Pointer; const nSize: Cardinal); //同步事件 function GetStatus: Boolean; //获取状态 public constructor Create; destructor Destroy; override; //创建释放 procedure SetDH(const nCH,nDH: string); //设置栋号 function StartReader(var nHint: string): Boolean; procedure StopReader; //起停采集 property CH: string read FCH; property IsBusy: Boolean read GetStatus; property Interval: Integer read FInterval write FInterval; property OnItem: TMCGSOnItem read FOnItem write FOnItem; property OnData: TMCGSOnData read FOnData write FOnData; property OnDataSync: TMCGSOnData read FOnDataSync write FOnDataSync; //属性相关 end; var gMCGSManager: TMCGSManager = nil; //全局使用 implementation type TVarItem = record FVarName: string; //变量名 FIndex: Integer; //数据内容 end; TVarName = record FInnerName: string; //内部名称 FOutName: string; //外部名称 end; const cSize_HintBuffer = 200; cDHNull = '!'; //null dh cVarItem: array[0..39] of TVarItem = ((FVarName:'风机1_%d'; FIndex:0), (FVarName:'风机2_%d'; FIndex:1), (FVarName:'风机3_%d'; FIndex:2), (FVarName:'风机4_%d'; FIndex:3), (FVarName:'风机5_%d'; FIndex:4), (FVarName:'风机开始1_%d'; FIndex:5), (FVarName:'风机停止1_%d'; FIndex:6), (FVarName:'通风级别1_%d'; FIndex:7), (FVarName:'热水1_%d'; FIndex:8), (FVarName:'热水2_%d'; FIndex:9), (FVarName:'热水3_%d'; FIndex:10), (FVarName:'热水4_%d'; FIndex:11),(FVarName:'目标温度1_%d'; FIndex:12), (FVarName:'温度1_%d'; FIndex:13),(FVarName:'温度2_%d'; FIndex:14), (FVarName:'温度3_%d'; FIndex:15),(FVarName:'温度4_%d'; FIndex:16), (FVarName:'湿度1_%d'; FIndex:17),(FVarName:'湿度2_%d'; FIndex:18), (FVarName:'湿度3_%d'; FIndex:19),(FVarName:'湿度4_%d'; FIndex:20), (FVarName:'日龄d_%d'; FIndex:21),(FVarName:'日龄h_%d'; FIndex:22), (FVarName:'料量t_%d'; FIndex:23),(FVarName:'料量k_%d'; FIndex:24), (FVarName:'水量t_%d'; FIndex:25),(FVarName:'水量k_%d'; FIndex:26), (FVarName:'室外温度1_%d'; FIndex:27),(FVarName:'凉1_%d'; FIndex:28), (FVarName:'热1_%d'; FIndex:29),(FVarName:'通风报警1_%d'; FIndex:30), (FVarName:'日料量1_%d'; FIndex:31),(FVarName:'体重1_%d'; FIndex:32), (FVarName:'氨气1_%d'; FIndex:33),(FVarName:'负压1_%d'; FIndex:34), (FVarName:'负压2_%d'; FIndex:35),(FVarName:'水帘开度1_%d'; FIndex:36), (FVarName:'水帘泵1_%d'; FIndex:37),(FVarName:'侧窗l_%d'; FIndex:38), (FVarName:'侧窗r_%d'; FIndex:39)); //MCGS variant var gVarNames: array of TVarName; //变量映射 function LoadVarNames: Boolean; var nStr: string; nIni: TIniFile; nList: TStrings; i,nIdx,nCount: Integer; begin Result := False; nList := nil; SetLength(gVarNames, 0); nIni := TIniFile.Create(gPath + 'DH.ini'); try nList := TStringList.Create; nIni.ReadSection('DH', nList); if nList.Count < 1 then Exit; nIdx := 0; nCount := nList.Count - 1; for i:=0 to nCount do begin nStr := nIni.ReadString('DH', nList[i], ''); if nStr = '' then Continue; SetLength(gVarNames, nIdx+1); gVarNames[nIdx].FInnerName := nList[i]; gVarNames[nIdx].FOutName := nStr; Inc(nIdx); end; Result := Length(gVarNames) > 0; finally nList.Free; nIni.Free; end; end; function GetOutName(const nInner: string): string; var nIdx: Integer; begin Result := ''; for nIdx:=Low(gVarNames) to High(gVarNames) do if gVarNames[nIdx].FInnerName = nInner then begin Result := gVarNames[nIdx].FOutName; Exit; end; end; //------------------------------------------------------------------------------ constructor TMCGSReader.Create(AOwner: TMCGSManager); begin inherited Create(False); FreeOnTerminate := False; FOwner := AOwner; FDataCenter := Unassigned; FWaiter := TWaitObject.Create; FWaiter.Interval := FOwner.FInterval * 1000; end; destructor TMCGSReader.Destroy; begin FWaiter.Free; FDataCenter := Unassigned; inherited; end; procedure TMCGSReader.HintMsg(const nStr: string); var nBuf: PChar; begin GetMem(nBuf, cSize_HintBuffer); StrLCopy(nBuf, PChar(nStr), cSize_HintBuffer); with FOwner do begin FSyncer.AddData(nBuf, Ord(stWarnHint)); FSyncer.ApplySync; end; end; procedure TMCGSReader.Stop; begin Terminate; FWaiter.Wakeup; WaitFor; Free; end; procedure TMCGSReader.Execute; begin CoInitialize(nil); while not Terminated do try DoExecute; except on E:Exception do begin {$IFDEF DEBUG} HintMsg(E.Message); {$ENDIF} Sleep(320); end; end; CoUninitialize; end; procedure TMCGSReader.DoExecute; var nIdx: Integer; nVar: OleVariant; nItem: TMCGSParamItem; nPItem: PMCGSParamItem; begin with FOwner do begin FWaiter.EnterWait; if Terminated then Exit; try if VarIsEmpty(FDataCenter) then begin FDataCenter := GetActiveOleObject('McgsRun.DataCentre'); if VarIsEmpty(FDataCenter) then Exit; end; nVar := FDataCenter.McgsDataNum; //check object valid except on E:Exception do begin FDataCenter := Unassigned; //has invalid {$IFDEF DEBUG} HintMsg(E.Message); {$ENDIF} FSyncer.AddData(nil, Ord(stNoRun)); FSyncer.ApplySync; //update ui status Exit; end; end; {$IFDEF DEBUG} HintMsg('对象呼叫成功,开始读取数据.'); {$ENDIF} for nIdx:=Low(FDH) to High(FDH) do begin if FDH[nIdx].FDH = cDHNull then Continue; //null nItem.FCH := FDH[nIdx].FCH; nItem.FDH := FDH[nIdx].FDH; nItem.FSerial := FDH[nIdx].FSerial; if not ReadParam(nIdx+1, nItem) then Continue; //read params {$IFDEF DEBUG} HintMsg('数据读取完毕,同步发送.'); {$ENDIF} if Assigned(FOnData) then FOnData(nItem); //thread event New(nPItem); nPItem^ := nItem; FSyncer.AddData(nPItem, 0); FSyncer.ApplySync; end; end; end; //Desc: 从实时数据库中读取栋号为nDH的参数 function TMCGSReader.ReadParam(const nDH: Integer; var nItem: TMCGSParamItem): Boolean; var nIdx: Integer; nName,nVal,nRes: OleVariant; begin for nIdx:=Low(cVarItem) to High(cVarItem) do with cVarItem[nIdx] do begin nName := Format(FVarName, [nDH]); nName := GetOutName(nName); {$IFDEF DEBUG} HintMsg(Format('开始读取变量:[ %s ] -> [ %s ]', [FVarName, nName])); {$ENDIF} if nName = '' then begin case FIndex of 0: nItem.Ffj1 := 0; 1: nItem.Ffj2 := 0; 2: nItem.Ffj3 := 0; 3: nItem.Ffj4 := 0; 4: nItem.Ffj5 := 0; 5: nItem.Ffjo := 0; 6: nItem.Ffjc := 0; 7: nItem.Ftfjb := 0; 8: nItem.Frs1 := 0; 9: nItem.Frs2 := 0; 10: nItem.Frs3 := 0; 11: nItem.Frs4 := 0; 12: nItem.Fmw := 0; 13: nItem.Fw1 := 0; 14: nItem.Fw2 := 0; 15: nItem.Fw3 := 0; 16: nItem.Fw4 := 0; 17: nItem.Fs1 := 0; 18: nItem.Fs2 := 0; 19: nItem.Fs3 := 0; 20: nItem.Fs4 := 0; 21: nItem.Frld := 0; 22: nItem.Frlh := 0; 23: nItem.Fllt := 0; 24: nItem.Fllk := 0; 25: nItem.Fslt := 0; 26: nItem.fslk := 0; 27: nItem.Fsww := 0; 28: nItem.Fcold := 0; 29: nItem.Fhot := 0; 30: nItem.Ftfbj := 0; 31: nItem.Frll := 0; 32: nItem.Fweight := 0; 33: nItem.Faq := 0; 34: nItem.Ffy1 := 0; 35: nItem.Ffy2 := 0; 36: nItem.Fslkd := 0; 37: nItem.Fslb := 0; 38: nItem.Fccl := 0; 39: nItem.Fccr := 0; end; {$IFDEF DEBUG} HintMsg(Format('变量[ %s ]不需要处理,已跳过.', [FVarName])); {$ENDIF} Continue; end; //default value nRes := FDataCenter.GetValueFromName(nName, nVal); Result := nRes = 0; if not Result then begin HintMsg(Format('变量[ %s ]处理错误,已跳过.', [nName])); Exit; end; case FIndex of 0: nItem.Ffj1 := nVal; 1: nItem.Ffj2 := nVal; 2: nItem.Ffj3 := nVal; 3: nItem.Ffj4 := nVal; 4: nItem.Ffj5 := nVal; 5: nItem.Ffjo := nVal; 6: nItem.Ffjc := nVal; 7: nItem.Ftfjb := nVal; 8: nItem.Frs1 := nVal; 9: nItem.Frs2 := nVal; 10: nItem.Frs3 := nVal; 11: nItem.Frs4 := nVal; 12: nItem.Fmw := nVal; 13: nItem.Fw1 := nVal; 14: nItem.Fw2 := nVal; 15: nItem.Fw3 := nVal; 16: nItem.Fw4 := nVal; 17: nItem.Fs1 := nVal; 18: nItem.Fs2 := nVal; 19: nItem.Fs3 := nVal; 20: nItem.Fs4 := nVal; 21: nItem.Frld := nVal; 22: nItem.Frlh := nVal; 23: nItem.Fllt := nVal; 24: nItem.Fllk := nVal; 25: nItem.Fslt := nVal; 26: nItem.fslk := nVal; 27: nItem.Fsww := nVal; 28: nItem.Fcold := nVal; 29: nItem.Fhot := nVal; 30: nItem.Ftfbj := nVal; 31: nItem.Frll := nVal; 32: nItem.Fweight := nVal; 33: nItem.Faq := nVal; 34: nItem.Ffy1 := nVal; 35: nItem.Ffy2 := nVal; 36: nItem.Fslkd := nVal; 37: nItem.Fslb := nVal; 38: nItem.Fccl := nVal; 39: nItem.Fccr := nVal; end; nVal := Unassigned; //set item value {$IFDEF DEBUG} HintMsg(nName + '数据完毕.'); {$ENDIF} end; Result := True; end; //------------------------------------------------------------------------------ constructor TMCGSManager.Create; begin FCH := ''; SetLength(FDH, 0); FInterval := 5; FReader := nil; FSyncer := TDataSynchronizer.Create; FSyncer.SyncEvent := DoSync; FSyncer.SyncFreeEvent := DoSyncFree; end; destructor TMCGSManager.Destroy; begin StopReader; FSyncer.Free; inherited; end; function TMCGSManager.GetStatus: Boolean; begin Result := Assigned(FReader); end; //Date: 2011-5-25 //Parm: 场号;栋号 //Desc: 设置场号,栋号 procedure TMCGSManager.SetDH(const nCH,nDH: string); var nIdx: Integer; nList: TStrings; begin if IsBusy then Exit; //running nList := TStringList.Create; try FCH := nCH; SetLength(FDH, 0); if not SplitStr(nDH, nList, 0, ',') then Exit; SetLength(FDH, nList.Count); for nIdx:=Low(FDH) to High(FDH) do begin with FDH[nIdx] do begin FCH := nCH; FDH := nList[nIdx]; FSerial := nIdx; FStatus := isAdd; FLastUpdate := Now; end; if Assigned(FOnItem) then FOnItem(FDH[nIdx]); //xxxxx end; finally nList.Free; end; end; //Desc: 停止采集 procedure TMCGSManager.StopReader; var nIdx: Integer; begin if Assigned(FReader) then begin FReader.Stop; FReader := nil; end; for nIdx:=Low(FDH) to High(FDH) do begin FDH[nIdx].FStatus := isNone; FDH[nIdx].FLastUpdate := Now; if Assigned(FOnItem) then FOnItem(FDH[nIdx]); //xxxxx end; end; //Desc: 开启采集 function TMCGSManager.StartReader(var nHint: string): Boolean; begin Result := False; if FCH = '' then begin nHint := '场号无效'; Exit; end; if Length(FDH) < 1 then begin nHint := '栋号无效'; Exit; end; if not LoadVarNames then begin nHint := '读取变量表错误'; Exit; end; if not Assigned(FReader) then FReader := TMCGSReader.Create(Self); Result := Assigned(FReader); end; //Desc: 线程到主进程同步数据 procedure TMCGSManager.DoSync(const nData: Pointer; const nSize: Cardinal); var nIdx: Integer; nItem: PMCGSParamItem; begin case nSize of Ord(stNoRun): begin if Assigned(FOnItem) then begin for nIdx:=Low(FDH) to High(FDH) do begin with FDH[nIdx] do begin FStatus := isNone; FLastUpdate := Now; end; FOnItem(FDH[nIdx]); end; Exit; //datacentre invalid end; end; Ord(stData): begin nItem := nData; if Assigned(FOnItem) then begin with FDH[nItem.FSerial] do begin FStatus := isUpdate; FLastUpdate := Now; end; FOnItem(FDH[nItem.FSerial]); end; if Assigned(FOnDataSync) then FOnDataSync(nItem^); //xxxxx end; Ord(stWarnHint): begin gDebugLog(StrPas(PChar(nData)), False); end; end; end; //Desc: 释放资源 procedure TMCGSManager.DoSyncFree(const nData: Pointer; const nSize: Cardinal); begin case nSize of Ord(stData): Dispose(PMCGSParamItem(nData)); Ord(stWarnHint): FreeMem(nData, cSize_HintBuffer); end; end; initialization gMCGSManager := TMCGSManager.Create; finalization FreeAndNil(gMCGSManager); end.
unit DevApp.Base.DetailForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, PascalCoin.RPC.Interfaces, FMX.Controls.Presentation, FMX.StdCtrls, PascalCoin.RPC.Exceptions; type TDevBaseForm = class(TForm) HeaderLayout: TLayout; FooterLayout: TLayout; ContentLayout: TLayout; FormCaption: TLabel; private FDefaultURI: String; procedure SetDefaultURI(const Value: String); { Private declarations } protected function NodeAPI: IPascalCoinNodeAPI; function ExplorerAPI: IPascalCoinExplorerAPI; function WalletExplorerAPI: IPascalCoinWalletAPI; function UseURI: String; virtual; procedure HandleAPIException(E: Exception); public { Public declarations } procedure InitialiseThis; virtual; function CanClose: Boolean; Virtual; procedure TearDown; virtual; property DefaultURI: String read FDefaultURI write SetDefaultURI; end; var DevBaseForm: TDevBaseForm; implementation {$R *.fmx} uses DevApp.Shared, FMX.DialogService; { TDevBaseForm } function TDevBaseForm.CanClose: Boolean; begin Result := True; end; function TDevBaseForm.ExplorerAPI: IPascalCoinExplorerAPI; begin Result := Config.Container.Resolve<IPascalCoinExplorerAPI>; Result.NodeURI := UseURI; end; function TDevBaseForm.NodeAPI: IPascalCoinNodeAPI; begin Result := Config.Container.Resolve<IPascalCoinNodeAPI>; Result.NodeURI := UseURI; end; procedure TDevBaseForm.HandleAPIException(E: Exception); begin TDialogService.ShowMessage(E.Message); end; procedure TDevBaseForm.InitialiseThis; begin //for descendants; not abstract as this is easier end; procedure TDevBaseForm.SetDefaultURI(const Value: String); begin FDefaultURI := Value; end; procedure TDevBaseForm.TearDown; begin //for descendants; not abstract as this is easier end; function TDevBaseForm.UseURI: String; begin Result := FDefaultURI; end; function TDevBaseForm.WalletExplorerAPI: IPascalCoinWalletAPI; begin Result := Config.Container.Resolve<IPascalCoinWalletAPI>; Result.NodeURI := UseURI; end; end.
unit HtmlTokenizer; interface uses ActiveX, Classes, SysUtils, Contnrs, DomCore, Entities; const CP_UTF16 = 1200; type TTokenizerState = ( tsDataState, // DoDataState; //13.2.5.1 Data state tsRCDataState, // DoRCDataState; //13.2.5.2 RCDATA state tsRawTextState, // DoRawTextState; //13.2.5.3 RAWTEXT state tsScriptDataState, // DoScriptDataState; //13.2.5.4 Script data state tsPlaintextState, // DoPlaintextState; //13.2.5.5 PLAINTEXT state tsTagOpenState, // DoTagOpenState; //13.2.5.6 Tag open state tsEndTagOpenState, // DoEndTagOpenState; //13.2.5.7 End tag open state tsTagNameState, // DoTagNameState; //13.2.5.8 Tag name state tsRCDATALessThanSignState, // DoRCDATALessThanSignState; //13.2.5.9 RCDATA less-than sign state tsRCDATAEndTagOpenState, // DoRCDATAEndTagOpenState; //13.2.5.10 RCDATA end tag open state tsRCDATAEndTagNameState, // DoRCDATAEndTagNameState; //13.2.5.11 RCDATA end tag name state tsRAWTEXTLessThanSignState, // DoRAWTEXTLessThanSignState; //13.2.5.12 RAWTEXT less-than sign state tsRAWTEXTEndTagOpenState, // DoRAWTEXTEndTagOpenState; //13.2.5.13 RAWTEXT end tag open state tsRAWTEXTEndTagNameState, // DoRAWTEXTEndTagNameState; //13.2.5.14 RAWTEXT end tag name state tsScriptDataLessThanSignState, // DoScriptDataLessThanSignState; //13.2.5.15 Script data less-than sign state tsScriptDataEndTagOpenState, // DoScriptDataEndTagOpenState; //13.2.5.16 Script data end tag open state tsScriptDataEndTagNameState, // DoScriptDataEndTagNameState; //13.2.5.17 Script data end tag name state tsScriptDataEscapeStartState, // DoScriptDataEscapeStartState; //13.2.5.18 Script data escape start state tsScriptDataEscapeStartDashState, // DoScriptDataEscapeStartDashState; //13.2.5.19 Script data escape start dash state tsScriptDataEscapedState, // DoScriptDataEscapedState; //13.2.5.20 Script data escaped state tsScriptDataEscapedDashState, // DoScriptDataEscapedDashState; //13.2.5.21 Script data escaped dash state tsScriptDataEscapedDashDashState, // DoScriptDataEscapedDashDashState; //13.2.5.22 Script data escaped dash dash state tsScriptDataEscapedLessThanSignState, // DoScriptDataEscapedLessThanSignState; //13.2.5.23 Script data escaped less-than sign state tsScriptDataEscapedEndTagOpenState, // DoScriptDataEscapedEndTagOpenState; //13.2.5.24 Script data escaped end tag open state tsScriptDataEscapedEndTagNameState, // DoScriptDataEscapedEndTagNameState; //13.2.5.25 Script data escaped end tag name state tsScriptDataDoubleEscapeStartState, // DoScriptDataDoubleEscapeStartState; //13.2.5.26 Script data double escape start state tsScriptDataDoubleEscapedState, // DoScriptDataDoubleEscapedState; //13.2.5.27 Script data double escaped state tsScriptDataDoubleEscapedDashState, // DoScriptDataDoubleEscapedDashState; //13.2.5.28 Script data double escaped dash state tsScriptDataDoubleEscapedDashDashState, // DoScriptDataDoubleEscapedDashDashState; //13.2.5.29 Script data double escaped dash dash state tsScriptDataDoubleEscapedLessThanSignState, // DoScriptDataDoubleEscapedLessThanSignState; //13.2.5.30 Script data double escaped less-than sign state tsScriptDataDoubleEscapeEndState, // DoScriptDataDoubleEscapeEndState; //13.2.5.31 Script data double escape end state tsBeforeAttributeNameState, // DoBeforeAttributeNameState; //13.2.5.32 Before attribute name state tsAttributeNameState, // DoAttributeNameState; //13.2.5.33 Attribute name state tsAfterAttributeNameState, // DoAfterAttributeNameState; //13.2.5.34 After attribute name state tsBeforeAttributeValueState, // DoBeforeAttributeValueState; //13.2.5.35 Before attribute value state tsAttributeValueDoubleQuotedState, // DoAttributeValueDoubleQuotedState; //13.2.5.36 Attribute value (double-quoted) state tsAttributeValueSingleQuotedState, // DoAttributeValueSingleQuotedState; //13.2.5.37 Attribute value (single-quoted) state tsAttributeValueUnquotedState, // DoAttributeValueUnquotedState; //13.2.5.38 Attribute value (unquoted) state tsAfterAttributeValueQuotedState, // DoAfterAttributeValueQuotedState; //13.2.5.39 After attribute value (quoted) state tsSelfClosingStartTagState, // DoSelfClosingStartTagState; //13.2.5.40 Self-closing start tag state tsBogusCommentState, // DoBogusCommentState; //13.2.5.41 Bogus comment state tsMarkupDeclarationOpenState, // DoMarkupDeclarationOpenState; //13.2.5.42 Markup declaration open state tsCommentStartState, // DoCommentStartState; //13.2.5.43 Comment start state tsCommentStartDashState, // DoCommentStartDashState; //13.2.5.44 Comment start dash state tsCommentState, // DoCommentState; //13.2.5.45 Comment state tsCommentLessThanSignState, // DoCommentLessThanSignState; //13.2.5.46 Comment less-than sign state tsCommentLessThanSignBangState, // DoCommentLessThanSignBangState; //13.2.5.47 Comment less-than sign bang state tsCommentLessThanSignBangDashState, // DoCommentLessThanSignBangDashState; //13.2.5.48 Comment less-than sign bang dash state tsCommentLessThanSignBangDashDashState, // DoCommentLessThanSignBangDashDashState; //13.2.5.49 Comment less-than sign bang dash dash state tsCommentEndDashState, // DoCommentEndDashState; //13.2.5.50 Comment end dash state tsCommentEndState, // DoCommentEndState; //13.2.5.51 Comment end state tsCommentEndBangState, // DoCommentEndBangState; //13.2.5.52 Comment end bang state tsDOCTYPEState, // DoDOCTYPEState; //13.2.5.53 DOCTYPE state tsBeforeDOCTYPENameState, // DoBeforeDOCTYPENameState; //13.2.5.54 Before DOCTYPE name state tsDOCTYPENameState, // DoDOCTYPENameState; //13.2.5.55 DOCTYPE name state tsAfterDOCTYPENameState, // DoAfterDOCTYPENameState; //13.2.5.56 After DOCTYPE name state tsAfterDOCTYPEPublicKeywordState, // DoAfterDOCTYPEPublicKeywordState; //13.2.5.57 After DOCTYPE public keyword state tsBeforeDOCTYPEPublicIdentifierState, // DoBeforeDOCTYPEPublicIdentifierState; //13.2.5.58 Before DOCTYPE public identifier state tsDOCTYPEPublicIdentifierDoubleQuotedState, // DoDOCTYPEPublicIdentifierDoubleQuotedState; //13.2.5.59 DOCTYPE public identifier (double-quoted) state tsDOCTYPEPublicIdentifierSingleQuotedState, // DoDOCTYPEPublicIdentifierSingleQuotedState; //13.2.5.60 DOCTYPE public identifier (single-quoted) state tsAfterDOCTYPEPublicIdentifierState, // DoAfterDOCTYPEPublicIdentifierState; //13.2.5.61 After DOCTYPE public identifier state tsBetweenDOCTYPEPublicAndSystemIdentifiersState, // DoBetweenDOCTYPEPublicAndSystemIdentifiersState; //13.2.5.62 Between DOCTYPE public and system identifiers state tsAfterDOCTYPESystemKeywordState, // DoAfterDOCTYPESystemKeywordState; //13.2.5.63 After DOCTYPE system keyword state tsBeforeDOCTYPESystemIdentifierState, // DoBeforeDOCTYPESystemIdentifierState; //13.2.5.64 Before DOCTYPE system identifier state tsDOCTYPESystemIdentifierDoubleQuotedState, // DoDOCTYPESystemIdentifierDoubleQuotedState; //13.2.5.65 DOCTYPE system identifier (double-quoted) state tsDOCTYPESystemIdentifierSingleQuotedState, // DoDOCTYPESystemIdentifierSingleQuotedState; //13.2.5.66 DOCTYPE system identifier (single-quoted) state tsAfterDOCTYPESystemIdentifierState, // DoAfterDOCTYPESystemIdentifierState; //13.2.5.67 After DOCTYPE system identifier state tsBogusDOCTYPEState, // DoBogusDOCTYPEState; //13.2.5.68 Bogus DOCTYPE state tsCDATASectionState, // DoCDATASectionState; //13.2.5.69 CDATA section state tsCDATASectionBracketState, // DoCDATASectionBracketState; //13.2.5.70 CDATA section bracket state tsCDATASectionEndState, // DoCDATASectionEndState; //13.2.5.71 CDATA section end state tsCharacterReferenceState, // DoCharacterReferenceState; //13.2.5.72 Character reference state tsNamedCharacterReferenceState, // DoNamedCharacterReferenceState; //13.2.5.73 Named character reference state tsAmbiguousAmpersandState, // DoAmbiguousAmpersandState; //13.2.5.74 Ambiguous ampersand state tsNumericCharacterReferenceState, // DoNumericCharacterReferenceState; //13.2.5.75 Numeric character reference state tsHexadecimalCharacterReferenceStartState, // DoHexadecimalCharacterReferenceStartState; //13.2.5.76 Hexadecimal character reference start state tsDecimalCharacterReferenceStartState, // DoDecimalCharacterReferenceStartState; //13.2.5.77 Decimal character reference start state tsHexadecimalCharacterReferenceState, // DoHexadecimalCharacterReferenceState; //13.2.5.78 Hexadecimal character reference state tsDecimalCharacterReferenceState, // DoDecimalCharacterReferenceState; //13.2.5.79 Decimal character reference state tsNumericCharacterReferenceEndState // DoNumericCharacterReferenceEndState; //13.2.5.80 Numeric character reference end state ); //The output of the tokenization step is a series of zero or more of the following tokens: THtmlTokenType = ( ttDocType, //DOCTYPE (TDocTypeToken) ttStartTag, //start tag (TStartTagToken) ttEndTag, //end tag (TEndTagToken) ttComment, //comment (TCommentToken) ttCharacter, //character (TCharacterToken) ttEndOfFile //end-of-file (TEndOfFileToken) ); { The InputStream supplies a series of Unicode characters to the tokenizer. The InputStream also takes care of converting any CRLF into LF (as CR is never allowed to reach the HTML tokenizer) } TInputStream = class private FStream: ISequentialStream; FEncoding: Word; FEOF: Boolean; FBuffer: UCS4String; FBufferPosition: Integer; //the index into FBuffer that is the "current" position FBufferSize: Integer; //the number of characters in the ring buffer (from FBufferPosition) that are valid function IsSurrogate(const n: Word): Boolean; function GetNextCharacterFromStream: UCS4Char; function GetNextUTF16Character: UCS4Char; function Consume: UCS4Char; function FetchNextCharacterInfoBuffer: Boolean; procedure LogFmt(const s: string; const Args: array of const); public constructor Create(const Html: UnicodeString); overload; constructor Create(ByteStream: ISequentialStream; Encoding: Word=CP_UTF16); overload; function TryRead(out ch: UCS4Char): Boolean; //Returns the next UCS4 character value. function Peek(k: Integer): UCS4Char; //peek the k-th upcoming character property EOF: Boolean read FEOF; end; { The base class for the tokens emitted by the tokenizer THtmlToken - TDocTypeToken - TTagToken - TStartTagToken - TEndTagToken - TCommentToken - TCharacterToken - TEndOfFileToken } THtmlToken = class protected function GetDescription: string; virtual; public TokenType: THtmlTokenType; constructor Create(ATokenType: THtmlTokenType); property Description: string read GetDescription; end; TDocTypeToken = class(THtmlToken) private FName: UnicodeString; FPublicIdentifier: UnicodeString; FSystemIdentifier: UnicodeString; FForceQuirks: Boolean; FNameMissing: Boolean; FPublicIdentifierMissing: Boolean; FSystemIdentifierMissing: Boolean; procedure SetPublicIdentifier(const Value: UnicodeString); procedure SetSystemIdentifier(const Value: UnicodeString); procedure SetName(const Value: UnicodeString); protected procedure AppendName(const ch: UCS4Char); //to the Name procedure AppendPublicIdentifier(const ch: UCS4Char); procedure AppendSystemIdentifier(const ch: UCS4Char); function GetDescription: string; override; public constructor Create; property Name: UnicodeString read FName write SetName; property PublicIdentifier: UnicodeString read FPublicIdentifier write SetPublicIdentifier; property SystemIdentifier: UnicodeString read FSystemIdentifier write SetSystemIdentifier; property NameMissing: Boolean read FNameMissing; property PublicIdentifierMissing: Boolean read FPublicIdentifierMissing; property SystemIdentifierMissing: Boolean read FSystemIdentifierMissing; property ForceQuirks: Boolean read FForceQuirks write FForceQuirks; end; //Base class of StartTagToken and EndTagToken TTagToken = class(THtmlToken) private FData: UCS4String; FAttributes: TList; FSelfClosing: Boolean; function GetTagName: UnicodeString; protected CurrentAttributeName: UnicodeString; CurrentAttributeValue: UnicodeString; procedure NewAttribute; procedure FinalizeAttributeName; function GetDescription: string; override; public constructor Create(ATokenType: THtmlTokenType); destructor Destroy; override; procedure AppendCharacter(const ch: UCS4Char); //append to TagName property TagName: UnicodeString read GetTagName; property Attributes: TList read FAttributes; property SelfClosing: Boolean read FSelfClosing write FSelfClosing; end; TStartTagToken = class(TTagToken) public constructor Create; procedure AcknowledgeSelfClosing; end; TEndTagToken = class(TTagToken) public constructor Create; end; TCommentToken = class(THtmlToken) private FData: UCS4String; function GetDataString: UnicodeString; protected function GetDescription: string; override; public constructor Create; procedure AppendCharacter(const ch: UCS4Char); //to Data property DataString: UnicodeString read GetDataString; end; TCharacterToken = class(THtmlToken) private function GetDataString: UnicodeString; protected function GetDescription: string; override; public Data: UCS4Char; constructor Create; property DataString: UnicodeString read GetDataString; end; TEndOfFileToken = class(THtmlToken) protected function GetDescription: string; override; public Data: UCS4String; constructor Create; end; TTokenEvent = procedure(Sender: TObject; AToken: THtmlToken) of object; THtmlTokenizer = class private FStream: TInputStream; FState2: TTokenizerState; FReturnState2: TTokenizerState; FCurrentInputCharacter: UCS4Char; FCurrentToken: THtmlToken; FCharacterReferenceCode: Cardinal; FReconsume: Boolean; FEOF: Boolean; FTemporaryBuffer: UCS4String; FNameOfLastEmittedStartTag: string; FParserPause: Boolean; FOnToken: TTokenEvent; //event handler procedure AddNotImplementedParseError(const StateHandlerName: string); function GetNext: UCS4Char; procedure Initialize; procedure AddParseError(ParseErrorName: string); //The output of the tokenization step is a series of zero or more of the following tokens: // DOCTYPE, start tag, end tag, comment, character, end-of-file. // DOCTYPE tokens have a name, a public identifier, a system identifier, and a force-quirks flag. procedure EmitToken(const AToken: THtmlToken); procedure EmitCurrentDocTypeToken; //Emit the current DOCTYPE token procedure EmitCurrentTagToken; //Emits the current token (whether it be a StartTag or EndTag) procedure EmitStartTag; //Emit the current StartTag token procedure EmitEndTag; //Emit the current EndTag token procedure EmitCurrentCommentToken; //Emit the current Comment token procedure EmitCharacter(const Character: UCS4Char); //Emit a Character token procedure EmitEndOfFileToken; //Emit an EndOfFile token procedure Reconsume(NewTokenizerState: TTokenizerState); procedure SetReturnState(const State: TTokenizerState); function Consume: UCS4Char; function NextFewCharacters(const Value: UnicodeString; const CaseSensitive: Boolean; const IncludingCurrentInputCharacter: Boolean): Boolean; function GetCurrentTagToken: TTagToken; function TemporaryBufferIs(const Value: UnicodeString): Boolean; procedure AppendToTemporaryBuffer(const Value: UCS4Char); procedure AppendToCurrentAttributeName(const Value: UCS4Char); procedure AppendToCurrentAttributeValue(const Value: UCS4Char); procedure AppendToCurrentCommentData(const Value: UCS4Char); procedure FlushCodePointsConsumed; function IsAppropriateEndTag(const EndTagToken: TEndTagToken): Boolean; function IsConsumedAsPartOfAnAttribute: Boolean; procedure LogFmt(const Fmt: string; const Args: array of const); property CurrentInputCharacter: UCS4Char read FCurrentInputCharacter; //The current input character is the last character to have been consumed. property CurrentTagToken: TTagToken read GetCurrentTagToken; //The current tag token (either TStartTagtoken or TEndTagToken) private //Tokenizer state machine handlers procedure DoDataState; //13.2.5.1 Data state procedure DoRCDATAState; //13.2.5.2 RCDATA state procedure DoRawTextState; //13.2.5.3 RAWTEXT state procedure DoScriptDataState; //13.2.5.4 Script data state procedure DoPlaintextState; //13.2.5.5 PLAINTEXT state procedure DoTagOpenState; //13.2.5.6 Tag open state procedure DoEndTagOpenState; //13.2.5.7 End tag open state procedure DoTagNameState; //13.2.5.8 Tag name state procedure DoRCDATALessThanSignState; //13.2.5.9 RCDATA less-than sign state procedure DoRCDATAEndTagOpenState; //13.2.5.10 RCDATA end tag open state procedure DoRCDATAEndTagNameState; //13.2.5.11 RCDATA end tag name state procedure DoRAWTEXTLessThanSignState; //13.2.5.12 RAWTEXT less-than sign state procedure DoRAWTEXTEndTagOpenState; //13.2.5.13 RAWTEXT end tag open state procedure DoRAWTEXTEndTagNameState; //13.2.5.14 RAWTEXT end tag name state procedure DoScriptDataLessThanSignState; //13.2.5.15 Script data less-than sign state procedure DoScriptDataEndTagOpenState; //13.2.5.16 Script data end tag open state procedure DoScriptDataEndTagNameState; //13.2.5.17 Script data end tag name state procedure DoScriptDataEscapeStartState; //13.2.5.18 Script data escape start state procedure DoScriptDataEscapeStartDashState; //13.2.5.19 Script data escape start dash state procedure DoScriptDataEscapedState; //13.2.5.20 Script data escaped state procedure DoScriptDataEscapedDashState; //13.2.5.21 Script data escaped dash state procedure DoScriptDataEscapedDashDashState; //13.2.5.22 Script data escaped dash dash state procedure DoScriptDataEscapedLessThanSignState; //13.2.5.23 Script data escaped less-than sign state procedure DoScriptDataEscapedEndTagOpenState; //13.2.5.24 Script data escaped end tag open state procedure DoScriptDataEscapedEndTagNameState; //13.2.5.25 Script data escaped end tag name state procedure DoScriptDataDoubleEscapeStartState; //13.2.5.26 Script data double escape start state procedure DoScriptDataDoubleEscapedState; //13.2.5.27 Script data double escaped state procedure DoScriptDataDoubleEscapedDashState; //13.2.5.28 Script data double escaped dash state procedure DoScriptDataDoubleEscapedDashDashState; //13.2.5.29 Script data double escaped dash dash state procedure DoScriptDataDoubleEscapedLessThanSignState; //13.2.5.30 Script data double escaped less-than sign state procedure DoScriptDataDoubleEscapeEndState; //13.2.5.31 Script data double escape end state procedure DoBeforeAttributeNameState; //13.2.5.32 Before attribute name state procedure DoAttributeNameState; //13.2.5.33 Attribute name state procedure DoAfterAttributeNameState; //13.2.5.34 After attribute name state procedure DoBeforeAttributeValueState; //13.2.5.35 Before attribute value state procedure DoAttributeValueDoubleQuotedState; //13.2.5.36 Attribute value (double-quoted) state procedure DoAttributeValueSingleQuotedState; //13.2.5.37 Attribute value (single-quoted) state procedure DoAttributeValueUnquotedState; //13.2.5.38 Attribute value (unquoted) state procedure DoAfterAttributeValueQuotedState; //13.2.5.39 After attribute value (quoted) state procedure DoSelfClosingStartTagState; //13.2.5.40 Self-closing start tag state procedure DoBogusCommentState; //13.2.5.41 Bogus comment state procedure DoMarkupDeclarationOpenState; procedure DoCommentStartState; //13.2.5.43 Comment start state procedure DoCommentStartDashState; //13.2.5.44 Comment start dash state procedure DoCommentState; //13.2.5.45 Comment state procedure DoCommentLessThanSignState; //13.2.5.46 Comment less-than sign state procedure DoCommentLessThanSignBangState; //13.2.5.47 Comment less-than sign bang state procedure DoCommentLessThanSignBangDashState; //13.2.5.48 Comment less-than sign bang dash state procedure DoCommentLessThanSignBangDashDashState; //13.2.5.49 Comment less-than sign bang dash dash state procedure DoCommentEndDashState; //13.2.5.50 Comment end dash state procedure DoCommentEndState; //13.2.5.51 Comment end state procedure DoCommentEndBangState; //13.2.5.52 Comment end bang state procedure DoDOCTYPEState; //13.2.5.53 DOCTYPE state procedure DoBeforeDOCTYPENameState; //13.2.5.54 Before DOCTYPE name state procedure DoDOCTYPENameState; //13.2.5.55 DOCTYPE name state procedure DoAfterDOCTYPENameState; //13.2.5.56 After DOCTYPE name state procedure DoAfterDOCTYPEPublicKeywordState; //13.2.5.57 After DOCTYPE public keyword state procedure DoBeforeDOCTYPEPublicIdentifierState; //13.2.5.58 Before DOCTYPE public identifier state procedure DoDOCTYPEPublicIdentifierDoubleQuotedState; //13.2.5.59 DOCTYPE public identifier (double-quoted) state procedure DoDOCTYPEPublicIdentifierSingleQuotedState; //13.2.5.60 DOCTYPE public identifier (single-quoted) state procedure DoAfterDOCTYPEPublicIdentifierState; //13.2.5.61 After DOCTYPE public identifier state procedure DoBetweenDOCTYPEPublicAndSystemIdentifiersState; //13.2.5.62 Between DOCTYPE public and system identifiers state procedure DoAfterDOCTYPESystemKeywordState; //13.2.5.63 After DOCTYPE system keyword state procedure DoBeforeDOCTYPESystemIdentifierState; //13.2.5.64 Before DOCTYPE system identifier state procedure DoDOCTYPESystemIdentifierDoubleQuotedState; //13.2.5.65 DOCTYPE system identifier (double-quoted) state procedure DoDOCTYPESystemIdentifierSingleQuotedState; //13.2.5.66 DOCTYPE system identifier (single-quoted) state procedure DoAfterDOCTYPESystemIdentifierState; //13.2.5.67 After DOCTYPE system identifier state procedure DoBogusDOCTYPEState; //13.2.5.68 Bogus DOCTYPE state procedure DoCDATASectionState; //13.2.5.69 CDATA section state procedure DoCDATASectionBracketState; //13.2.5.70 CDATA section bracket state procedure DoCDATASectionEndState; //13.2.5.71 CDATA section end state procedure DoCharacterReferenceState; //13.2.5.72 Character reference state procedure DoNamedCharacterReferenceState; //13.2.5.73 Named character reference state procedure DoAmbiguousAmpersandState; //13.2.5.74 Ambiguous ampersand state procedure DoNumericCharacterReferenceState; //13.2.5.75 Numeric character reference state procedure DoHexadecimalCharacterReferenceStartState; //13.2.5.76 Hexadecimal character reference start state procedure DoDecimalCharacterReferenceStartState; //13.2.5.77 Decimal character reference start state procedure DoHexadecimalCharacterReferenceState; //13.2.5.78 Hexadecimal character reference state procedure DoDecimalCharacterReferenceState; //13.2.5.79 Decimal character reference state procedure DoNumericCharacterReferenceEndState; //13.2.5.80 Numeric character reference end state public constructor Create(Html: UnicodeString); procedure Parse; procedure SetState(const State: TTokenizerState); //tree construction has two situations where it needs to change the tokenzier state property ParserPause: Boolean read FParserPause write FParserPause; property OnToken: TTokenEvent read FOnToken write FOnToken; end; { Delphi 5 had the issue with .Stat implementation: Potential issue in TStreamAdapter.Stat implementation http://qc.embarcadero.com/wc/qcmain.aspx?d=45528 Alpha Blended Splash Screen in Delphi - Part 2 http://melander.dk/articles/alphasplash2/2/ The problem with TStreamAdapter is in its implementation of the IStream.stat method. The stat method takes two parameters: A STATSTG out parameter and a STATFLAG value. The STATFLAG value specifies if the stat method should return a value in the STATSTG.pwcsName member. If it does return a value, it is the responsibility of the called object (i.e. TStreamAdapter) to allocate memory for the string value, and the responsibility of the caller (i.e. GDI+) to deallocate the string. Now TStreamAdapter.stat completely ignores the STATFLAG parameter, which is understandable because it doesn’t know anything about filenames, but unfortunately it also fails to zero the STATSTG.pwcsName member. The result is that the caller (GDI+ in this case) receives an invalid string That was fixed by the time XE6 came along, but there's another bug (10.3) The .Read method is supposed to return S_FALSE if the number of bytes read was less than the number of bytes requested. And it's supposed to return an error if there was an error (rather than success). } TFixedStreamAdapter = class(TStreamAdapter) public function Read(pv: Pointer; cb: FixedUInt; pcbRead: PFixedUInt): HResult; override; stdcall; end; //Again, the version is Dephi is buggy. So we fix their bugs for them. function UCS4ToUnicodeString(const S: UCS4String): UnicodeString; procedure UCS4StrCat(var Dest: UCS4String; const Source: UCS4Char); //similar to System._UStrCat procedure UCS4StrFromChar(var Dest: UCS4String; const Source: UCS4Char); //similar to System._UStrFromChar procedure UCS4StrFromUStr(var Dest: UCS4String; const Source: UnicodeString); function UCS4StrCopy(const S: UCS4String; Index, Count: Integer): UCS4String; //similar to System._UStrCopy procedure UCS4StrFromPUCS4CharLen(var Dest: UCS4String; Source: PUCS4Char; CharLength: Integer); //similar to System._UStrFromPWCharLen function UCS4CharToUnicodeString(const ch: UCS4Char): UnicodeString; //either 1 or 2 WideChar implementation uses Windows, TypInfo, ComObj, HtmlParserTests, HtmlTags; const //https://infra.spec.whatwg.org/#code-points asciiTabOrNewline = [$0009, $000A, $000D]; //TAB, LF, CR. https://infra.spec.whatwg.org/#ascii-tab-or-newline asciiWhitespace = [$0009, $000A, $000C, $000D, $0020]; //TAB, LF, FF, CR, SPACE. //https://infra.spec.whatwg.org/#ascii-whitespace asciiDigit = [Ord('0')..Ord('9')]; //https://infra.spec.whatwg.org/#ascii-digit asciiUpperHexDigit = [Ord('A')..Ord('F')]; //https://infra.spec.whatwg.org/#ascii-upper-hex-digit asciiLowerHexDigit = [Ord('a')..Ord('f')]; //https://infra.spec.whatwg.org/#ascii-lower-hex-digit asciiHexDigit = asciiUpperHexDigit + asciiLowerHexDigit; //https://infra.spec.whatwg.org/#ascii-hex-digit asciiUpperAlpha = [Ord('A')..Ord('Z')]; //https://infra.spec.whatwg.org/#ascii-upper-alpha asciiLowerAlpha = [Ord('a')..Ord('z')]; //https://infra.spec.whatwg.org/#ascii-lower-alpha asciiAlpha = asciiUpperAlpha + asciiLowerAlpha; //https://infra.spec.whatwg.org/#ascii-alpha asciiAlphaNumeric = asciiDigit + asciiAlpha; //https://infra.spec.whatwg.org/#ascii-alphanumeric UEOF = UCS4Char(-1); //A special EOF unicode character { THtmlTokenizer } procedure THtmlTokenizer.LogFmt(const Fmt: string; const Args: array of const); var s: string; begin if IsDebuggerPresent then begin s := Format(Fmt, Args); OutputDebugString(PChar(s)); end; end; function THtmlTokenizer.NextFewCharacters(const Value: UnicodeString; const CaseSensitive: Boolean; const IncludingCurrentInputCharacter: Boolean): Boolean; var ch: UCS4Char; wc: WideChar; i: Integer; nStart: Integer; peek: UnicodeString; peekOffset: Integer; begin Result := False; if Value = '' then raise Exception.Create('NextFewCharacters peek value cannot be empty'); SetLength(peek, Length(Value)); nStart := 1; if IncludingCurrentInputCharacter then begin if FCurrentInputCharacter > $FFFF then begin LogFmt('Got extended unicode character while peeking. Leaving. (0x%.8x)', [FCurrentInputCharacter]); Exit; end; wc := WideChar(FCurrentInputCharacter); peek[1] := wc; Inc(nStart); end; peekOffset := 1; for i := nStart to Length(Value) do begin ch := FStream.Peek(peekOffset); if ch > $FFFF then Exit; wc := WideChar(ch); peek[i] := wc; Inc(peekOffset); end; if CaseSensitive then Result := (peek = Value) else Result := SameText(peek, Value); end; procedure THtmlTokenizer.AddNotImplementedParseError(const StateHandlerName: string); begin AddParseError('not-implemented-'+StateHandlerName); raise ENotImplemented.Create(StateHandlerName); end; procedure THtmlTokenizer.AddParseError(ParseErrorName: string); begin LogFmt('Parse Error: %s', [ParseErrorName]); end; procedure THtmlTokenizer.AppendToCurrentAttributeName(const Value: UCS4Char); begin CurrentTagToken.CurrentAttributeName := CurrentTagToken.CurrentAttributeName + UCS4CharToUnicodeString(Value); end; procedure THtmlTokenizer.AppendToCurrentAttributeValue(const Value: UCS4Char); begin CurrentTagToken.CurrentAttributeValue := CurrentTagToken.CurrentAttributeValue + UCS4CharToUnicodeString(Value); end; procedure THtmlTokenizer.AppendToCurrentCommentData(const Value: UCS4Char); begin (FCurrentToken as TCommentToken).AppendCharacter(Value); end; procedure THtmlTokenizer.AppendToTemporaryBuffer(const Value: UCS4Char); begin UCS4StrCat(FTemporaryBuffer, Value); end; function THtmlTokenizer.Consume: UCS4Char; begin if (FReconsume) then begin FReconsume := False; end else begin FCurrentInputCharacter := Self.GetNext; end; Result := FCurrentInputCharacter; LogFmt('<== U+%.8x (''%s'')', [Result, WideChar(Result)]); end; constructor THtmlTokenizer.Create(Html: UnicodeString); begin inherited Create; Initialize; FStream := TInputStream.Create(Html); end; procedure THtmlTokenizer.Parse; begin while not FEOF do begin { Before each step of the tokenizer, the user agent must first check the parser pause flag. If it is true, then the tokenizer must abort the processing of any nested invocations of the tokenizer, yielding control back to the caller. } if ParserPause then Exit; case FState2 of tsDataState: DoDataState; //13.2.5.1 Data state tsRCDataState: DoRCDATAState; //13.2.5.2 RCDATA state tsRawTextState: DoRawTextState; //13.2.5.3 RAWTEXT state tsScriptDataState: DoScriptDataState; //13.2.5.4 Script data state tsPlaintextState: DoPlaintextState; //13.2.5.5 PLAINTEXT state tsTagOpenState: DoTagOpenState; //13.2.5.6 Tag open state tsEndTagOpenState: DoEndTagOpenState; //13.2.5.7 End tag open state tsTagNameState: DoTagNameState; //13.2.5.8 Tag name state tsRCDATALessThanSignState: DoRCDATALessThanSignState; //13.2.5.9 RCDATA less-than sign state tsRCDATAEndTagOpenState: DoRCDATAEndTagOpenState; //13.2.5.10 RCDATA end tag open state tsRCDATAEndTagNameState: DoRCDATAEndTagNameState; //13.2.5.11 RCDATA end tag name state tsRAWTEXTLessThanSignState: DoRAWTEXTLessThanSignState; //13.2.5.12 RAWTEXT less-than sign state tsRAWTEXTEndTagOpenState: DoRAWTEXTEndTagOpenState; //13.2.5.13 RAWTEXT end tag open state tsRAWTEXTEndTagNameState: DoRAWTEXTEndTagNameState; //13.2.5.14 RAWTEXT end tag name state tsScriptDataLessThanSignState: DoScriptDataLessThanSignState; //13.2.5.15 Script data less-than sign state tsScriptDataEndTagOpenState: DoScriptDataEndTagOpenState; //13.2.5.16 Script data end tag open state tsScriptDataEndTagNameState: DoScriptDataEndTagNameState; //13.2.5.17 Script data end tag name state tsScriptDataEscapeStartState: DoScriptDataEscapeStartState; //13.2.5.18 Script data escape start state tsScriptDataEscapeStartDashState: DoScriptDataEscapeStartDashState; //13.2.5.19 Script data escape start dash state tsScriptDataEscapedState: DoScriptDataEscapedState; //13.2.5.20 Script data escaped state tsScriptDataEscapedDashState: DoScriptDataEscapedDashState; //13.2.5.21 Script data escaped dash state tsScriptDataEscapedDashDashState: DoScriptDataEscapedDashDashState; //13.2.5.22 Script data escaped dash dash state tsScriptDataEscapedLessThanSignState: DoScriptDataEscapedLessThanSignState; //13.2.5.23 Script data escaped less-than sign state tsScriptDataEscapedEndTagOpenState: DoScriptDataEscapedEndTagOpenState; //13.2.5.24 Script data escaped end tag open state tsScriptDataEscapedEndTagNameState: DoScriptDataEscapedEndTagNameState; //13.2.5.25 Script data escaped end tag name state tsScriptDataDoubleEscapeStartState: DoScriptDataDoubleEscapeStartState; //13.2.5.26 Script data double escape start state tsScriptDataDoubleEscapedState: DoScriptDataDoubleEscapedState; //13.2.5.27 Script data double escaped state tsScriptDataDoubleEscapedDashState: DoScriptDataDoubleEscapedDashState; //13.2.5.28 Script data double escaped dash state tsScriptDataDoubleEscapedDashDashState: DoScriptDataDoubleEscapedDashDashState; //13.2.5.29 Script data double escaped dash dash state tsScriptDataDoubleEscapedLessThanSignState: DoScriptDataDoubleEscapedLessThanSignState; //13.2.5.30 Script data double escaped less-than sign state tsScriptDataDoubleEscapeEndState: DoScriptDataDoubleEscapeEndState; //13.2.5.31 Script data double escape end state tsBeforeAttributeNameState: DoBeforeAttributeNameState; //13.2.5.32 Before attribute name state tsAttributeNameState: DoAttributeNameState; //13.2.5.33 Attribute name state tsAfterAttributeNameState: DoAfterAttributeNameState; //13.2.5.34 After attribute name state tsBeforeAttributeValueState: DoBeforeAttributeValueState; //13.2.5.35 Before attribute value state tsAttributeValueDoubleQuotedState: DoAttributeValueDoubleQuotedState; //13.2.5.36 Attribute value (double-quoted) state tsAttributeValueSingleQuotedState: DoAttributeValueSingleQuotedState; //13.2.5.37 Attribute value (single-quoted) state tsAttributeValueUnquotedState: DoAttributeValueUnquotedState; //13.2.5.38 Attribute value (unquoted) state tsAfterAttributeValueQuotedState: DoAfterAttributeValueQuotedState; //13.2.5.39 After attribute value (quoted) state tsSelfClosingStartTagState: DoSelfClosingStartTagState; //13.2.5.40 Self-closing start tag state tsBogusCommentState: DoBogusCommentState; //13.2.5.41 Bogus comment state tsMarkupDeclarationOpenState: DoMarkupDeclarationOpenState; //13.2.5.42 Markup declaration open state tsCommentStartState: DoCommentStartState; //13.2.5.43 Comment start state tsCommentStartDashState: DoCommentStartDashState; //13.2.5.44 Comment start dash state tsCommentState: DoCommentState; //13.2.5.45 Comment state tsCommentLessThanSignState: DoCommentLessThanSignState; //13.2.5.46 Comment less-than sign state tsCommentLessThanSignBangState: DoCommentLessThanSignBangState; //13.2.5.47 Comment less-than sign bang state tsCommentLessThanSignBangDashState: DoCommentLessThanSignBangDashState; //13.2.5.48 Comment less-than sign bang dash state tsCommentLessThanSignBangDashDashState: DoCommentLessThanSignBangDashDashState; //13.2.5.49 Comment less-than sign bang dash dash state tsCommentEndDashState: DoCommentEndDashState; //13.2.5.50 Comment end dash state tsCommentEndState: DoCommentEndState; //13.2.5.51 Comment end state tsCommentEndBangState: DoCommentEndBangState; //13.2.5.52 Comment end bang state tsDOCTYPEState: DoDOCTYPEState; //13.2.5.53 DOCTYPE state tsBeforeDOCTYPENameState: DoBeforeDOCTYPENameState; //13.2.5.54 Before DOCTYPE name state tsDOCTYPENameState: DoDOCTYPENameState; //13.2.5.55 DOCTYPE name state tsAfterDOCTYPENameState: DoAfterDOCTYPENameState; //13.2.5.56 After DOCTYPE name state tsAfterDOCTYPEPublicKeywordState: DoAfterDOCTYPEPublicKeywordState; //13.2.5.57 After DOCTYPE public keyword state tsBeforeDOCTYPEPublicIdentifierState: DoBeforeDOCTYPEPublicIdentifierState; //13.2.5.58 Before DOCTYPE public identifier state tsDOCTYPEPublicIdentifierDoubleQuotedState: DoDOCTYPEPublicIdentifierDoubleQuotedState; //13.2.5.59 DOCTYPE public identifier (double-quoted) state tsDOCTYPEPublicIdentifierSingleQuotedState: DoDOCTYPEPublicIdentifierSingleQuotedState; //13.2.5.60 DOCTYPE public identifier (single-quoted) state tsAfterDOCTYPEPublicIdentifierState: DoAfterDOCTYPEPublicIdentifierState; //13.2.5.61 After DOCTYPE public identifier state tsBetweenDOCTYPEPublicAndSystemIdentifiersState: DoBetweenDOCTYPEPublicAndSystemIdentifiersState; //13.2.5.62 Between DOCTYPE public and system identifiers state tsAfterDOCTYPESystemKeywordState: DoAfterDOCTYPESystemKeywordState; //13.2.5.63 After DOCTYPE system keyword state tsBeforeDOCTYPESystemIdentifierState: DoBeforeDOCTYPESystemIdentifierState; //13.2.5.64 Before DOCTYPE system identifier state tsDOCTYPESystemIdentifierDoubleQuotedState: DoDOCTYPESystemIdentifierDoubleQuotedState; //13.2.5.65 DOCTYPE system identifier (double-quoted) state tsDOCTYPESystemIdentifierSingleQuotedState: DoDOCTYPESystemIdentifierSingleQuotedState; //13.2.5.66 DOCTYPE system identifier (single-quoted) state tsAfterDOCTYPESystemIdentifierState: DoAfterDOCTYPESystemIdentifierState; //13.2.5.67 After DOCTYPE system identifier state tsBogusDOCTYPEState: DoBogusDOCTYPEState; //13.2.5.68 Bogus DOCTYPE state tsCDATASectionState: DoCDATASectionState; //13.2.5.69 CDATA section state tsCDATASectionBracketState: DoCDATASectionBracketState; //13.2.5.70 CDATA section bracket state tsCDATASectionEndState: DoCDATASectionEndState; //13.2.5.71 CDATA section end state tsCharacterReferenceState: DoCharacterReferenceState; //13.2.5.72 Character reference state tsNamedCharacterReferenceState: DoNamedCharacterReferenceState; //13.2.5.73 Named character reference state tsAmbiguousAmpersandState: DoAmbiguousAmpersandState; //13.2.5.74 Ambiguous ampersand state tsNumericCharacterReferenceState: DoNumericCharacterReferenceState; //13.2.5.75 Numeric character reference state tsHexadecimalCharacterReferenceStartState: DoHexadecimalCharacterReferenceStartState; //13.2.5.76 Hexadecimal character reference start state tsDecimalCharacterReferenceStartState: DoDecimalCharacterReferenceStartState; //13.2.5.77 Decimal character reference start state tsHexadecimalCharacterReferenceState: DoHexadecimalCharacterReferenceState; //13.2.5.78 Hexadecimal character reference state tsDecimalCharacterReferenceState: DoDecimalCharacterReferenceState; //13.2.5.79 Decimal character reference state tsNumericCharacterReferenceEndState: DoNumericCharacterReferenceEndState; //13.2.5.80 Numeric character reference end state else //unknown state? There's no way out. AddParseError('Unknown-parser-state-'+TypInfo.GetEnumName(TypeInfo(TTokenizerState), Ord(FState2))); Break; end; end; end; procedure THtmlTokenizer.DoDataState; var ch: UCS4Char; begin //13.2.5.1 Data state //https://html.spec.whatwg.org/multipage/parsing.html#data-state ch := Consume; //consume the next input character case ch of $0026: //U+0026 AMPERSAND (&) begin SetReturnState(tsDataState); SetState(tsCharacterReferenceState); end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsTagOpenState); end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); EmitCharacter(FCurrentInputCharacter); end; UEOF: EmitEndOfFileToken; else EmitCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoRCDATAState; var ch: UCS4Char; begin //13.2.5.2 RCDATA state //https://html.spec.whatwg.org/multipage/parsing.html#rcdata-state ch := Consume; //consume the next input character case ch of $0026: //U+0026 AMPERSAND (&) begin SetReturnState(tsRCDATAState); SetState(tsCharacterReferenceState); end; $003C: SetReturnState(tsRCDATALessThanSignState); //U+003C LESS-THAN SIGN $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); EmitCharacter($FFFD); end; UEOF: EmitEndOfFileToken; else EmitCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoRawTextState; var ch: UCS4Char; begin //13.2.5.3 RAWTEXT state //https://html.spec.whatwg.org/multipage/parsing.html#rawtext-state ch := Consume; //consume the next input character case ch of Ord('<'): SetState(tsRawTextLessThanSignState); $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); EmitCharacter($0000FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: EmitEndOfFileToken; else EmitCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoScriptDataState; var ch: UCS4Char; begin //13.2.5.4 Script data state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-state ch := Consume; //consume the next input character case ch of $003C: SetState(tsScriptDataLessThanSignState); //U+003C LESS-THAN SIGN (<) $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); EmitCharacter($0000FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: EmitEndOfFileToken; else EmitCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoPlaintextState; var ch: UCS4Char; begin //13.2.5.5 PLAINTEXT state //https://html.spec.whatwg.org/multipage/parsing.html#plaintext-state ch := Consume; //consume the next input character case ch of $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); EmitCharacter($0000FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: EmitEndOfFileToken; else EmitCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoTagOpenState; var ch: UCS4Char; begin //13.2.5.6 Tag open state //https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state ch := Consume; //consume the next input character if ch = Ord('!') then //U+0021 EXCLAMATION MARK (!) begin SetState(tsMarkupDeclarationOpenState); //Switch to the markup declaration open state. end else if ch = Ord('/') then //U+002F SOLIDUS (/) begin SetState(tsEndTagOpenState); //Switch to the end tag open state. end else if ch in asciiAlpha then begin FCurrentToken := TStartTagToken.Create; //Create a new start tag token, set its tag name to the empty string Reconsume(tsTagNameState); //Reconsume in the tag name state. end else if ch = Ord('?') then //U+003F QUESTION MARK (?) begin AddParseError('unexpected-question-mark-instead-of-tag-name'); //This is an unexpected-question-mark-instead-of-tag-name parse error FCurrentToken := TCommentToken.Create; //Create a comment token whose data is the empty string. Reconsume(tsBogusCommentState); //Reconsume in the bogus comment state. end else if ch = UEOF then begin AddParseError('eof-before-tag-name'); //This is an eof-before-tag-name parse error. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter(UEOF); //and an end-of-file token. end else begin AddParseError('invalid-first-character-of-tag-name'); //This is an eof-before-tag-name parse error. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token Reconsume(tsDataState); //Reconsume in the data state. end; end; procedure THtmlTokenizer.DoEndTagOpenState; var ch: UCS4Char; begin //13.2.5.7 End tag open state //https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state ch := Consume; //consume the next input character if ch in asciiAlpha then begin FCurrentToken := TEndTagToken.Create; //Create a new end tag token, set its tag name to the empty string. Reconsume(tsTagNameState); //Reconsume in the tag name state. end else if ch = Ord('>') then //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-end-tag-name'); SetState(tsDataState); end else if ch = UEOF then begin AddParseError('eof-before-tag-name'); //This is an eof-before-tag-name parse error. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token, EmitCharacter($002F); //a U+002F SOLIDUS character token EmitEndOfFileToken; //and an end-of-file token end else begin AddParseError('invalid-first-character-of-tag-name'); //This is an invalid-first-character-of-tag-name parse error. FCurrentToken := TCommentToken.Create; //Create a comment token whose data is the empty string. Reconsume(tsBogusCommentState); //Reconsume in the bogus comment state. end; end; procedure THtmlTokenizer.DoTagNameState; var ch: UCS4Char; begin //13.2.5.8 Tag name state //https://html.spec.whatwg.org/multipage/parsing.html#tag-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE SetState(tsBeforeAttributeNameState); //Switch to the before attribute name state. end else if ch = $002F then //U+002F SOLIDUS (/) begin SetState(tsSelfClosingStartTagState); //Switch to the self-closing start tag state. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end else if ch in asciiUpperAlpha then begin //Append the lowercase version of the current input character (add 0x0020 to the character's code point) //to the current tag token's tag name. CurrentTagToken.AppendCharacter(ch + $0020); end else if ch = $0000 then //U+0000 NULL begin AddParseError('unexpected-null-character'); CurrentTagToken.AppendCharacter($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current tag token's tag name. end else if ch = UEOF then begin AddParseError('eof-in-tag'); EmitEndOfFileToken; //Emit an end-of-file token. end else begin CurrentTagToken.AppendCharacter(FCurrentInputCharacter); //Append the current input character to the current tag token's tag name. end; end; procedure THtmlTokenizer.DoRCDATALessThanSignState; var ch: UCS4Char; begin //13.2.5.9 RCDATA less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#rcdata-less-than-sign-state ch := Consume; //consume the next input character case ch of $002F: //U+002F SOLIDUS (/) begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. SetState(tsRCDATAEndTagOpenState); //Switch to the RCDATA end tag open state. end; else EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. Reconsume(tsRCDATAState); //Reconsume in the RCDATA state. end; end; procedure THtmlTokenizer.DoRCDATAEndTagOpenState; var ch: UCS4Char; begin //13.2.5.10 RCDATA end tag open state //https://html.spec.whatwg.org/multipage/parsing.html#rcdata-end-tag-open-state ch := Consume; //consume the next input character if ch in asciiAlpha then begin FCurrentToken := TEndTagToken.Create; //Create a new end tag token //set its tag name to the empty string. Reconsume(tsRCDATAEndTagNameState); //Reconsume in the RCDATA end tag name state. end else begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter($002F); //and a U+002F SOLIDUS character token. Reconsume(tsRCDATAState); //Reconsume in the RCDATA state. end; end; procedure THtmlTokenizer.DoRCDATAEndTagNameState; var ch: UCS4Char; procedure AnythingElse; var i: Integer; begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token, EmitCharacter($002F); //a U+002F SOLIDUS character token, //and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). for i := 0 to Length(FTemporaryBuffer)-1 do EmitCharacter(FTemporaryBuffer[i]); Reconsume(tsRCDATAState); //Reconsume in the RCDATA state. end; begin //13.2.5.11 RCDATA end tag name state //https://html.spec.whatwg.org/multipage/parsing.html#rcdata-end-tag-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsBeforeAttributeNameState) //then switch to the before attribute name state. else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch = $002F then //U+002F SOLIDUS (/) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsSelfClosingStartTagState) //then switch to the self-closing start tag state. else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then begin SetState(tsDataState); //then switch to the data state EmitCurrentTagToken; //and emit the current tag token. end else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch in asciiUpperAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else if ch in asciiLowerAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter); //Append the current input character to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else AnythingElse; end; procedure THtmlTokenizer.DoRAWTEXTLessThanSignState; var ch: UCS4Char; begin //13.2.5.12 RAWTEXT less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#rawtext-less-than-sign-state ch := Consume; //consume the next input character case ch of $002F: //U+002F SOLIDUS (/) begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. SetState(tsRAWTEXTEndTagOpenState); //Switch to the RAWTEXT end tag open state. end; else EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. Reconsume(tsRAWTEXTState); //Reconsume in the RAWTEXT state. end; end; procedure THtmlTokenizer.DoRAWTEXTEndTagOpenState; var ch: UCS4Char; begin //13.2.5.13 RAWTEXT end tag open state //https://html.spec.whatwg.org/multipage/parsing.html#rawtext-end-tag-open-state ch := Consume; //consume the next input character if ch in asciiAlpha then begin FCurrentToken := TEndTagToken.Create; //Create a new end tag token, //set its tag name to the empty string. Reconsume(tsRAWTEXTEndTagNameState); //Reconsume in the RAWTEXT end tag name state. end else begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter($002F); //and a U+002F SOLIDUS character token. Reconsume(tsRAWTEXTState); //Reconsume in the RAWTEXT state. end; end; procedure THtmlTokenizer.DoRAWTEXTEndTagNameState; var ch: UCS4Char; procedure AnythingElse; var i: Integer; begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token, EmitCharacter($002F); //a U+002F SOLIDUS character token, //and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). for i := 0 to Length(FTemporaryBuffer)-1 do EmitCharacter(FTemporaryBuffer[i]); Reconsume(tsRAWTEXTState); //Reconsume in the RAWTEXT state. end; begin //13.2.5.14 RAWTEXT end tag name state //https://html.spec.whatwg.org/multipage/parsing.html#rawtext-end-tag-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsBeforeAttributeNameState) //switch to the before attribute name state. else AnythingElse; // treat it as per the "anything else" entry below. end else if ch = $002F then //U+002F SOLIDUS (/) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsSelfClosingStartTagState) //switch to the self-closing start tag state. else AnythingElse; // treat it as per the "anything else" entry below. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then begin SetState(tsDataState); //switch to the data state EmitCurrentTagToken; //and emit the current tag token. end else AnythingElse; // treat it as per the "anything else" entry below. end else if ch in asciiUpperAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else if ch in asciiLowerAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter); //Append the current input character to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else AnythingElse; end; procedure THtmlTokenizer.DoScriptDataLessThanSignState; var ch: UCS4Char; begin //13.2.5.15 Script data less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-less-than-sign-state ch := Consume; //consume the next input character if ch = $002F then //U+002F SOLIDUS (/) begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. SetState(tsScriptDataEndTagOpenState); //Switch to the script data end tag open state. end else if ch = $0021 then //U+0021 EXCLAMATION MARK (!) begin SetState(tsScriptDataEscapeStartState); //Switch to the script data escape start state. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter($0021); //and a U+0021 EXCLAMATION MARK character token. end else begin EmitCharacter($002C); //Emit a U+003C LESS-THAN SIGN character token. Reconsume(tsScriptDataState); //Reconsume in the script data state. end; end; procedure THtmlTokenizer.DoScriptDataEndTagOpenState; var ch: UCS4Char; token: TEndTagToken; begin //13.2.5.16 Script data end tag open state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-end-tag-open-state ch := Consume; //consume the next input character if ch in asciiAlpha then begin token := TEndTagToken.Create; //Create a new end tag token //token.TagName := ''; //set its tag name to the empty string FCurrentToken := token; Reconsume(tsScriptDataEndTagNameState); //Reconsume in the script data end tag name state. end else begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter($002F); //and a U+002F SOLIDUS character token. Reconsume(tsScriptDataState); //Reconsume in the script data state. end; end; procedure THtmlTokenizer.DoScriptDataEndTagNameState; var ch: UCS4Char; procedure AnythingElse; var i: Integer; begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token, EmitCharacter($002F); //a U+002F SOLIDUS character token, //and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). for i := 0 to Length(FTemporaryBuffer)-1 do EmitCharacter(FTemporaryBuffer[i]); Reconsume(tsScriptDataState); //Reconsume in the script data state. end; begin //13.2.5.17 Script data end tag name state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-end-tag-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsBeforeAttributeNameState) //switch to the before attribute name state. else AnythingElse; //treat it as per the "anything else" entry below. end else if ch = $002F then //U+002F SOLIDUS (/) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsSelfClosingStartTagState) //switch to the self-closing start tag state. else AnythingElse; //treat it as per the "anything else" entry below. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then begin SetState(tsDataState); //switch to the data state EmitCurrentTagToken; //and emit the current tag token. end else AnythingElse; //treat it as per the "anything else" entry below. end else if ch in asciiUpperAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else if ch in asciiLowerAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter); //Append the current input character to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else AnythingElse; end; procedure THtmlTokenizer.DoScriptDataEscapeStartState; var ch: UCS4Char; begin //13.2.5.18 Script data escape start state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataEscapeStartDashState); //Switch to the script data escape start dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; else Reconsume(tsScriptDataState); //Reconsume in the script data state. end; end; procedure THtmlTokenizer.DoScriptDataEscapeStartDashState; var ch: UCS4Char; begin //13.2.5.19 Script data escape start dash state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escape-start-dash-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataEscapedDashDashState); //Switch to the script data escaped dash dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; else Reconsume(tsScriptDataState); //Reconsume in the script data state. end; end; procedure THtmlTokenizer.DoScriptDataEscapedState; var ch: UCS4Char; begin //13.2.5.20 Script data escaped state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataEscapedDashState); //Switch to the script data escaped dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataEscapedLessThanSignState); // Switch to the script data escaped less-than sign state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: //EOF begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataEscapedDashState; var ch: UCS4Char; begin //13.2.5.21 Script data escaped dash state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-dash-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataEscapedDashDashState); //Switch to the script data escaped dash dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataEscapedLessThanSignState); //Switch to the script data escaped less-than sign state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. SetState(tsScriptDataEscapedState); //Switch to the script data escaped state. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else //Switch to the script data escaped state. //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataEscapedDashDashState; var ch: UCS4Char; begin //13.2.5.22 Script data escaped dash dash state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-dash-dash-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataEscapedLessThanSignState); //Switch to the script data escaped less-than sign state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsScriptDataState); //Switch to the script data state. EmitCharacter($003E); //Emit a U+003E GREATER-THAN SIGN character token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. SetState(tsScriptDataEscapedState); //Switch to the script data escaped state. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: //EOF begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else SetState(tsScriptDataEscapedState); //Switch to the script data escaped state. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataEscapedLessThanSignState; var ch: UCS4Char; begin //13.2.5.23 Script data escaped less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-less-than-sign-state ch := Consume; //consume the next input character if ch = $002F then //U+002F SOLIDUS (/) begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. SetState(tsScriptDataEscapedEndTagOpenState); //Switch to the script data escaped end tag open state. end else if ch in asciiAlpha then begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. Reconsume(tsScriptDataDoubleEscapeStartState); //Reconsume in the script data double escape start state. end else begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. Reconsume(tsScriptDataEscapedState); //Reconsume in the script data escaped state. end; end; procedure THtmlTokenizer.DoScriptDataEscapedEndTagOpenState; var ch: UCS4Char; begin //13.2.5.24 Script data escaped end tag open state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-end-tag-open-state ch := Consume; //consume the next input character if ch in asciiAlpha then begin FCurrentToken := TEndTagToken.Create; //Create a new end tag token, //set its tag name to the empty string. Reconsume(tsScriptDataEscapedEndTagNameState); //Reconsume in the script data escaped end tag name state. end else begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token EmitCharacter($002F); //and a U+002F SOLIDUS character token. Reconsume(tsScriptDataEscapedState); //Reconsume in the script data escaped state. end; end; procedure THtmlTokenizer.DoScriptDataEscapedEndTagNameState; var ch: UCS4Char; procedure AnythingElse; var i: Integer; begin EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token, EmitCharacter($002F); //a U+002F SOLIDUS character token, //and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). for i := 0 to Length(FTemporaryBuffer)-1 do EmitCharacter(FTemporaryBuffer[i]); Reconsume(tsScriptDataEscapedState); //Reconsume in the script data escaped state. end; begin //13.2.5.25 Script data escaped end tag name state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-end-tag-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsBeforeAttributeNameState) //then switch to the before attribute name state. else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch = $002F then //U+002F SOLIDUS (/) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then SetState(tsSelfClosingStartTagState) //then switch to the self-closing start tag state. else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin //If the current end tag token is an appropriate end tag token, if IsAppropriateEndTag(FCurrentToken as TEndTagToken) then begin SetState(tsDataState); //then switch to the data state EmitCurrentTagToken; //and emit the current tag token. end else AnythingElse; //Otherwise, treat it as per the "anything else" entry below. end else if ch in asciiUpperAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else if ch in asciiLowerAlpha then begin (FCurrentToken as TTagToken).AppendCharacter(FCurrentInputCharacter); //Append the current input character to the current tag token's tag name. AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. end else AnythingElse; end; procedure THtmlTokenizer.DoScriptDataDoubleEscapeStartState; var ch: UCS4Char; begin //13.2.5.26 Script data double escape start state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escape-start-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020, $002F, $003E] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //U+002F SOLIDUS (/) //U+003E GREATER-THAN SIGN (>) //If the temporary buffer is the string "script" if TemporaryBufferIs('script') then SetState(tsScriptDataDoubleEscapedState) //then switch to the script data double escaped state. else begin SetState(tsScriptDataEscapedState); //Otherwise, switch to the script data escaped state. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end else if ch in asciiUpperAlpha then begin AppendToTemporaryBuffer(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the temporary buffer. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end else if ch in asciiLowerAlpha then begin AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end else Reconsume(tsScriptDataEscapedState); //Reconsume in the script data escaped state. end; procedure THtmlTokenizer.DoScriptDataDoubleEscapedState; var ch: UCS4Char; begin //13.2.5.27 Script data double escaped state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataDoubleEscapedDashState); //Switch to the script data double escaped dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataDoubleEscapedLessThanSignState); //Switch to the script data double escaped less-than sign state. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataDoubleEscapedDashState; var ch: UCS4Char; begin //13.2.5.28 Script data double escaped dash state // https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-dash-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsScriptDataDoubleEscapedDashDashState); //Switch to the script data double escaped dash dash state. EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataDoubleEscapedLessThanSignState); //Switch to the script data double escaped less-than sign state. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. SetState(tsScriptDataDoubleEscapedState); //Switch to the script data double escaped state. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else SetState(tsScriptDataDoubleEscapedState); //Switch to the script data double escaped state. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataDoubleEscapedDashDashState; var ch: UCS4Char; begin //13.2.5.29 Script data double escaped dash dash state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-dash-dash-state ch := Consume; //consume the next input character case ch of $002D: //U+002D HYPHEN-MINUS (-) begin EmitCharacter($002D); //Emit a U+002D HYPHEN-MINUS character token. end; $003C: //U+003C LESS-THAN SIGN (<) begin SetState(tsScriptDataDoubleEscapedLessThanSignState);//Switch to the script data double escaped less-than sign state. EmitCharacter($003C); //Emit a U+003C LESS-THAN SIGN character token. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsScriptDataState); //Switch to the script data state. EmitCharacter($003E); //Emit a U+003E GREATER-THAN SIGN character token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. SetState(tsScriptDataDoubleEscapedState); //Switch to the script data double escaped state. EmitCharacter($FFFD); //Emit a U+FFFD REPLACEMENT CHARACTER character token. end; UEOF: begin AddParseError('eof-in-script-html-comment-like-text'); //This is an eof-in-script-html-comment-like-text parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else SetState(tsScriptDataDoubleEscapedState); //Switch to the script data double escaped state. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoScriptDataDoubleEscapedLessThanSignState; var ch: UCS4Char; begin //13.2.5.30 Script data double escaped less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-less-than-sign-state ch := Consume; //consume the next input character case ch of $002F: //U+002F SOLIDUS (/) begin SetLength(FTemporaryBuffer, 0); //Set the temporary buffer to the empty string. SetState(tsScriptDataDoubleEscapeEndState); //Switch to the script data double escape end state. EmitCharacter($002F); //Emit a U+002F SOLIDUS character token. end; else Reconsume(tsScriptDataDoubleEscapedState); //Reconsume in the script data double escaped state. end; end; procedure THtmlTokenizer.DoScriptDataDoubleEscapeEndState; var ch: UCS4Char; begin //13.2.5.31 Script data double escape end state //https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escape-end-stat ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020, $002F, $003E] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //U+002F SOLIDUS (/) //U+003E GREATER-THAN SIGN (>) //If the temporary buffer is the string "script" if TemporaryBufferIs('script') then SetState(tsScriptDataEscapedState) //then switch to the script data escaped state. else begin SetState(tsScriptDataDoubleEscapedState); //Otherwise, switch to the script data double escaped state. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end; end else if ch in asciiUpperAlpha then begin AppendToTemporaryBuffer(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the temporary buffer. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end else if ch in asciiLowerAlpha then begin AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. EmitCharacter(CurrentInputCharacter); //Emit the current input character as a character token. end else Reconsume(tsScriptDataDoubleEscapedState); //Reconsume in the script data escaped state. end; procedure THtmlTokenizer.DoBeforeAttributeNameState; var ch: UCS4Char; begin //13.2.5.32 Before attribute name state //https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state ch := Consume; //Consume the next input character case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $002F, //U+002F SOLIDUS (/) $003E, //U+003E GREATER-THAN SIGN (>) UEOF: begin Reconsume(tsAfterAttributeNameState); //Reconsume in the after attribute name state. end; $003D: //U+003D EQUALS SIGN (=) begin AddParseError('unexpected-equals-sign-before-attribute-name'); //This is an unexpected-equals-sign-before-attribute-name parse error. CurrentTagToken.NewAttribute; //Start a new attribute in the current tag token. CurrentTagToken.CurrentAttributeName := UCS4CharToUnicodeString(FCurrentInputCharacter); //Set that attribute's name to the current input character, CurrentTagToken.CurrentAttributeValue := ''; //and its value to the empty string. SetState(tsAttributeNameState); //Switch to the attribute name state. end; else CurrentTagToken.NewAttribute; //Start a new attribute in the current tag token. CurrentTagToken.CurrentAttributeName := ''; // Set that attribute name and value to the empty string. CurrentTagToken.CurrentAttributeValue := ''; // (and value!) Reconsume(tsAttributeNameState); //Reconsume in the attribute name state. end; end; procedure THtmlTokenizer.DoAttributeNameState; var ch: UCS4Char; procedure AnythingElse; begin AppendToCurrentAttributeName(FCurrentInputCharacter); //Append the current input character to the current attribute's name. end; begin //13.2.5.33 Attribute name state //https://html.spec.whatwg.org/multipage/parsing.html#attribute-name-state ch := Consume; //Consume the next input character if (ch in [$0009, $000A, $000C, $0020, $002F, $003E]) or (ch = UEOF) then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //U+002F SOLIDUS (/) //U+003E GREATER-THAN SIGN (>) //EOF CurrentTagToken.FinalizeAttributeName; Reconsume(tsAfterAttributeNameState); //Reconsume in the after attribute name state. end else if ch = $003D then //U+003D EQUALS SIGN (=) begin CurrentTagToken.FinalizeAttributeName; SetState(tsBeforeAttributeValueState); //Switch to the before attribute value state. end else if ch in asciiUpperAlpha then begin AppendToCurrentAttributeName(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current attribute's name. end else if ch = $0000 then //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. AppendToCurrentAttributeName($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's name. end else if ch in [$0020, $0027, $003C] then begin //U+0022 QUOTATION MARK (") //U+0027 APOSTROPHE (') //U+003C LESS-THAN SIGN (<) AddParseError('unexpected-character-in-attribute-name'); //This is an unexpected-character-in-attribute-name parse error. AnythingElse; //Treat it as per the "anything else" entry below. end else AnythingElse; end; procedure THtmlTokenizer.DoAfterAttributeNameState; var ch: UCS4Char; begin //13.2.5.34 After attribute name state //https://html.spec.whatwg.org/multipage/parsing.html#after-attribute-name-state ch := Consume; //Consume the next input character case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $002F: //U+002F SOLIDUS (/) begin SetState(tsSelfClosingStartTagState); //Switch to the self-closing start tag state. end; $003D: //U+003D EQUALS SIGN (=) begin SetState(tsBeforeAttributeValueState); //Switch to the before attribute value state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else CurrentTagToken.NewAttribute; //Start a new attribute in the current tag token. CurrentTagToken.CurrentAttributeName := ''; //Set that attribute name and value to the empty string. CurrentTagToken.CurrentAttributeValue := ''; //(and value!) Reconsume(tsAttributeNameState); //Reconsume in the attribute name state. end; end; procedure THtmlTokenizer.DoBeforeAttributeValueState; var ch: UCS4Char; begin //13.2.5.35 Before attribute value state //https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-value-state ch := Consume; //Consume the next input character case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $0022: //U+0022 QUOTATION MARK (") begin SetState(tsAttributeValueDoubleQuotedState); //Switch to the attribute value (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin SetState(tsAttributeValueSingleQuotedState); //Switch to the attribute value (single-quoted) state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-attribute-value'); //This is a missing-attribute-value parse error. SetState(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end; else Reconsume(tsAttributeValueUnquotedState); //Reconsume in the attribute value (unquoted) state. end; end; procedure THtmlTokenizer.DoAttributeValueDoubleQuotedState; var ch: UCS4Char; begin //13.2.5.36 Attribute value (double-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state ch := Consume; //Consume the next input character: case ch of $0022: //U+0022 QUOTATION MARK (") begin SetState(tsAfterAttributeValueQuotedState); //Switch to the after attribute value (quoted) state. end; $0026: //U+0026 AMPERSAND (&) begin SetReturnState(tsAttributeValueDoubleQuotedState); //Set the return state to the attribute value (double-quoted) state. SetState(tsCharacterReferenceState); //Switch to the character reference state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. AppendToCurrentAttributeValue($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentAttributeValue(FCurrentInputCharacter); //Append the current input character to the current attribute's value. end; end; procedure THtmlTokenizer.DoAttributeValueSingleQuotedState; var ch: UCS4Char; begin //13.2.5.37 Attribute value (single-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(single-quoted)-state ch := Consume; // Consume the next input character: case ch of $0027: //U+0027 APOSTROPHE (') begin SetState(tsAfterattributeValueQuotedState); //Switch to the after attribute value (quoted) state. end; $0026: //U+0026 AMPERSAND (&) begin SetReturnState(tsAttributeValueSingleQuotedState); //Set the return state to the attribute value (single-quoted) state. SetState(tsCharacterReferenceState); //Switch to the character reference state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. AppendToCurrentAttributeValue($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentAttributeValue(FCurrentInputCharacter); //Append the current input character to the current attribute's value. end; end; procedure THtmlTokenizer.DoAttributeValueUnquotedState; var ch: UCS4Char; begin //13.2.5.38 Attribute value (unquoted) state //https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(unquoted)-state ch := Consume; // Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin SetState(tsBeforeAttributeNameState); //Switch to the before attribute name state. end; $0026: //U+0026 AMPERSAND (&) begin SetReturnState(tsAttributeValueUnquotedState); //Set the return state to the attribute value (unquoted) state. SetState(tsCharacterReferenceState); //Switch to the character reference state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetSTate(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. AppendToCurrentAttributeValue($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value. end; $0022, //U+0022 QUOTATION MARK (") $0027, //U+0027 APOSTROPHE (') $003C, //U+003C LESS-THAN SIGN (<) $003D, //U+003D EQUALS SIGN (=) $0060: //U+0060 GRAVE ACCENT (`) begin AddParseError('unexpected-character-in-unquoted-attribute-value'); //This is an unexpected-character-in-unquoted-attribute-value parse error. AppendToCurrentAttributeValue(FCurrentInputCharacter); //Treat it as per the "anything else" entry below. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentAttributeValue(FCurrentInputCharacter); //Append the current input character to the current attribute's value. end; end; procedure THtmlTokenizer.DoAfterAttributeValueQuotedState; var ch: UCS4Char; begin //13.2.5.39 After attribute value (quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#after-attribute-value-(quoted)-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin SetState(tsBeforeAttributeNameState); //Switch to the before attribute name state. end; $002F: //U+002F SOLIDUS (/) begin SetState(tsSelfClosingStartTagState); //Switch to the self-closing start tag state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-whitespace-between-attributes'); //This is a missing-whitespace-between-attributes parse error. Reconsume(tsBeforeAttributeNameState); //Reconsume in the before attribute name state. end; end; procedure THtmlTokenizer.DoSelfClosingStartTagState; var ch: UCS4Char; begin //13.2.5.40 Self-closing start tag state //https://html.spec.whatwg.org/multipage/parsing.html#self-closing-start-tag-state ch := Consume; case ch of $003E: //U+003E GREATER-THAN SIGN (>) begin CurrentTagToken.SelfClosing := True; //Set the self-closing flag of the current tag token. SetState(tsDataState); //Switch to the data state. EmitCurrentTagToken; //Emit the current tag token. end; UEOF: begin AddParseError('eof-in-tag'); //This is an eof-in-tag parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('unexpected-solidus-in-tag'); //This is an unexpected-solidus-in-tag parse error. Reconsume(tsBeforeAttributeNameState); //Reconsume in the before attribute name state. end; end; procedure THtmlTokenizer.DoBogusCommentState; var ch: UCS4Char; begin //13.2.5.41 Bogus comment state //https://html.spec.whatwg.org/multipage/parsing.html#bogus-comment-state ch := Consume; //Consume the next input character: case ch of $003E: // U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentCommentToken; //Emit the current comment token. end; UEOF: begin EmitCurrentCommentToken; //Emit the comment. EmitEndOfFileToken; //Emit an end-of-file token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. (FCurrentToken as TCommentToken).AppendCharacter($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data. end; else //Append the current input character to the comment token's data. (FCurrentToken as TCommentToken).AppendCharacter(FCurrentInputCharacter); end; end; procedure THtmlTokenizer.DoMarkupDeclarationOpenState; var newCommentToken: TCommentToken; begin //13.2.5.42 Markup declaration open state //https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state if NextFewCharacters('--', True, False) then //Two U+002D HYPHEN-MINUS characters (-) begin //Consume those two characters, Consume; //"-" Consume; //"-" FCurrentToken := TCommentToken.Create; //create a comment token whose data is the empty string//create a comment token whose data is the empty string, SetState(tsCommentStartState); //and switch to the comment start state. end else if NextFewCharacters('DOCTYPE', False, False) then begin //ASCII case-insensitive match for the word "DOCTYPE" //Consume those characters Consume; //D Consume; //O Consume; //C Consume; //T Consume; //Y Consume; //P Consume; //E SetState(tsDOCTYPEState); //and switch to the DOCTYPE state. end else if NextFewCharacters('[CDATA[', True, False) then begin //The string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after) //Consume those characters. Consume; //[ Consume; //C Consume; //D Consume; //A Consume; //T Consume; //A Consume; //[ //TODO: If there is an [adjusted current node] and it is not an element in the [HTML namespace], //then switch to the [CDATA section state]. { if (FAdjustedCurrentNode <> nil) and (FAdjustedCurrentNode.Namespace <> 'HTML') then begin SetState(tsCDATASectionState); Exit; end;} AddParseError('cdata-in-html-content'); //Otherwise, this is a cdata-in-html-content parse error. //Create a comment token whose data is the "[CDATA[" string. newCommentToken := TCommentToken.Create; newCommentToken.AppendCharacter(Ord('[')); newCommentToken.AppendCharacter(Ord('C')); newCommentToken.AppendCharacter(Ord('D')); newCommentToken.AppendCharacter(Ord('A')); newCommentToken.AppendCharacter(Ord('T')); newCommentToken.AppendCharacter(Ord('A')); newCommentToken.AppendCharacter(Ord('[')); FCurrentToken := newCommentToken; SetState(tsBogusCommentState); //Switch to the bogus comment state. end else begin AddParseError('incorrectly-opened-comment'); //This is an incorrectly-opened-comment parse error. FCurrentToken := TCommentToken.Create; //Create a comment token whose data is the empty string. SetState(tsBogusCommentState); //Switch to the bogus comment state (don't consume anything in the current state). end; end; procedure THtmlTokenizer.DoCommentStartState; var ch: UCS4Char; begin //13.2.5.43 Comment start state //https://html.spec.whatwg.org/multipage/parsing.html#comment-start-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentStartDashState); //Switch to the comment start dash state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-closing-of-empty-comment'); //This is an abrupt-closing-of-empty-comment parse error. SetState(tsDataState); //Switch to the data state. EmitCurrentCommentToken; //Emit the current comment token. end; else Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentStartDashState; var ch: UCS4Char; begin //13.2.5.44 Comment start dash state //https://html.spec.whatwg.org/multipage/parsing.html#comment-start-dash-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentEndState); //Switch to the comment end state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-closing-of-empty-comment'); //This is an abrupt-closing-of-empty-comment parse error. SetState(tsDataState); //Switch to the data state. EmitCurrentCommentToken; //Emit the current comment token. end; UEOF: begin AddParseError('eof-in-comment'); //This is an eof-in-comment parse error. EmitCurrentCommentToken; //Emit the current comment token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentCommentData($002D); //Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentState; var ch: UCS4Char; begin //13.2.5.45 Comment state //https://html.spec.whatwg.org/multipage/parsing.html#comment-state ch := Consume; // Consume the next input character: case ch of $003C: //U+003C LESS-THAN SIGN (<) begin AppendToCurrentCommentData(FCurrentInputCharacter); //Append the current input character to the comment token's data. SetState(tsCommentLessThanSignState); //Switch to the comment less-than sign state. end; $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentEndDashState); //Switch to the comment end dash state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. AppendToCurrentCommentData($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data. end; UEOF: begin AddParseError('eof-in-comment'); //This is an eof-in-comment parse error. EmitCurrentCommentToken; //Emit the current comment token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentCommentData(FCurrentInputCharacter); //Append the current input character to the comment token's data. end; end; procedure THtmlTokenizer.DoCommentLessThanSignState; var ch: UCS4Char; begin //13.2.5.46 Comment less-than sign state //https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-state ch := Consume; // Consume the next input character: case ch of $0021: //U+0021 EXCLAMATION MARK (!) begin AppendToCurrentCommentData(FCurrentInputCharacter); //Append the current input character to the comment token's data. SetState(tsCommentLessThanSignBangState); //Switch to the comment less-than sign bang state. end; $003C: //U+003C LESS-THAN SIGN (<) begin AppendToCurrentCommentData(FCurrentInputCharacter); //Append the current input character to the comment token's data. end; else Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentLessThanSignBangState; var ch: UCS4Char; begin //13.2.5.47 Comment less-than sign bang state //https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentLessThanSignBangDashState); //Switch to the comment less-than sign bang dash state. end; else Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentLessThanSignBangDashState; var ch: UCS4Char; begin //13.2.5.48 Comment less-than sign bang dash state //https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-dash-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentLessThanSignBangDashDashState); //Switch to the comment less-than sign bang dash dash state. end; else Reconsume(tsCommentEndDashState); //Reconsume in the comment end dash state. end; end; procedure THtmlTokenizer.DoCommentLessThanSignBangDashDashState; var ch: UCS4Char; begin //13.2.5.49 Comment less-than sign bang dash dash state //https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-dash-dash-state ch := Consume; // Consume the next input character: case ch of $003E, //U+003E GREATER-THAN SIGN (>) UEOF: begin Reconsume(tsCommentEndState); //Reconsume in the comment end state. end; else AddParseError('nested-comment'); //This is a nested-comment parse error. Reconsume(tsCommentEndState); //Reconsume in the comment end state. end; end; procedure THtmlTokenizer.DoCommentEndDashState; var ch: UCS4Char; begin //13.2.5.50 Comment end dash state //https://html.spec.whatwg.org/multipage/parsing.html#comment-end-dash-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin SetState(tsCommentEndState); //Switch to the comment end state. end; UEOF: begin AddParseError('eof-in-comment'); //This is an eof-in-comment parse error. EmitCurrentCommentToken; //Emit the current comment token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentCommentData($002D); //Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentEndState; var ch: UCS4Char; begin //13.2.5.51 Comment end state //https://html.spec.whatwg.org/multipage/parsing.html#comment-end-state ch := Consume; // Consume the next input character: case ch of $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentCommentToken; //Emit the current comment token. end; $0021: //U+0021 EXCLAMATION MARK (!) begin SetState(tsCommentEndBangState); //Switch to the comment end bang state. end; $002D: //U+002D HYPHEN-MINUS (-) begin AppendToCurrentCommentData($002D); //Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. end; UEOF: begin AddParseError('eof-in-comment'); //This is an eof-in-comment parse error. EmitCurrentCommentToken; //Emit the current comment token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentCommentData($002D); //Append two U+002D HYPHEN-MINUS characters (-) to the comment token's data. AppendToCurrentCommentData($002D); //(two!) Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoCommentEndBangState; var ch: UCS4Char; begin //13.2.5.52 Comment end bang state //https://html.spec.whatwg.org/multipage/parsing.html#comment-end-bang-state ch := Consume; // Consume the next input character: case ch of $002D: //U+002D HYPHEN-MINUS (-) begin AppendToCurrentCommentData($002D); //Append two U+002D HYPHEN-MINUS characters (-) AppendToCurrentCommentData($002D); //(two!) AppendToCurrentCommentData($0021); //and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. SetState(tsCommentEndDashState); //Switch to the comment end dash state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('incorrectly-closed-comment'); //This is an incorrectly-closed-comment parse error. SetState(tsDataState); //Switch to the data state. EmitCurrentCommentToken; //Emit the current comment token. end; UEOF: begin AddParseError('eof-in-comment'); //This is an eof-in-comment parse error. EmitCurrentCommentToken; //Emit the current comment token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AppendToCurrentCommentData($002D); //Append two U+002D HYPHEN-MINUS characters (-) AppendToCurrentCommentData($002D); //(two!) AppendToCurrentCommentData($0021); //and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. Reconsume(tsCommentState); //Reconsume in the comment state. end; end; procedure THtmlTokenizer.DoDOCTYPEState; var ch: UCS4Char; token: TDocTypeToken; begin //13.2.5.53 DOCTYPE state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-state ch := Consume; //consume the next input character case ch of $0009, $000A, $000C, $0020: begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE SetState(tsBeforeDOCTYPENameState); //Switch to the before DOCTYPE name state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin Reconsume(tsBeforeDOCTYPENameState); //Reconsume in the before DOCTYPE name state. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. token := TDocTypeToken.Create; //Create a new DOCTYPE token. token.ForceQuirks := True; //Set its force-quirks flag to on. EmitToken(token); //Emit the current token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-whitespace-before-doctype-name'); //This is a missing-whitespace-before-doctype-name parse error. Reconsume(tsBeforeDOCTYPENameState); //Reconsume in the before DOCTYPE name state. end; end; procedure THtmlTokenizer.DoBeforeDOCTYPENameState; var ch: UCS4Char; token: TDocTypeToken; begin //13.2.5.54 Before DOCTYPE name state //https://html.spec.whatwg.org/multipage/parsing.html#before-doctype-name-state { QUESTION: U+003E GREATER-THAN SIGN (>) says to create a new doctype token, and then to emit the "currenttoken. Is the current token the new doctype token we just created, or is it previous current token? } ch := Consume; if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE //Ignore the character. end else if ch in asciiUpperAlpha then begin token := TDoctypeToken.Create; //Create a new DOCTYPE token. token.Name := WideChar(ch + $0020); //Set the token's name to the lowercase version of the current input character (add 0x0020 to the character's code point). FCurrentToken := token; SetState(tsDOCTYPENameState); //Switch to the DOCTYPE name state. end else if ch = $0000 then //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. token := TDocTypeToken.Create; //Create a new DOCTYPE token. token.Name := WideChar($FFFD); //Set the token's name to a U+FFFD REPLACEMENT CHARACTER character. FCurrentToken := token; SetState(tsDOCTYPENameState); //Switch to the DOCTYPE name state. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-doctype-name'); //This is a missing-doctype-name parse error. token := TDocTypeToken.Create; //Create a new DOCTYPE token. token.ForceQuirks := True; //Set its force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitToken(token); //Emit the current token. end else if ch = UEOF then //EOF begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. token := TDocTypeToken.Create; //Create a new DOCTYPE token. token.ForceQuirks := True; //Set its force-quirks flag to on. EmitToken(token); //Emit the current token. EmitEndOfFileToken; //Emit an end-of-file token. end else begin token := TDocTypeToken.Create; //Create a new DOCTYPE token. token.Name := UCS4CharToUnicodeString(FCurrentInputCharacter); //Set the token's name to the current input character. SetState(tsDOCTYPENameState); //Switch to the DOCTYPE name state. end; end; procedure THtmlTokenizer.DoDOCTYPENameState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.55 DOCTYPE name state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-name-state ch := Consume; //consume the next input character if ch in [$0009, $000A, $000C, $0020] then begin //U+0009 CHARACTER TABULATION (tab) //U+000A LINE FEED (LF) //U+000C FORM FEED (FF) //U+0020 SPACE SetState(tsAfterDOCTYPENameState); //Switch to the after DOCTYPE name state. end else if ch = $003E then //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end else if ch in asciiUpperAlpha then begin dt.AppendName(FCurrentInputCharacter + $0020); //Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current DOCTYPE token's name. end else if ch = $0000 then //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. dt.AppendName($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's name. end else if ch = UEOF then begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end else begin dt.AppendName(FCurrentInputCharacter); //Append the current input character to the current DOCTYPE token's name. end; end; procedure THtmlTokenizer.DoAfterDOCTYPENameState; var ch: UCS4Char; begin //13.2.5.56 After DOCTYPE name state //https://html.spec.whatwg.org/multipage/parsing.html#after-doctype-name-state ch := Consume; //consume the next input character case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else if NextFewCharacters('PUBLIC', False, True) then begin //If the six characters starting from the current input character //are an ASCII case-insensitive match for the word "PUBLIC", //then consume those characters //Consume; //P don't consume this; it already is the "current" character. Consume; //U Consume; //B Consume; //L Consume; //I Consume; //C SetState(tsAfterDOCTYPEPublicKeywordState); //and switch to the after DOCTYPE public keyword state. end else if NextFewCharacters('SYSTEM', False, True) then begin //if the six characters starting from the current input character //are an ASCII case-insensitive match for the word "SYSTEM", //then consume those characters Consume; //S Consume; //Y Consume; //S Consume; //T Consume; //E Consume; //M SetState(tsAfterDOCTYPESystemKeywordState); //and switch to the after DOCTYPE system keyword state. end else begin //Otherwise, AddParseError('invalid-character-sequence-after-doctype-name'); //this is an invalid-character-sequence-after-doctype-name parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; end; procedure THtmlTokenizer.DoAfterDOCTYPEPublicKeywordState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.57 After DOCTYPE public keyword state //https://html.spec.whatwg.org/multipage/parsing.html#after-doctype-public-keyword-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin SetState(tsBeforeDOCTYPEPublicIdentifierState); //Switch to the before DOCTYPE public identifier state. end; $0022: //U+0022 QUOTATION MARK (") begin AddParseError('missing-whitespace-after-doctype-public-keyword'); //This is a missing-whitespace-after-doctype-public-keyword parse error. dt.PublicIdentifier := ''; // Set the current DOCTYPE token's public identifier to the empty string (not missing), SetState(tsDOCTYPEPublicIdentifierDoubleQuotedState); //then switch to the DOCTYPE public identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin AddParseError('missing-whitespace-after-doctype-public-keyword'); //This is a missing-whitespace-after-doctype-public-keyword parse error. dt.PublicIdentifier := ''; // Set the current DOCTYPE token's public identifier to the empty string (not missing), SetState(tsDOCTYPEPublicIdentifierSingleQuotedState); //then switch to the DOCTYPE public identifier (single-quoted) state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-doctype-public-identifier'); // This is a missing-doctype-public-identifier parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; // Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-public-identifier'); //This is a missing-quote-before-doctype-public-identifier parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoBeforeDOCTYPEPublicIdentifierState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.58 Before DOCTYPE public identifier state //https://html.spec.whatwg.org/multipage/parsing.html#before-doctype-public-identifier-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $0022: //U+0022 QUOTATION MARK (") begin dt.PublicIdentifier := ''; //Set the current DOCTYPE token's public identifier to the empty string (not missing), SetState(tsDOCTYPEPublicIdentifierDoubleQuotedState); //then switch to the DOCTYPE public identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin dt.PublicIdentifier := ''; //Set the current DOCTYPE token's public identifier to the empty string (not missing), SetState(tsDOCTYPEPublicIdentifierSingleQuotedState); //then switch to the DOCTYPE public identifier (single-quoted) state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-doctype-public-identifier'); //This is a missing-doctype-public-identifier parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; // the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; // Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-public-identifier'); //This is a missing-quote-before-doctype-public-identifier parse error. (FCurrentToken as TDocTypeToken).ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoDOCTYPEPublicIdentifierDoubleQuotedState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.59 DOCTYPE public identifier (double-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-public-identifier-(double-quoted)-state ch := Consume; //Consume the next input character: case ch of $0022: //U+0022 QUOTATION MARK (") begin SetState(tsAfterDOCTYPEPublicIdentifierState); //Switch to the after DOCTYPE public identifier state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. dt.PublicIdentifier := dt.PublicIdentifier + #$FFFD; // Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-doctype-public-identifier'); //This is an abrupt-doctype-public-identifier parse error. dt.ForceQuirks := True; // Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else //Append the current input character to the current DOCTYPE token's public identifier. dt.AppendPublicIdentifier(CurrentInputCharacter); end; end; procedure THtmlTokenizer.DoDOCTYPEPublicIdentifierSingleQuotedState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.60 DOCTYPE public identifier (single-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-public-identifier-(single-quoted)-state ch := Consume; //Consume the next input character: case ch of $0027: //U+0027 APOSTROPHE (') begin SetState(tsAfterDOCTYPEPublicIdentifierState); //Switch to the after DOCTYPE public identifier state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. dt.PublicIdentifier := dt.PublicIdentifier + #$FFFD; //Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-doctype-public-identifier'); //This is an abrupt-doctype-public-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else dt.PublicIdentifier := dt.PublicIdentifier + WideChar(FCurrentInputCharacter); //Append the current input character to the current DOCTYPE token's public identifier. end; end; procedure THtmlTokenizer.DoAfterDOCTYPEPublicIdentifierState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.61 After DOCTYPE public identifier state //https://html.spec.whatwg.org/multipage/parsing.html#after-doctype-public-identifier-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin SetState(tsBetweenDOCTYPEPublicAndSystemIdentifiersState); //Switch to the between DOCTYPE public and system identifiers state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; $0022: //U+0022 QUOTATION MARK (") begin AddParseError('missing-whitespace-between-doctype-public-and-system-identifiers'); //This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierDoubleQuotedState); //then switch to the DOCTYPE system identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin AddParseError('missing-whitespace-between-doctype-public-and-system-identifiers'); //This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierSingleQuotedState); //then switch to the DOCTYPE system identifier (single-quoted) state. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; // Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-system-identifier'); //This is a missing-quote-before-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoBetweenDOCTYPEPublicAndSystemIdentifiersState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.62 Between DOCTYPE public and system identifiers state //https://html.spec.whatwg.org/multipage/parsing.html#between-doctype-public-and-system-identifiers-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; $0022: //U+0022 QUOTATION MARK (") begin dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierDoubleQuotedState); //then switch to the DOCTYPE system identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierSingleQuotedState); //then switch to the DOCTYPE system identifier (single-quoted) state. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-system-identifier'); //This is a missing-quote-before-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoAfterDOCTYPESystemKeywordState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.63 After DOCTYPE system keyword state //https://html.spec.whatwg.org/multipage/parsing.html#after-doctype-system-keyword-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin SetState(tsBeforeDOCTYPESystemIdentifierState); //Switch to the before DOCTYPE system identifier state. end; $0022: //U+0022 QUOTATION MARK (") begin AddParseError('missing-whitespace-after-doctype-system-keyword'); //This is a missing-whitespace-after-doctype-system-keyword parse error. dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierDoubleQuotedState); //switch to the DOCTYPE system identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin AddParseError('missing-whitespace-after-doctype-system-keyword'); //This is a missing-whitespace-after-doctype-system-keyword parse error. dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierSingleQuotedState); //switch to the DOCTYPE system identifier (single-quoted) state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-doctype-system-identifier'); //This is a missing-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-system-identifier'); //This is a missing-quote-before-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoBeforeDOCTYPESystemIdentifierState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.64 Before DOCTYPE system identifier state //https://html.spec.whatwg.org/multipage/parsing.html#before-doctype-system-identifier-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $0022: //U+0022 QUOTATION MARK (") begin dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierDoubleQuotedState); //switch to the DOCTYPE system identifier (double-quoted) state. end; $0027: //U+0027 APOSTROPHE (') begin dt.SystemIdentifier := ''; //Set the current DOCTYPE token's system identifier to the empty string (not missing), SetState(tsDOCTYPESystemIdentifierSingleQuotedState); //switch to the DOCTYPE system identifier (single-quoted) state. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('missing-doctype-system-identifier'); //This is a missing-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('missing-quote-before-doctype-system-identifier'); //This is a missing-quote-before-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. end; end; procedure THtmlTokenizer.DoDOCTYPESystemIdentifierDoubleQuotedState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.65 DOCTYPE system identifier (double-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-system-identifier-(double-quoted)-state ch := Consume; //Consume the next input character: case ch of $0022: //U+0022 QUOTATION MARK (") begin SetState(tsAfterDOCTYPESystemIdentifierState); //Switch to the after DOCTYPE system identifier state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. dt.SystemIdentifier := dt.SystemIdentifier + #$FFFD; // Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-doctype-system-identifier'); //This is an abrupt-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else dt.AppendSystemIdentifier(FCurrentInputCharacter); //Append the current input character to the current DOCTYPE token's system identifier. end; end; procedure THtmlTokenizer.DoDOCTYPESystemIdentifierSingleQuotedState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.66 DOCTYPE system identifier (single-quoted) state //https://html.spec.whatwg.org/multipage/parsing.html#doctype-system-identifier-(single-quoted)-state ch := Consume; //Consume the next input character: case ch of $0027: //U+0027 APOSTROPHE (') begin SetState(tsAfterDOCTYPESystemIdentifierState); //Switch to the after DOCTYPE system identifier state. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. dt.AppendSystemIdentifier($FFFD); //Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier. end; $003E: //U+003E GREATER-THAN SIGN (>) begin AddParseError('abrupt-doctype-system-identifier'); //This is an abrupt-doctype-system-identifier parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. SetState(tsDataState); //Switch to the data state. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else dt.AppendSystemIdentifier(FCurrentInputCharacter); //Append the current input character to the current DOCTYPE token's system identifier. end; end; procedure THtmlTokenizer.DoAfterDOCTYPESystemIdentifierState; var ch: UCS4Char; function dt: TDocTypeToken; begin Result := FCurrentToken as TDocTypeToken; end; begin //13.2.5.67 After DOCTYPE system identifier state //https://html.spec.whatwg.org/multipage/parsing.html#after-doctype-system-identifier-state ch := Consume; //Consume the next input character: case ch of $0009, //U+0009 CHARACTER TABULATION (tab) $000A, //U+000A LINE FEED (LF) $000C, //U+000C FORM FEED (FF) $0020: //U+0020 SPACE begin //Ignore the character. end; $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. end; UEOF: begin AddParseError('eof-in-doctype'); //This is an eof-in-doctype parse error. dt.ForceQuirks := True; //Set the current DOCTYPE token's force-quirks flag to on. EmitCurrentDoctypeToken; //Emit the current DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else AddParseError('unexpected-character-after-doctype-system-identifier'); //This is an unexpected-character-after-doctype-system-identifier parse error. Reconsume(tsBogusDOCTYPEState); //Reconsume in the bogus DOCTYPE state. //(This does not set the current DOCTYPE token's force-quirks flag to on.) end; end; procedure THtmlTokenizer.DoBogusDOCTYPEState; var ch: UCS4Char; begin //13.2.5.68 Bogus DOCTYPE state //https://html.spec.whatwg.org/multipage/parsing.html#bogus-doctype-state ch := Consume; //consume the next input character case ch of $003E: //U+003E GREATER-THAN SIGN (>) begin SetState(tsDataState); //Switch to the data state. EmitCurrentDocTypeToken; //Emit the DOCTYPE token. end; $0000: //U+0000 NULL begin AddParseError('unexpected-null-character'); //This is an unexpected-null-character parse error. //Ignore the character. end; UEOF: begin EmitCurrentDocTypeToken; //Emit the DOCTYPE token. EmitEndOfFileToken; //Emit an end-of-file token. end; else //Ignore the character. end; end; procedure THtmlTokenizer.DoCDATASectionState; var ch: UCS4Char; begin //13.2.5.69 CDATA section state //https://html.spec.whatwg.org/multipage/parsing.html#cdata-section-state ch := Consume; //Consume the next input character: case ch of $005D: //U+005D RIGHT SQUARE BRACKET (]) begin SetState(tsCDATASectionBracketState); //Switch to the CDATA section bracket state. end; UEOF: begin AddParseError('eof-in-cdata'); //This is an eof-in-cdata parse error. EmitEndOfFileToken; //Emit an end-of-file token. end; else EmitCharacter(FCurrentInputCharacter); //Emit the current input character as a character token. end; end; procedure THtmlTokenizer.DoCDATASectionBracketState; var ch: UCS4Char; begin //13.2.5.70 CDATA section bracket state //https://html.spec.whatwg.org/multipage/parsing.html#cdata-section-bracket-state ch := Consume; //Consume the next input character: case ch of $005D: //U+005D RIGHT SQUARE BRACKET (]) begin SetState(tsCDATASectionEndState); //Switch to the CDATA section end state. end; else EmitCharacter($005D); //Emit a U+005D RIGHT SQUARE BRACKET character token. Reconsume(tsCDATASectionState); //Reconsume in the CDATA section state. end; end; procedure THtmlTokenizer.DoCDATASectionEndState; var ch: UCS4Char; begin //13.2.5.71 CDATA section end state //https://html.spec.whatwg.org/multipage/parsing.html#cdata-section-end-state ch := Consume; //Consume the next input character: case ch of $005D: //U+005D RIGHT SQUARE BRACKET (]) begin EmitCharacter($005D); //Emit a U+005D RIGHT SQUARE BRACKET character token. end; $003E: //U+003E GREATER-THAN SIGN character begin SetState(tsDataState); //Switch to the data state. end; else EmitCharacter($005D); //Emit two U+005D RIGHT SQUARE BRACKET character tokens. EmitCharacter($005D); //(two!) Reconsume(tsCDataSEctionState); //Reconsume in the CDATA section state. end; end; procedure THtmlTokenizer.DoCharacterReferenceState; var ch: UCS4Char; begin //13.2.5.72 Character reference state //https://html.spec.whatwg.org/multipage/parsing.html#character-reference-state //Set the temporary buffer to the empty string. SetLength(FTemporaryBuffer, 0); AppendToTemporaryBuffer($0026); //Append a U+0026 AMPERSAND (&) character to the temporary buffer. ch := Consume; //Consume the next input character if ch in asciiAlphaNumeric then begin Reconsume(tsNamedCharacterReferenceState); //Reconsume in the named character reference state. end else if ch = $0023 then //U+0023 NUMBER SIGN (#) begin AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. SetState(tsNumericCharacterReferenceState); //Switch to the numeric character reference state. end else begin //Flush code points consumed as a character reference. FlushCodePointsConsumed; Reconsume(FReturnState2); //Reconsume in the return state. end; end; procedure THtmlTokenizer.DoNamedCharacterReferenceState; begin //13.2.5.73 Named character reference state //https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state { Consume the maximum number of characters possible, where the consumed characters are one of the identifiers in the first column of the named character references table. Append each character to the temporary buffer when it's consumed. } //TODO: this whole thing (* consumed := ''; match := False; repeat ch := Consume; if ch > $FFFF then Break; match := If there is a match If the character reference was consumed as part of an attribute, and the last character matched is not a U+003B SEMICOLON character (;), and the next input character is either a U+003D EQUALS SIGN character (=) or an ASCII alphanumeric, then, for historical reasons, flush code points consumed as a character reference and switch to the return state. Otherwise: 1. If the last character matched is not a U+003B SEMICOLON character (;), then this is a missing-semicolon-after-character-reference parse error. 2. Set the temporary buffer to the empty string. Append one or two characters corresponding to the character reference name (as given by the second column of the named character references table) to the temporary buffer. 3. Flush code points consumed as a character reference. Switch to the return state. Otherwise Flush code points consumed as a character reference. Switch to the ambiguous ampersand state. *) end; procedure THtmlTokenizer.DoAmbiguousAmpersandState; var ch: UCS4Char; begin //13.2.5.74 Ambiguous ampersand state //https://html.spec.whatwg.org/multipage/parsing.html#ambiguous-ampersand-state ch := Consume; //Consume the next input character: if ch in asciiAlphanumeric then begin //If the character reference was consumed as part of an attribute, then if IsConsumedAsPartOfAnAttribute then CurrentTagToken.CurrentAttributeValue := CurrentTagToken.CurrentAttributeValue + UCS4CharToUnicodeString(FCurrentInputCharacter) //append the current input character to the current attribute's value. else EmitCharacter(FCurrentInputCharacter); //emit the current input character as a character token. end else if ch = $003B then //U+003B SEMICOLON (;) begin AddParseError('unknown-named-character-reference'); //This is an unknown-named-character-reference parse error. Reconsume(FReturnState2); //Reconsume in the return state. end else Reconsume(FReturnState2); //Reconsume in the return state. end; procedure THtmlTokenizer.DoNumericCharacterReferenceState; var ch: UCS4Char; begin //13.2.5.75 Numeric character reference state //https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-state FCharacterReferenceCode := 0; //Set the character reference code to zero (0). ch := Consume; //Consume the next input character: case ch of $0078, //U+0078 LATIN SMALL LETTER X $0058: //U+0058 LATIN CAPITAL LETTER X begin AppendToTemporaryBuffer(FCurrentInputCharacter); //Append the current input character to the temporary buffer. SetState(tsHexadecimalCharacterReferenceStartState); //Switch to the hexadecimal character reference start state. end; else Reconsume(tsDecimalCharacterReferenceStartState); //Reconsume in the decimal character reference start state. end; end; procedure THtmlTokenizer.DoHexadecimalCharacterReferenceStartState; var ch: UCS4Char; begin //13.2.5.76 Hexadecimal character reference start state //https://html.spec.whatwg.org/multipage/parsing.html#hexadecimal-character-reference-start-state ch := Consume; //Consume the next input character: if ch in asciiHexDigit then begin Reconsume(tsHexadecimalCharacterReferenceState); //Reconsume in the hexadecimal character reference state. end else begin AddParseError('absence-of-digits-in-numeric-character-reference'); //This is an absence-of-digits-in-numeric-character-reference parse error. FlushCodePointsConsumed; //Flush code points consumed as a character reference. Reconsume(FReturnState2); //Reconsume in the return state. end; end; procedure THtmlTokenizer.DoDecimalCharacterReferenceStartState; var ch: UCS4Char; begin //13.2.5.77 Decimal character reference start state //https://html.spec.whatwg.org/multipage/parsing.html#decimal-character-reference-start-state ch := Consume; //Consume the next input character: if ch in asciiDigit then begin Reconsume(tsDecimalCharacterReferenceState); //Reconsume in the decimal character reference state. end else begin AddParseError('absence-of-digits-in-numeric-character-reference'); //This is an absence-of-digits-in-numeric-character-reference parse error. FlushCodePointsConsumed; //Flush code points consumed as a character reference. Reconsume(FReturnState2); //Reconsume in the return state. end; end; procedure THtmlTokenizer.DoHexadecimalCharacterReferenceState; var ch: UCS4Char; begin //13.2.5.78 Hexadecimal character reference state //https://html.spec.whatwg.org/multipage/parsing.html#hexadecimal-character-reference-state ch := Consume; //Consume the next input character: if ch in asciiDigit then begin FCharacterReferenceCode := FCharacterReferenceCode * 16; //Multiply the character reference code by 16. FCharacterReferenceCode := FCharacterReferenceCode + (ch - $0030); //Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code. end else if ch in asciiUpperHexDigit then begin FCharacterReferenceCode := FCharacterReferenceCode * 16; //Multiply the character reference code by 16. FCharacterReferenceCode := FCharacterReferenceCode + (ch - $0037); //Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0037 from the character's code point) to the character reference code. end else if ch in asciiLowerHexDigit then begin FCharacterReferenceCode := FCharacterReferenceCode * 16; //Multiply the character reference code by 16. FCharacterReferenceCode := FCharacterReferenceCode + (ch - $0057); //Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0057 from the character's code point) to the character reference code. end else if ch = $003B then //U+003B SEMICOLON begin SetState(tsNumericCharacterReferenceEndState); //Switch to the numeric character reference end state. end else begin AddParseError('missing-semicolon-after-character-reference'); //This is a missing-semicolon-after-character-reference parse error. Reconsume(tsNumericCharacterReferenceEndState); //Reconsume in the numeric character reference end state. end; end; procedure THtmlTokenizer.DoDecimalCharacterReferenceState; var ch: UCS4Char; begin //13.2.5.79 Decimal character reference state //https://html.spec.whatwg.org/multipage/parsing.html#decimal-character-reference-state ch := Consume; //Consume the next input character: if ch in asciiDigit then begin FCharacterReferenceCode := FCharacterReferenceCode * 10; //Multiply the character reference code by 10. FCharacterReferenceCode := FCharacterReferenceCode + (ch - $0030); //Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code. end else if ch = $003B then // U+003B SEMICOLON begin SetState(tsNumericCharacterReferenceEndState); //Switch to the numeric character reference end state. end else begin AddParseError('missing-semicolon-after-character-reference'); //This is a missing-semicolon-after-character-reference parse error. Reconsume(tsNumericCharacterReferenceEndState); //Reconsume in the numeric character reference end state. end; end; procedure THtmlTokenizer.DoNumericCharacterReferenceEndState; begin //13.2.5.80 Numeric character reference end state //https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state (* Check the character reference code: If the number is 0x00, then this is a null-character-reference parse error. Set the character reference code to 0xFFFD. If the number is greater than 0x10FFFF, then this is a character-reference-outside-unicode-range parse error. Set the character reference code to 0xFFFD. If the number is a surrogate, then this is a surrogate-character-reference parse error. Set the character reference code to 0xFFFD. If the number is a noncharacter, then this is a noncharacter-character-reference parse error. If the number is 0x0D, or a control that's not ASCII whitespace, then this is a control-character-reference parse error. If the number is one of the numbers in the first column of the following table, then find the row with that number in the first column, and set the character reference code to the number in the second column of that row. Number Code point 0x80 0x20AC EURO SIGN (€) 0x82 0x201A SINGLE LOW-9 QUOTATION MARK (‚) 0x83 0x0192 LATIN SMALL LETTER F WITH HOOK (ƒ) 0x84 0x201E DOUBLE LOW-9 QUOTATION MARK („) 0x85 0x2026 HORIZONTAL ELLIPSIS (…) 0x86 0x2020 DAGGER (†) 0x87 0x2021 DOUBLE DAGGER (‡) 0x88 0x02C6 MODIFIER LETTER CIRCUMFLEX ACCENT (ˆ) 0x89 0x2030 PER MILLE SIGN (‰) 0x8A 0x0160 LATIN CAPITAL LETTER S WITH CARON (Š) 0x8B 0x2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK (‹) 0x8C 0x0152 LATIN CAPITAL LIGATURE OE (Œ) 0x8E 0x017D LATIN CAPITAL LETTER Z WITH CARON (Ž) 0x91 0x2018 LEFT SINGLE QUOTATION MARK (‘) 0x92 0x2019 RIGHT SINGLE QUOTATION MARK (’) 0x93 0x201C LEFT DOUBLE QUOTATION MARK (“) 0x94 0x201D RIGHT DOUBLE QUOTATION MARK (”) 0x95 0x2022 BULLET (•) 0x96 0x2013 EN DASH (–) 0x97 0x2014 EM DASH (—) 0x98 0x02DC SMALL TILDE (˜) 0x99 0x2122 TRADE MARK SIGN (™) 0x9A 0x0161 LATIN SMALL LETTER S WITH CARON (š) 0x9B 0x203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (›) 0x9C 0x0153 LATIN SMALL LIGATURE OE (œ) 0x9E 0x017E LATIN SMALL LETTER Z WITH CARON (ž) 0x9F 0x0178 LATIN CAPITAL LETTER Y WITH DIAERESIS (Ÿ) Set the temporary buffer to the empty string. Append a code point equal to the character reference code to the temporary buffer. Flush code points consumed as a character reference. Switch to the return state. *) AddNotImplementedParseError('NumericCharacterReferenceEndState'); end; procedure THtmlTokenizer.EmitCharacter(const Character: UCS4Char); var token: TCharacterToken; begin //Emit a character token. token := TCharacterToken.Create; token.Data := Character; EmitToken(token); end; procedure THtmlTokenizer.EmitCurrentCommentToken; begin //Emit the current token - which is assumed to be a Comment token. EmitToken(FCurrentToken as TCommentToken); end; procedure THtmlTokenizer.EmitCurrentTagToken; begin //Emit the current token - which is assumed to be a either a StartTag or EndTag token. if FCurrentToken = nil then raise Exception.Create('EmitCurrentTagToken expected a current token'); if FCurrentToken is TStartTagToken then EmitStartTag else if FCurrentToken is TEndTagToken then EmitEndTag else raise Exception.CreateFmt('EmitCurrentTagToken expected the current token to be a tag (was %s)', [FCurrentToken.ClassName]); end; procedure THtmlTokenizer.EmitCurrentDocTypeToken; begin //Emit the current token - which is assumed to be a DOCTYPE token. EmitToken(FCurrentToken as TDocTypeToken); end; procedure THtmlTokenizer.EmitEndOfFileToken; var token: TEndOfFileToken; begin //Emit an End Of File token. token := TEndOfFileToken.Create; EmitToken(token); end; procedure THtmlTokenizer.EmitEndTag; var token: TEndTagToken; begin { Emit the current token - which is assumed to be a EndTag token. } token := FCurrentToken as TEndTagToken; if token = nil then raise Exception.Create('Cannot emit end tag: CurrentToken is nil'); //When an end tag token is emitted with attributes, //that is an end-tag-with-attributes parse error. if token.Attributes.Count > 0 then AddParseError('end-tag-with-attributes'); //When an end tag token is emitted with its self-closing flag set, //that is an end-tag-with-trailing-solidus parse error. if token.SelfClosing then AddParseError('end-tag-with-trailing-solidus'); EmitToken(token); end; procedure THtmlTokenizer.EmitStartTag; var startTag: TStartTagToken; begin { Emit the current token - which is assumed to be a StartTag token. } if not (FCurrentToken is TStartTagToken) then raise EConvertError.CreateFmt('Cannot cast %s object to type TStartTagToken', [FCurrentToken.ClassName]); startTag := FCurrentToken as TStartTagToken; startTag.FinalizeAttributeName; EmitToken(startTag); { https://html.spec.whatwg.org/multipage/parsing.html#acknowledge-self-closing-flag When a start tag token is emitted with its [self-closing flag] set, if the flag is not **acknowledged** when it is processed by the tree construction stage, that is a [non-void-html-element-start-tag-with-trailing-solidus] [parse error]. } //I *guess* the tree builder acknowledges it by clearing the self-closing boolean? //I suppose there could also be some sort of StartTag.AcknowledgeSelfClosingFlag if startTag.SelfClosing = True then AddParseError('non-void-html-element-start-tag-with-trailing-solidus'); end; procedure THtmlTokenizer.EmitToken(const AToken: THtmlToken); begin if Assigned(FOnToken) then FOnToken(Self, AToken); end; procedure THtmlTokenizer.FlushCodePointsConsumed; var i: Integer; begin { https://html.spec.whatwg.org/multipage/parsing.html#flush-code-points-consumed-as-a-character-reference When a state says to **flush code points consumed as a character reference**, it means that for each [code point] in the [temporary buffer] (in the order they were added to the buffer) user agent must append the code point from the buffer to the current attribute's value if the character reference was [consumed as part of an attribute], or emit the code point as a character token otherwise. } if IsConsumedAsPartOfAnAttribute then begin for i := 0 to Length(FTemporaryBuffer)-1 do CurrentTagToken.CurrentAttributeValue := CurrentTagToken.CurrentAttributeValue + UCS4CharToUnicodeString(FTemporaryBuffer[i]); end else begin { TODO: Implementation question. It says append all the character to the current attribute vulue, but it says otherwise emit the code point (singular) as a character token. Am i only emitting one character from the Temporary buffer? Am i emitting all characters from the temporary buffer? Or am i only to emit the *"current input character"* } for i := 0 to Length(FTemporaryBuffer)-1 do CurrentTagToken.CurrentAttributeValue := CurrentTagToken.CurrentAttributeValue + UCS4CharToUnicodeString(FTemporaryBuffer[i]); end; end; function THtmlTokenizer.GetCurrentTagToken: TTagToken; begin Result := FCurrentToken as TTagToken; end; function THtmlTokenizer.GetNext: UCS4Char; var res: Boolean; begin res := FStream.TryRead({out}Result); if not res then begin Result := UEOF; FEOF := True; Exit; end; end; procedure THtmlTokenizer.Initialize; begin FStream := nil; FState2 := tsDataState; //The state machine must start in the data state. FCurrentInputCharacter := MaxInt; //UCS4 doesn't allow negative, so we use $FFFFFFFF end; function THtmlTokenizer.IsAppropriateEndTag(const EndTagToken: TEndTagToken): Boolean; begin { https://html.spec.whatwg.org/multipage/parsing.html#appropriate-end-tag-token An **appropriate end tag token** is an end tag token whose tag name matches the tag name of the last start tag to have been emitted from this tokenizer, if any. If no start tag has been emitted from this tokenizer, then no end tag token is appropriate. } if EndTagToken = nil then raise EArgumentNilException.Create('EndTagToken'); //TODO: Implementator's question: Should the tag name comparison case sensitive? Result := SameText(FNameOfLastEmittedStartTag, EndTagToken.TagName); end; function THtmlTokenizer.IsConsumedAsPartOfAnAttribute: Boolean; begin { https://html.spec.whatwg.org/multipage/parsing.html#charref-in-attribute A [character reference] is said to be **consumed as part of an attribute** if the return state is either - [attribute value (double-quoted) state], - [attribute value (single-quoted) state] or - [attribute value (unquoted) state]. } Result := FReturnState2 in [ tsAttributeValueDoubleQuotedState, tsAttributeValueSingleQuotedState, tsAttributeValueUnquotedState]; end; procedure THtmlTokenizer.Reconsume(NewTokenizerState: TTokenizerState); begin { When a state says to reconsume a matched character in a specified state, that means to switch to that state, but when it attempts to consume the next input character, provide it with the current input character instead. This method is public because there are two situations where the tree construction state needs to change the tokenzier state. } FReconsume := True; SetState(NewTokenizerState); end; procedure THtmlTokenizer.SetState(const State: TTokenizerState); begin FState2 := State; LogFmt(' ==> %s', [TypInfo.GetEnumName(TypeInfo(TTokenizerState), Ord(State))]); end; function THtmlTokenizer.TemporaryBufferIs(const Value: UnicodeString): Boolean; var tb: UnicodeString; begin tb := UCS4StringToUnicodeString(FTemporaryBuffer); Result := SameText(tb, Value); //TODO: Implementor's question: should this be case sensitive? end; procedure THtmlTokenizer.SetReturnState(const State: TTokenizerState); begin FReturnState2 := State; LogFmt(' ReturnState ==> %s', [TypInfo.GetEnumName(TypeInfo(TTokenizerState), Ord(State))]); end; { TInputStream } function TInputStream.Consume: UCS4Char; begin { Extract the next character from our (possibly buffered) stream. } //Get the next character from the ring buffer if FBufferSize > 0 then begin Result := FBuffer[FBufferPosition]; Inc(FBufferPosition); if FBufferPosition >= Length(FBuffer) then //the ring part of ring-buffer FBufferPosition := 0; Dec(FBufferSize); Exit; end; Result := GetNextCharacterFromStream; end; constructor TInputStream.Create(ByteStream: ISequentialStream; Encoding: Word); begin inherited Create; FStream := ByteStream; FEncoding := Encoding; FEOF := False; //FBuffer is a ring-buffer, with the current position at "FBufferPosition" //and there is FBufferSize valid characters SetLength(FBuffer, 1024); FBufferSize := 0; FBufferPosition := 0; end; function TInputStream.FetchNextCharacterInfoBuffer: Boolean; var ch: UCS4Char; n: Integer; begin ch := Self.GetNextCharacterFromStream; if ch = UEOF then begin Result := False; Exit; end; n := FBufferPosition + FBufferSize; if n > Length(FBuffer) then n := 0; FBuffer[n] := ch; Inc(FBufferSize); Result := True; end; function TInputStream.GetNextCharacterFromStream: UCS4Char; begin case FEncoding of CP_UTF16: Result := Self.GetNextUTF16Character else raise Exception.Create('Unknown encoding'); end; end; function TInputStream.GetNextUTF16Character: UCS4Char; var wh, wl: Word; hr: HRESULT; cbRead: FixedUInt; begin { Get the next UTF-16 character from the stream. NOTE: The next input character could be larger than 16-bits. That's because Unicode characters are larger than 16-bits. The common bug in .NET TextReader is that it will return a surrogate, rather than the actual character, if the character's numeric value is larger than 16-bits. For that reason we can't use TextReader/StreamReader/StringReader. } hr := FStream.Read(@wh, sizeof(Word), @cbRead); OleCheck(hr); if hr = S_FALSE then begin Result := UEOF; // FEOF := True; can't set this yet. We're not *really* at the end, because we might be peeking. Have to save setting EOF until we officially read it Exit; end; if IsSurrogate(wh) then begin //It's a surrogate pair. Read the 2nd character hr := FStream.Read(@wl, sizeof(Word), nil); OleCheck(hr); if hr = S_FALSE then //If we couldn't read it, then it's nonsense anyway begin //Invalid surrogate pair: the pair is missing FEOF := True; wl := $DC00; //so that when we subtract $DC00 it becomes zero (really: so that it doesn't become negative) end; wh := (wh - $D800) * $400; wl := (wl - $DC00); Result := wh+wl; Exit; end; //It's a regular-old character. Result := wh; end; constructor TInputStream.Create(const Html: UnicodeString); var stream: TStream; stm: ISequentialStream; begin stream := TStringStream.Create(Html, CP_UTF16); stm := TFixedStreamAdapter.Create(stream, soOwned) as IStream; Self.Create(stm, CP_UTF16); end; function TInputStream.IsSurrogate(const n: Word): Boolean; begin case n of $D800..$DFFF: Result := True; else Result := False; end; end; function TInputStream.Peek(k: Integer): UCS4Char; begin // Return the k-th character (e.g. 1st, 2nd, 3rd) without popping it. { Ensure the ring buffer has at least k characters If k<n, that means k-th character is in the buffer. Then return the k-th character from the buffer. } while k > FBufferSize do begin //If k > n, that means k-th character is not in the buffer. //Read up to the k-th character and add it to the buffer. //Since already n characters are in the buffer, //total k-n number of characters will be read. //Then return the k-th character from the buffer. if not FetchNextCharacterInfoBuffer then begin Result := UEOF; Exit; end; end; Result := FBuffer[FBufferPosition+(k-1)]; LogFmt(' Peek: [%s]', []); end; procedure TInputStream.LogFmt(const s: string; const Args: array of const); begin end; function TInputStream.TryRead(out ch: UCS4Char): Boolean; begin { Read the next unicode character from the input stream. } Result := False; ch := Consume; if ch = UEOF then begin FEOF := True; Exit; end; //U+000D CARRIAGE RETURN (CR) if ch = $000D then begin { U+000D CARRIAGE RETURN (CR) characters and U+000A LINE FEED (LF) characters are treated specially. } if Peek(1) = $000A then //U+000A LINE FEED (LF) begin { Any LF character that immediately follows a CR character must be ignored, and all CR characters must then be converted to LF characters. Thus, newlines in HTML DOMs are represented by LF characters, and there are never any CR characters in the input to the tokenization stage. } Consume; end; ch := $000A; //U+000A LINE FEED (LF) end; Result := True; end; { TDocTypeToken } procedure TDocTypeToken.AppendName(const ch: UCS4Char); begin FName := FName + UCS4CharToUnicodeString(ch); end; procedure TDocTypeToken.AppendPublicIdentifier(const ch: UCS4Char); begin FPublicIdentifier := FPublicIdentifier + UCS4CharToUnicodeString(ch); end; procedure TDocTypeToken.AppendSystemIdentifier(const ch: UCS4Char); begin FSystemIdentifier := FSystemIdentifier + UCS4CharToUnicodeString(ch); end; constructor TDocTypeToken.Create; begin inherited Create(ttDocType); { When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), and the force-quirks flag must be set to off (its other state is on). } FNameMissing := True; FPublicIdentifierMissing := True; FSystemIdentifierMissing := True; ForceQuirks := False; end; function TDocTypeToken.GetDescription: string; begin { DOCTYPE: HTML } Result := 'DOCTYPE: '+Self.Name; end; procedure TDocTypeToken.SetName(const Value: UnicodeString); begin FName := Value; FNameMissing := False; end; procedure TDocTypeToken.SetPublicIdentifier(const Value: UnicodeString); begin FPublicIdentifier := Value; FPublicIdentifierMissing := False; end; procedure TDocTypeToken.SetSystemIdentifier(const Value: UnicodeString); begin FSystemIdentifier := Value; FSystemIdentifierMissing := False; end; { TEndTagToken } constructor TEndTagToken.Create; begin inherited Create(ttEndTag); end; { TStartTagToken } procedure TStartTagToken.AcknowledgeSelfClosing; begin FSelfClosing := False; end; constructor TStartTagToken.Create; begin inherited Create(ttStartTag); end; { THtmlToken } constructor THtmlToken.Create(ATokenType: THtmlTokenType); begin inherited Create; Self.TokenType := ATokenType; end; function THtmlToken.GetDescription: string; begin Result := 'Base Token'; end; { TCommentToken } procedure TCommentToken.AppendCharacter(const ch: UCS4Char); begin if ch > $FFFF then raise Exception.CreateFmt('Attempt to add extended character (%d) to comment token', [ch]); UCS4StrCat({var}FData, ch); end; constructor TCommentToken.Create; begin inherited Create(ttComment); end; function TCommentToken.GetDataString: UnicodeString; begin Result := UCS4ToUnicodeString(FData); end; function TCommentToken.GetDescription: string; begin Result := '#comment: '+Self.DataString; end; { TCharacterToken } constructor TCharacterToken.Create; begin inherited Create(ttCharacter); end; function TCharacterToken.GetDataString: UnicodeString; var s: UCS4String; begin SetLength(s, 1); s[0] := Self.Data; Result := UCS4StringToUnicodeString(s); end; function TCharacterToken.GetDescription: string; var s: string; ch: Word; begin s := Self.DataString; if Length(s) = 1 then begin ch := Word(s[1]); case ch of //$0000..$001F: {C0 controls}; $0000: ch := $2400; //NULL $0001: ch := $2401; //SOH $0002: ch := $2402; //STX $0003: ch := $2403; //ETX $0004: ch := $2404; //EOT $0005: ch := $2405; //ENQ $0006: ch := $2406; //ACK $0007: ch := $2407; //BEL $0008: ch := $2408; //BS $0009: ch := $279D; //$2409; //HT $000A: ch := $23ce; //$240A; //LF $000B: ch := $240B; //VT $000C: ch := $240C; //FF $000D: ch := $23ce; //$240D; //CR $000E: ch := $240E; //SO $000F: ch := $240F; //SI $0010: ch := $2410; //DLE $0011: ch := $2411; //DC1 $0012: ch := $2412; //DC2 $0013: ch := $2413; //DC3 $0014: ch := $2414; //DC4 $0015: ch := $2415; //NAK $0016: ch := $2416; //SYN $0017: ch := $2417; //ETB $0018: ch := $2418; //CAN $0019: ch := $2419; //EM $001A: ch := $241A; //SUB $001B: ch := $241B; //ESC $001C: ch := $241C; //FS $001D: ch := $241D; //GS $001E: ch := $241E; //RS $001F: ch := $241F; //US //$0020: ch := $00B7; //' ' $007F: ch := $232B; //$2421; {delete} $0080..$009F: {C1 controls}; end; s[1] := WideChar(ch); end; Result := '#character: '+s; end; { TEndOfFileToken } constructor TEndOfFileToken.Create; begin inherited Create(ttEndOfFile); end; function TEndOfFileToken.GetDescription: string; begin Result := '[End-of-File]'; end; { TFixedStreamAdapter } function TFixedStreamAdapter.Read(pv: Pointer; cb: FixedUInt; pcbRead: PFixedUInt): HResult; var bytesRead: FixedUInt; begin try if pv = nil then begin Result := STG_E_INVALIDPOINTER; //One of the pointer values is invalid. Exit; end; bytesRead := Self.Stream.Read(pv^, cb); if pcbRead <> nil then pcbRead^ := bytesRead; //FIX: IStream must return S_FALSE if the number of bytes read is less than the number of bytes requested in cb. if bytesRead < cb then begin Result := S_FALSE; Exit; end; Result := S_OK; except Result := E_FAIL; //And we don't return S_FALSE (success) for an error, we return an error. end; end; function UCS4ToUnicodeString(const S: UCS4String): UnicodeString; var I: Integer; CharCount: Integer; Tmp: array of WideChar; //should be begin SetLength(Tmp, Length(S) * 2 - 1); //Maximum possible number of characters CharCount := -1; I := 0; while I <= Length(S)-1 do //FIX: less OR EQUAL than begin if S[I] >= $10000 then begin Inc(CharCount); Tmp[CharCount] := WideChar((((S[I] - $00010000) shr 10) and $000003FF) or $D800); Inc(CharCount); Tmp[CharCount] := WideChar(((S[I] - $00010000) and $000003FF)or $DC00); end else begin Inc(CharCount); Tmp[CharCount] := WideChar(S[I]); end; Inc(I); end; SetString(Result, PChar(Tmp), CharCount + 1); end; procedure UCS4StrCat(var Dest: UCS4String; const Source: UCS4Char); var n: Integer; begin { Concatenate two strings: Dest := Dest + Source; } n := Length(Dest); SetLength(Dest, n+1); Dest[n] := Source; end; procedure UCS4StrFromChar(var Dest: UCS4String; const Source: UCS4Char); begin { Convert a single UCS4Char into a UCS4String. Similar to: System._UStrFromChar UnicodeString <== AnsiChar System._UStrFromWChar UnicodeString <== WideChar System._WStrFromChar WideString <== AnsiChar System._WStrFromWChar WideString } SetLength(Dest, 1);// Dest[0] := Source; end; procedure UCS4StrFromUStr(var Dest: UCS4String; const Source: UnicodeString); var i: Integer; wh, wl: Word; ch: UCS4Char; n: Integer; begin if Source = '' then begin SetLength(Dest, 0); Exit; end; i := 1; while i <= Length(Source) do begin wl := Word(Source[i]); //Check if wl is a surrogate apir case wl of $D800..$DFFF: begin //Is it a surrogate pair. //Push wl to the upper word, and read the lower word wh := (wl - $D800) * $400; if (i+1) <= Length(Source) then wl := Word(Source[i+1]) else wl := 0; ch := wh+wl; end; else ch := wl; end; n := Length(Dest); SetLength(Dest, n+1); Dest[n] := ch; end; end; function UCS4StrCopy(const S: UCS4String; Index, Count: Integer): UCS4String; //similar to System._UStrCopy begin Result := Copy(S, Index-1, Count); end; procedure UCS4StrFromPUCS4CharLen(var Dest: UCS4String; Source: PUCS4Char; CharLength: Integer); //similar to System._UStrFromPWCharLen begin SetLength(Dest, CharLength); Move(Source^, Dest[0], CharLength*sizeof(UCS4Char)); end; function UCS4CharToUnicodeString(const ch: UCS4Char): UnicodeString; //either 1 or 2 WideChar var s: UCS4String; begin UCS4StrFromChar({var}s, ch); Result := UCS4StringToUnicodeString(s); end; { TTagToken } procedure TTagToken.AppendCharacter(const ch: UCS4Char); begin if ch > $FFFF then raise Exception.CreateFmt('Attempt to add extended character (%d) to tag token', [ch]); UCS4StrCat(FData, ch); end; constructor TTagToken.Create(ATokenType: THtmlTokenType); begin inherited Create(ATokenType); FSelfClosing := False; //self-closing flag must be unset (its other state is that it be set) FAttributes := TList.Create; //and its attributes list must be empty. end; destructor TTagToken.Destroy; begin FreeAndNil(FAttributes); inherited; end; procedure TTagToken.FinalizeAttributeName; begin { TODO: When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a duplicate-attribute parse error and the new attribute must be removed from the token. } end; function TTagToken.GetDescription: string; var s: string; i: Integer; begin { <section id="lblTitle" class="blue even primary"> } s := '<'+Self.TagName; for i := 0 to Self.Attributes.Count-1 do s := s+' key="value"'; s := s+'>'; Result := s; end; function TTagToken.GetTagName: UnicodeString; begin Result := UCS4ToUnicodeString(FData); end; procedure TTagToken.NewAttribute; begin CurrentAttributeName := ''; CurrentAttributeValue := ''; end; end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Model relacionado à tabela [PRODUTO] The MIT License Copyright: Copyright (C) 2021 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 Produto; interface uses MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TProduto = class(TModelBase) private FId: Integer; FIdProdutoUnidade: Integer; FIdTributGrupoTributario: Integer; FIdProdutoTipo: Integer; FIdProdutoSubgrupo: Integer; FGtin: string; FCodigoInterno: string; FNome: string; FDescricao: string; FDescricaoPdv: string; FValorCompra: Extended; FValorVenda: Extended; FQuantidadeEstoque: Extended; FEstoqueMinimo: Extended; FEstoqueMaximo: Extended; FCodigoNcm: string; FIat: string; FIppt: string; FTipoItemSped: string; FTaxaIpi: Extended; FTaxaIssqn: Extended; FTaxaPis: Extended; FTaxaCofins: Extended; FTaxaIcms: Extended; FCst: string; FCsosn: string; FTotalizadorParcial: string; FEcfIcmsSt: string; FCodigoBalanca: Integer; FPafPSt: string; FHashRegistro: string; FValorCusto: Extended; FSituacao: string; FCodigoCest: string; public // procedure ValidarInsercao; override; // procedure ValidarAlteracao; override; // procedure ValidarExclusao; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_PRODUTO_UNIDADE')] [MVCNameAsAttribute('idProdutoUnidade')] property IdProdutoUnidade: Integer read FIdProdutoUnidade write FIdProdutoUnidade; [MVCColumnAttribute('ID_TRIBUT_GRUPO_TRIBUTARIO')] [MVCNameAsAttribute('idTributGrupoTributario')] property IdTributGrupoTributario: Integer read FIdTributGrupoTributario write FIdTributGrupoTributario; [MVCColumnAttribute('ID_PRODUTO_TIPO')] [MVCNameAsAttribute('idProdutoTipo')] property IdProdutoTipo: Integer read FIdProdutoTipo write FIdProdutoTipo; [MVCColumnAttribute('ID_PRODUTO_SUBGRUPO')] [MVCNameAsAttribute('idProdutoSubgrupo')] property IdProdutoSubgrupo: Integer read FIdProdutoSubgrupo write FIdProdutoSubgrupo; [MVCColumnAttribute('GTIN')] [MVCNameAsAttribute('gtin')] property Gtin: string read FGtin write FGtin; [MVCColumnAttribute('CODIGO_INTERNO')] [MVCNameAsAttribute('codigoInterno')] property CodigoInterno: string read FCodigoInterno write FCodigoInterno; [MVCColumnAttribute('NOME')] [MVCNameAsAttribute('nome')] property Nome: string read FNome write FNome; [MVCColumnAttribute('DESCRICAO')] [MVCNameAsAttribute('descricao')] property Descricao: string read FDescricao write FDescricao; [MVCColumnAttribute('DESCRICAO_PDV')] [MVCNameAsAttribute('descricaoPdv')] property DescricaoPdv: string read FDescricaoPdv write FDescricaoPdv; [MVCColumnAttribute('VALOR_COMPRA')] [MVCNameAsAttribute('valorCompra')] property ValorCompra: Extended read FValorCompra write FValorCompra; [MVCColumnAttribute('VALOR_VENDA')] [MVCNameAsAttribute('valorVenda')] property ValorVenda: Extended read FValorVenda write FValorVenda; [MVCColumnAttribute('QUANTIDADE_ESTOQUE')] [MVCNameAsAttribute('quantidadeEstoque')] property QuantidadeEstoque: Extended read FQuantidadeEstoque write FQuantidadeEstoque; [MVCColumnAttribute('ESTOQUE_MINIMO')] [MVCNameAsAttribute('estoqueMinimo')] property EstoqueMinimo: Extended read FEstoqueMinimo write FEstoqueMinimo; [MVCColumnAttribute('ESTOQUE_MAXIMO')] [MVCNameAsAttribute('estoqueMaximo')] property EstoqueMaximo: Extended read FEstoqueMaximo write FEstoqueMaximo; [MVCColumnAttribute('CODIGO_NCM')] [MVCNameAsAttribute('codigoNcm')] property CodigoNcm: string read FCodigoNcm write FCodigoNcm; [MVCColumnAttribute('IAT')] [MVCNameAsAttribute('iat')] property Iat: string read FIat write FIat; [MVCColumnAttribute('IPPT')] [MVCNameAsAttribute('ippt')] property Ippt: string read FIppt write FIppt; [MVCColumnAttribute('TIPO_ITEM_SPED')] [MVCNameAsAttribute('tipoItemSped')] property TipoItemSped: string read FTipoItemSped write FTipoItemSped; [MVCColumnAttribute('TAXA_IPI')] [MVCNameAsAttribute('taxaIpi')] property TaxaIpi: Extended read FTaxaIpi write FTaxaIpi; [MVCColumnAttribute('TAXA_ISSQN')] [MVCNameAsAttribute('taxaIssqn')] property TaxaIssqn: Extended read FTaxaIssqn write FTaxaIssqn; [MVCColumnAttribute('TAXA_PIS')] [MVCNameAsAttribute('taxaPis')] property TaxaPis: Extended read FTaxaPis write FTaxaPis; [MVCColumnAttribute('TAXA_COFINS')] [MVCNameAsAttribute('taxaCofins')] property TaxaCofins: Extended read FTaxaCofins write FTaxaCofins; [MVCColumnAttribute('TAXA_ICMS')] [MVCNameAsAttribute('taxaIcms')] property TaxaIcms: Extended read FTaxaIcms write FTaxaIcms; [MVCColumnAttribute('CST')] [MVCNameAsAttribute('cst')] property Cst: string read FCst write FCst; [MVCColumnAttribute('CSOSN')] [MVCNameAsAttribute('csosn')] property Csosn: string read FCsosn write FCsosn; [MVCColumnAttribute('TOTALIZADOR_PARCIAL')] [MVCNameAsAttribute('totalizadorParcial')] property TotalizadorParcial: string read FTotalizadorParcial write FTotalizadorParcial; [MVCColumnAttribute('ECF_ICMS_ST')] [MVCNameAsAttribute('ecfIcmsSt')] property EcfIcmsSt: string read FEcfIcmsSt write FEcfIcmsSt; [MVCColumnAttribute('CODIGO_BALANCA')] [MVCNameAsAttribute('codigoBalanca')] property CodigoBalanca: Integer read FCodigoBalanca write FCodigoBalanca; [MVCColumnAttribute('PAF_P_ST')] [MVCNameAsAttribute('pafPSt')] property PafPSt: string read FPafPSt write FPafPSt; [MVCColumnAttribute('HASH_REGISTRO')] [MVCNameAsAttribute('hashRegistro')] property HashRegistro: string read FHashRegistro write FHashRegistro; [MVCColumnAttribute('VALOR_CUSTO')] [MVCNameAsAttribute('valorCusto')] property ValorCusto: Extended read FValorCusto write FValorCusto; [MVCColumnAttribute('SITUACAO')] [MVCNameAsAttribute('situacao')] property Situacao: string read FSituacao write FSituacao; [MVCColumnAttribute('CODIGO_CEST')] [MVCNameAsAttribute('codigoCest')] property CodigoCest: string read FCodigoCest write FCodigoCest; end; implementation { TProduto } end.
unit BCEditor.Editor.CompletionProposal; interface uses System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.ImgList, BCEditor.Editor.CompletionProposal.Colors, BCEditor.Editor.CompletionProposal.Columns, BCEditor.Editor.CompletionProposal.Trigger, BCEditor.Types; const BCEDITOR_COMPLETION_PROPOSAL_DEFAULT_OPTIONS = [cpoAutoConstraints, cpoAddHighlighterKeywords, cpoFiltered, cpoParseItemsFromText, cpoUseHighlighterColumnFont]; type TBCEditorCompletionProposal = class(TPersistent) strict private FCloseChars: string; FColors: TBCEditorCompletionProposalColors; FColumns: TBCEditorCompletionProposalColumns; FCompletionColumnIndex: Integer; FConstraints: TSizeConstraints; FEnabled: Boolean; FImages: TCustomImageList; FOptions: TBCEditorCompletionProposalOptions; FOwner: TComponent; FSecondaryShortCut: TShortCut; FShortCut: TShortCut; FTrigger: TBCEditorCompletionProposalTrigger; FVisibleLines: Integer; FWidth: Integer; procedure SetImages(const AValue: TCustomImageList); protected function GetOwner: TPersistent; override; public constructor Create(AOwner: TComponent); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; procedure SetOption(const AOption: TBCEditorCompletionProposalOption; const AEnabled: Boolean); published property CloseChars: string read FCloseChars write FCloseChars; property Colors: TBCEditorCompletionProposalColors read FColors write FColors; property Columns: TBCEditorCompletionProposalColumns read FColumns write FColumns; property CompletionColumnIndex: Integer read FCompletionColumnIndex write FCompletionColumnIndex default 0; property Constraints: TSizeConstraints read FConstraints write FConstraints; property Enabled: Boolean read FEnabled write FEnabled default True; property Images: TCustomImageList read FImages write SetImages; property Options: TBCEditorCompletionProposalOptions read FOptions write FOptions default BCEDITOR_COMPLETION_PROPOSAL_DEFAULT_OPTIONS; property SecondaryShortCut: TShortCut read FSecondaryShortCut write FSecondaryShortCut; property ShortCut: TShortCut read FShortCut write FShortCut; property Trigger: TBCEditorCompletionProposalTrigger read FTrigger write FTrigger; property VisibleLines: Integer read FVisibleLines write FVisibleLines default 8; property Width: Integer read FWidth write FWidth default 260; end; implementation uses Vcl.Menus; constructor TBCEditorCompletionProposal.Create(AOwner: TComponent); begin inherited Create; FOwner := AOwner; FCloseChars := '()[]. '; FColors := TBCEditorCompletionProposalColors.Create; FColumns := TBCEditorCompletionProposalColumns.Create(Self, TBCEditorCompletionProposalColumn); FColumns.Add; { default column } FCompletionColumnIndex := 0; FEnabled := True; FOptions := BCEDITOR_COMPLETION_PROPOSAL_DEFAULT_OPTIONS; FShortCut := Vcl.Menus.ShortCut(Ord(' '), [ssCtrl]); FTrigger := TBCEditorCompletionProposalTrigger.Create; FVisibleLines := 8; FWidth := 260; FConstraints := TSizeConstraints.Create(nil); end; destructor TBCEditorCompletionProposal.Destroy; begin FColors.Free; FTrigger.Free; FColumns.Free; FConstraints.Free; inherited; end; procedure TBCEditorCompletionProposal.Assign(ASource: TPersistent); begin if ASource is TBCEditorCompletionProposal then with ASource as TBCEditorCompletionProposal do begin Self.FCloseChars := FCloseChars; Self.FColors.Assign(FColors); Self.FColumns.Assign(FColumns); Self.FEnabled := FEnabled; Self.FImages := FImages; Self.FOptions := FOptions; Self.FSecondaryShortCut := FSecondaryShortCut; Self.FShortCut := FShortCut; Self.FTrigger.Assign(FTrigger); Self.FVisibleLines := FVisibleLines; Self.FWidth := FWidth; end else inherited Assign(ASource); end; procedure TBCEditorCompletionProposal.SetOption(const AOption: TBCEditorCompletionProposalOption; const AEnabled: Boolean); begin if AEnabled then Include(FOptions, AOption) else Exclude(FOptions, AOption); end; function TBCEditorCompletionProposal.GetOwner: TPersistent; begin Result := FOwner; end; procedure TBCEditorCompletionProposal.SetImages(const AValue: TCustomImageList); begin if FImages <> AValue then begin FImages := AValue; if Assigned(FImages) then FImages.FreeNotification(FOwner); end; end; end.
unit Interval; interface uses StrUtils, SysUtils, StringTokenizer; type TInterval=class private _separators : Vector; _intervals : Vector; _content : String; _startOffset : integer; _min : integer; _endOffset : integer; EMPTY_CHAR : char; _max : integer; __VERSION : String; procedure setFormatString(format : String); procedure parseString(format : String); procedure parseInterval(format : String; start : integer; end : integer); procedure parseSeparator(format : String; start : integer; end : integer); function getInterval(i : integer): Interval; function getSeparator(i : integer): String; function getIntervalsCount(): int; function getIndexIntervalFromOffset(offset : integer): int; function getIndexSeparatorFromOffset(offset : integer): int; function isCharDeletionValid(offset : integer): boolean; function isCharInsertionValid(c : char; offset : integer): boolean; function replaceChar(offset : integer; c : char): int; function getDisplayableString(hasFocus : boolean): String; function isAllEmpty(): boolean; function getIntValue(offset : integer): int; procedure setIntValue(offset : integer; value : integer); function getMinIntValue(offset : integer): int; function getMaxIntValue(offset : integer): int; procedure setValue(value : String); procedure clear(); function getMinimum(): int; function getMaximum(): int; function getMaxCharCount(): int; procedure setOffset(offset : integer); function getStartOffset(): int; function getEndOffset(): int; procedure replaceChar(offset : integer; c : char); function isEmpty(): boolean; function getContent(): String; function getEditingDisplayableString(): String; function getEditedDisplayableString(): String; function getMaxCompletedString(): String; function getMinCompletedString(): String; function getIntValue(): int; procedure setIntValue(value : integer); function getCurrentPossibleValue(): String; procedure clear(); public; constructor Create; destructor Destroy; override; end; function substring(str : String; offset : integer): String; function substring2(str : String; offset : integer; count : integer): String; function startsWith(str : String; prefix : String): boolean; function endsWith(str : String; suffix : String): boolean; implementation function substring(str : String; offset : integer): String; begin result := RightStr(str, Length(str) - offset); end; function substring2(str : String; offset : integer; count : integer): String; begin result := MidStr(str, offset+1, count - offset); end; function startsWith(str : String; prefix : String): boolean; begin result := (Pos(prefix, str) = 1); end; function endsWith(str : String; suffix : String): boolean; begin result := (RightStr(str, Length(suffix)) = suffix); end; { TInterval } constructor TInterval.Create(); begin inherited Create; end; destructor TInterval.Destroy(); begin inherited Destroy; end; unit Interval; interface uses StrUtils, SysUtils, StringTokenizer; type TInterval=class private _separators : Vector; _intervals : Vector; _content : String; _startOffset : integer; _min : integer; _endOffset : integer; EMPTY_CHAR : char; _max : integer; __VERSION : String; procedure setFormatString(format : String); procedure parseString(format : String); procedure parseInterval(format : String; start : integer; end : integer); procedure parseSeparator(format : String; start : integer; end : integer); function getInterval(i : integer): Interval; function getSeparator(i : integer): String; function getIntervalsCount(): int; function getIndexIntervalFromOffset(offset : integer): int; function getIndexSeparatorFromOffset(offset : integer): int; function isCharDeletionValid(offset : integer): boolean; function isCharInsertionValid(c : char; offset : integer): boolean; function replaceChar(offset : integer; c : char): int; function getDisplayableString(hasFocus : boolean): String; function isAllEmpty(): boolean; function getIntValue(offset : integer): int; procedure setIntValue(offset : integer; value : integer); function getMinIntValue(offset : integer): int; function getMaxIntValue(offset : integer): int; procedure setValue(value : String); procedure clear(); function getMinimum(): int; function getMaximum(): int; function getMaxCharCount(): int; procedure setOffset(offset : integer); function getStartOffset(): int; function getEndOffset(): int; procedure replaceChar(offset : integer; c : char); function isEmpty(): boolean; function getContent(): String; function getEditingDisplayableString(): String; function getEditedDisplayableString(): String; function getMaxCompletedString(): String; function getMinCompletedString(): String; function getIntValue(): int; procedure setIntValue(value : integer); function getCurrentPossibleValue(): String; procedure clear(); public; constructor Create; destructor Destroy; override; end; function substring(str : String; offset : integer): String; function substring2(str : String; offset : integer; count : integer): String; function startsWith(str : String; prefix : String): boolean; function endsWith(str : String; suffix : String): boolean; implementation function substring(str : String; offset : integer): String; begin result := RightStr(str, Length(str) - offset); end; function substring2(str : String; offset : integer; count : integer): String; begin result := MidStr(str, offset+1, count - offset); end; function startsWith(str : String; prefix : String): boolean; begin result := (Pos(prefix, str) = 1); end; function endsWith(str : String; suffix : String): boolean; begin result := (RightStr(str, Length(suffix)) = suffix); end; { TInterval } constructor TInterval.Create(); begin inherited Create; end; destructor TInterval.Destroy(); begin inherited Destroy; end; begin ~~~~~5 _intervals:=######7; ~~~~~5 _separators:=######7; EMPTY_CHAR:='_'; end; begin parseString(format); end; procedure TLyJFormat.setFormatString(format : String); begin parseString(format); end; procedure TLyJFormat.parseString(format : String); var start : integer; n : null; end : null; offset : integer; j : null; i : integer; firstInterval : null; beginBySep : boolean; size : integer; begin size:=format.length(); start:=format.indexOf('['); end:=format.indexOf(']'); beginBySep:=false; if (start<>0) then begin parseSeparator(format,0,start-1); beginBySep:=true; firstInterval:=start; end; parseInterval(format,start,end); start:=end+1; end:=format.indexOf('[',start)-1; begin parseSeparator(format,start,end); start:=end+1; end:=format.indexOf(']',start); parseInterval(format,start,end); start:=end+1; end:=format.indexOf('[',start)-1; end; if ((end<0) and (start<size)) then begin parseSeparator(format,start,size-1); end; offset:=firstInterval; i:=0; while (i<n) do begin j:=i; if (beginBySep) then begin j:=i+1; end; getInterval(i).setOffset(offset); offset+=getInterval(i).getMaxCharCount(); offset+=if ((i<(n-1))) then (getSeparator(j).length()) (0); inc(i); end; end; procedure TLyJFormat.parseInterval(format : String; start : integer; end : integer); var min : integer; str : String; pos : integer; max : null; begin if (start<end) then begin str:=substring2(format,start+1,end); begin pos:=str.indexOf('-'); min:=Integer.parseInt(substring2(str,0,pos)); max:=Integer.parseInt(substring(str,pos+1)); end; begin ~~~~~5 ; end; if (min<=max) then begin ~~~~~5 _intervals.add(######7); end else begin ~~~~~5 ; end; end else begin ~~~~~5 ; end; end; procedure TLyJFormat.parseSeparator(format : String; start : integer; end : integer); var str : String; begin if (start<=(end+1)) then begin str:=substring2(format,start,end+1); _separators.add(str); end else begin ~~~~~5 ; end; end; function TLyJFormat.getInterval(i : integer): Interval; begin result := _intervals.get(i); end; function TLyJFormat.getSeparator(i : integer): String; begin result := _separators.get(i); end; function TLyJFormat.getIntervalsCount(): int; begin result := _intervals.size(); end; function TLyJFormat.getIndexIntervalFromOffset(offset : integer): int; var n : null; i : integer; result : integer; begin result:=-1; i:=0; while (i<n) do begin if ((offset>=getInterval(i).getStartOffset()) and (offset<=getInterval(i).getEndOffset())) then begin result:=i; end; inc(i); end; result := result; end; function TLyJFormat.getIndexSeparatorFromOffset(offset : integer): int; var n : null; i : integer; result : integer; begin result:=-1; i:=0; while (i<n) do begin if ((offset>getInterval(i).getEndOffset()) and (offset<getInterval(i+1).getStartOffset())) then begin result:=i; end; inc(i); end; result := result; end; function TLyJFormat.isCharDeletionValid(offset : integer): boolean; var index : integer; begin index:=getIndexIntervalFromOffset(offset); if (index=-1) then begin result := false; end; result := true; end; function TLyJFormat.isCharInsertionValid(c : char; offset : integer): boolean; var minText : String; relOffset : integer; inter : Interval; maxValue : integer; index : integer; startOffset : integer; maxText : String; minValue : integer; minBuf : StringBuffer; maxBuf : StringBuffer; begin if (not Character.isDigit(c)) then begin result := false; end; index:=getIndexIntervalFromOffset(offset); if (index=-1) then begin result := false; end; inter:=getInterval(index); startOffset:=inter.getStartOffset(); relOffset:=offset-startOffset; ~~~~~5 minBuf:=######7; ~~~~~5 maxBuf:=######7; minBuf.setCharAt(relOffset,c); maxBuf.setCharAt(relOffset,c); minText:=minBuf.toString(); maxText:=maxBuf.toString(); begin minValue:=Integer.parseInt(minText); maxValue:=Integer.parseInt(maxText); end; begin result := false; end; if ((minValue<=inter.getMaximum()) and (maxValue>=inter.getMinimum())) then begin result := true; end; result := false; end; function TLyJFormat.replaceChar(offset : integer; c : char): int; var relOffset : integer; inter : Interval; index : integer; begin index:=getIndexIntervalFromOffset(offset); inter:=getInterval(index); relOffset:=offset-inter.getStartOffset(); inter.replaceChar(relOffset,c); if (relOffset=(inter.getMaxCharCount()-1)) then begin result := (if ((index<_separators.size())) then (offset+getSeparator(index).length()+1) (offset+1)); end; result := offset+1; end; function TLyJFormat.getDisplayableString(hasFocus : boolean): String; var n : null; j : null; i : integer; beginBySep : boolean; text : String; begin text:=''; if (hasFocus or isAllEmpty()) then begin hasFocus:=true; end; text:=''; beginBySep:=false; beginBySep:=(if ((n=0)) then false (getInterval(0).getStartOffset()<>0)); if (beginBySep) then begin text+=getSeparator(0); end; i:=0; while (i<n) do begin j:=i; if (beginBySep) then begin j:=i+1; end; text+=if ((hasFocus)) then (getInterval(i).getEditingDisplayableString()) (getInterval(i).getEditedDisplayableString()); if (j<_separators.size()) then begin text+=getSeparator(j); end; inc(i); end; result := text; end; function TLyJFormat.isAllEmpty(): boolean; var n : null; i : integer; begin i:=0; while (i<n) do begin if (not getInterval(i).isEmpty()) then begin result := false; end; inc(i); end; result := true; end; function TLyJFormat.getIntValue(offset : integer): int; var interIndex : integer; index : integer; count : integer; sepIndex : integer; begin if (getIntervalsCount()=0) then begin result := 0; end; interIndex:=getIndexIntervalFromOffset(offset); sepIndex:=getIndexSeparatorFromOffset(offset); if (interIndex<>-1) then begin result := getInterval(interIndex).getIntValue(); end else if (sepIndex<>-1) then begin result := getInterval(sepIndex).getIntValue(); end else begin count:=getIntervalsCount(); index:=if (((count-1)>=0)) then (count-1) (0); result := getInterval(index).getIntValue(); end; end; procedure TLyJFormat.setIntValue(offset : integer; value : integer); var interIndex : integer; sepIndex : integer; begin if (getIntervalsCount()=0) then begin exit; end; interIndex:=getIndexIntervalFromOffset(offset); sepIndex:=getIndexSeparatorFromOffset(offset); if (interIndex<>-1) then begin getInterval(interIndex).setIntValue(value); end else if (sepIndex<>-1) then begin getInterval(sepIndex).setIntValue(value); end else begin getInterval(getIntervalsCount()-1).setIntValue(value); end; end; function TLyJFormat.getMinIntValue(offset : integer): int; var interIndex : integer; sepIndex : integer; begin if (getIntervalsCount()=0) then begin result := 0; end; interIndex:=getIndexIntervalFromOffset(offset); sepIndex:=getIndexSeparatorFromOffset(offset); if (interIndex<>-1) then begin result := getInterval(interIndex).getMinimum(); end else if (sepIndex<>-1) then begin result := getInterval(sepIndex).getMinimum(); end else begin result := getInterval(getIntervalsCount()-1).getMinimum(); end; end; function TLyJFormat.getMaxIntValue(offset : integer): int; var interIndex : integer; sepIndex : integer; begin if (getIntervalsCount()=0) then begin result := 0; end; interIndex:=getIndexIntervalFromOffset(offset); sepIndex:=getIndexSeparatorFromOffset(offset); if (interIndex<>-1) then begin result := getInterval(interIndex).getMaximum(); end else if (sepIndex<>-1) then begin result := getInterval(sepIndex).getMaximum(); end else begin result := getInterval(getIntervalsCount()-1).getMaximum(); end; end; procedure TLyJFormat.setValue(value : String); var start : integer; n : null; end : null; i : integer; subVal : null; begin i:=0; while (i<n) do begin start:=getInterval(i).getStartOffset(); end:=getInterval(i).getEndOffset(); begin subVal:=Integer.parseInt(substring2(value,start,end+1)); getInterval(i).setIntValue(subVal); end; begin end; inc(i); end; end; procedure TLyJFormat.clear(); var n : null; i : integer; begin i:=0; while (i<n) do begin getInterval(i).clear(); inc(i); end; end; begin _min:=minimum; _max:=maximum; clear(); end; function TInterval.getMinimum(): int; begin result := _min; end; function TInterval.getMaximum(): int; begin result := _max; end; function TInterval.getMaxCharCount(): int; begin result := String.valueOf(_max).length(); end; procedure TInterval.setOffset(offset : integer); begin _startOffset:=offset; _endOffset:=offset+getMaxCharCount()-1; end; function TInterval.getStartOffset(): int; begin result := _startOffset; end; function TInterval.getEndOffset(): int; begin result := _endOffset; end; procedure TInterval.replaceChar(offset : integer; c : char); begin _content:=substring2(_content,0,offset)+c+substring(_content,offset+1); end; function TInterval.isEmpty(): boolean; var length : null; i : integer; begin i:=0; begin if (_content.charAt(i)<>EMPTY_CHAR) then begin result := false; end; inc(i); end; result := true; end; function TInterval.getContent(): String; begin result := _content; end; function TInterval.getEditingDisplayableString(): String; begin result := _content; end; function TInterval.getEditedDisplayableString(): String; var resu : StringBuffer; contentWithBlank : String; i : integer; tmp : String; value : integer; begin contentWithBlank:=_content.replace(EMPTY_CHAR,' '); tmp:=contentWithBlank.trim(); if (tmp.length()=0) then begin begin tmp:=String.valueOf(getMinimum()); end; begin end; end; value:=LyTools.intFromString(tmp); if (value<getMinimum()) then begin value:=getMinimum(); end; if (value>getMaximum()) then begin value:=getMaximum(); end; begin tmp:=String.valueOf(value); end; begin result := _content; end; ~~~~~5 resu:=######7; i:=tmp.length(); while (i<_content.length()) do begin resu.append('0'); inc(i); end; resu.append(tmp); result := (resu.toString()); end; function TInterval.getMaxCompletedString(): String; var filledWithChar : char; i : integer; tmp : StringBuffer; begin ~~~~~5 tmp:=######7; filledWithChar:='9'; i:=0; begin tmp.setCharAt(i,filledWithChar); inc(i); end; i:=tmp.toString().indexOf(EMPTY_CHAR); if (i=-1) then begin begin Integer.parseInt(tmp.toString()); result := tmp.toString(); end; begin result := ''; end; end; begin tmp.setCharAt(i,filledWithChar); inc(i); end; begin Integer.parseInt(tmp.toString()); result := tmp.toString(); end; begin result := ''; end; end; function TInterval.getMinCompletedString(): String; var i : integer; tmp : StringBuffer; begin ~~~~~5 tmp:=######7; i:=0; begin tmp.setCharAt(i,'0'); inc(i); end; i:=tmp.toString().indexOf(EMPTY_CHAR); if (i=-1) then begin begin Integer.parseInt(tmp.toString()); result := tmp.toString(); end; begin result := ''; end; end; begin tmp.setCharAt(i,'0'); inc(i); end; begin Integer.parseInt(tmp.toString()); result := tmp.toString(); end; begin result := ''; end; end; function TInterval.getIntValue(): int; begin result := Integer.parseInt(getEditedDisplayableString()); end; procedure TInterval.setIntValue(value : integer); var n : null; i : integer; str : String; max : integer; begin if ((value>=_min) and (value<=_max)) then begin str:=String.valueOf(value); max:=getMaxCharCount(); if (str.length()<max) then begin i:=0; while (i<n) do begin str:='0'+str; inc(i); end; end; _content:=str; end; end; function TInterval.getCurrentPossibleValue(): String; begin result := ''; end; procedure TInterval.clear(); var n : null; i : integer; begin _content:=''; i:=0; while (i<n) do begin _content+=String.valueOf(EMPTY_CHAR); inc(i); end; end; end.
(** * $Id: dco.framework.Client.pas 847 2014-05-25 18:16:04Z QXu $ * * 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. *) unit dco.framework.Client; interface uses System.TimeSpan, superobject { An universal object serialization framework with Json support }, dco.rpc.Serializer, dco.transport.Connection, dco.framework.Backlog, dco.framework.Command, dco.framework.Executor; type /// <summary>This class implements a command executor.</summary> TClient = class(TInterfacedObject, IExecutor) private FConnection: IConnection; FSerializer: ISerializer; FBacklog: TBacklog; public constructor Create(const Connection: IConnection; const Serializer: ISerializer; Backlog: TBacklog); destructor Destroy; override; public /// <summary>Exeuctes a command. The current thread is blocked until response is available.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(Command: TCommand): ISuperObject; overload; /// <summary>Exeuctes a command. The current thread is blocked until response is available or timed out.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(Command: TCommand; const Timeout: TTimeSpan): ISuperObject; overload; /// <summary>Sends a notification and then returns immediately without any delivery garantee.</summary> procedure Notify(Command: TCommand); end; implementation uses System.DateUtils, System.SysUtils, Vcl.Forms, Winapi.Windows, dutil.util.concurrent.Result, dco.rpc.Identifier; constructor TClient.Create(const Connection: IConnection; const Serializer: ISerializer; Backlog: TBacklog); begin assert(Connection <> nil); assert(Serializer <> nil); assert(Backlog <> nil); inherited Create; FConnection := Connection; FSerializer := Serializer; FBacklog := Backlog; end; destructor TClient.Destroy; begin FBacklog := nil; FSerializer := nil; FConnection := nil; inherited; end; function TClient.ExecuteAwait(Command: TCommand): ISuperObject; begin Result := ExecuteAwait(Command, TTimeSpan.FromSeconds(30)); end; function TClient.ExecuteAwait(Command: TCommand; const Timeout: TTimeSpan): ISuperObject; var ResultContainer: TResult<ISuperObject>; Id: TIdentifier; Message_: string; Expiration: TDateTime; begin assert(Command <> nil); assert(Command.Type_ = TCommand.TType.REQUEST); assert((Command.Params_ = nil) or (Command.Params_.DataType in [TSuperType.stArray, TSuperType.stObject])); ResultContainer := TResult<ISuperObject>.Create; try Id := FBacklog.Put(ResultContainer); Message_ := FSerializer.EncodeRequest(Command.Method_, Command.Params_, Id); if not FConnection.WriteEnsured(Message_) then begin FBacklog.TakeAndFailResult(Id); assert(ResultContainer.Available); // The result container has an exception now end else begin Expiration := IncMilliSecond(Now, Round(Timeout.TotalMilliseconds)); while not ResultContainer.Available do begin if Expiration < Now then begin FBacklog.TakeAndFailResult(Id); assert(ResultContainer.Available); // The result container has an exception now Break; end; // CAUTION: Waiting for a result in the main thread is *EXTREMELY EXPENSIVE*. If the current execution context is // in the main thread, we will call an idle callback periodically. if GetCurrentThreadId = System.MainThreadId then begin Application.ProcessMessages; end; end; end; Result := ResultContainer.Take; finally ResultContainer.Free; end; end; procedure TClient.Notify(Command: TCommand); var Message_: string; begin assert(Command <> nil); assert(Command.Type_ = TCommand.TType.NOTIFICATION); assert((Command.Params_ = nil) or (Command.Params_.DataType in [TSuperType.stArray, TSuperType.stObject])); Message_ := FSerializer.EncodeNotification(Command.Method_, Command.Params_); FConnection.Write(Message_); end; end.
{------------------------------------ 功能说明:系统服务 创建日期:2008/11/09 作者:wzw 版权:wzw -------------------------------------} unit SysSvc; interface uses SysUtils, Windows, Classes, FactoryIntf, SysSvcIntf, NotifyServiceIntf, ModuleLoaderIntf, ObjRefIntf; type TSysService = class(TObject, IInterface, ISysService) private FRefCount: Integer; protected {IInterface} function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; {ISysService} function Notify: INotifyService; function ModuleLoader: IModuleLoader; function GetObjRef(const IID: TGUID; out ObjRef: IObjRef): Boolean; public // Constructor Create; // Destructor Destroy;override; end; function SysService(const IntfName: string = ''; param: Integer = 0): ISysService; implementation uses SysFactoryMgr; var FSysService: ISysService; FIntfName: string; FParam: Integer; function SysService(const IntfName: string = ''; param: Integer = 0): ISysService; begin FIntfName := IntfName; FParam := param; if FSysService = nil then FSysService := TSysService.Create; Result := FSysService; end; { TSysService } function TSysService._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TSysService._Release: Integer; begin Result := InterlockedDecrement(FRefCount); if Result = 0 then Destroy; end; function TSysService.QueryInterface(const IID: TGUID; out Obj): HResult; var aFactory: TFactory; begin Result := E_NOINTERFACE; if self.GetInterface(IID, Obj) then Result := S_OK else begin if FIntfName = '' then FIntfName := GUIDToString(IID); aFactory := FactoryManager.FindFactory(FIntfName); if Assigned(aFactory) then begin aFactory.prepare(FParam); Result := aFactory.GetIntf(IID, Obj); end; end; end; function TSysService.Notify: INotifyService; begin Result := Self as INotifyService; end; function TSysService.ModuleLoader: IModuleLoader; begin Result := Self as IModuleLoader; end; function TSysService.GetObjRef(const IID: TGUID; out ObjRef: IObjRef): Boolean; var aFactory: TFactory; begin Result := False; if FIntfName = '' then FIntfName := GUIDToString(IID); aFactory := FactoryManager.FindFactory(FIntfName); if Assigned(aFactory) then begin aFactory.prepare(FParam); ObjRef := aFactory.GetObjRef; Result := True; end; end; initialization FSysService := nil; finalization FSysService := nil; end.
unit DAO.ExtratoExpressas; interface uses DAO.Base, Model.ExtratoExpressas, Generics.Collections, System.Classes; type TExtratoExpressasDAO = class(TDAO) private public function Insert(aExtrato: TExtratoExpressas): Boolean; function Update(aExtrato: TExtratoExpressas): Boolean; function Delete(sFiltro: String): Boolean; function FindExtrato(sFiltro: String): TObjectList<TExtratoExpressas>; function FindDatas(): TStringList; end; const TABLENAME = 'tbextratosexpressas'; implementation {TExtratoExpressasDAO} uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TExtratoExpressasDAO.Insert(aExtrato: TExtratoExpressas): Boolean; var sSQL: String; begin Result := False; sSQL := 'INSERT INTO ' + TABLENAME + '(COD_TIPO, NUM_EXTRATO, COD_CLIENTE, DAT_BASE, DAT_INICIO, DAT_TERMINO, COD_CADASTRO, COD_DISTRIBUIDOR, ' + 'NOM_DISTRIBUIDOR, VAL_PERCENTUAL_DISTRIBUIDOR, COD_ENTREGADOR, NOM_ENTREGADOR, VAL_PERCENTUAL_ENTREGADOR, ' + 'VAL_VERBA, QTD_VOLUMES, QTD_VOLUMES_EXTRA, QTD_ENTREGA, QTD_ATRASOS, VAL_VERBA_TOTAL, VAL_VOLUMES_EXTRA, ' + 'VAL_CREDITO, VAL_RESTRICAO, VAL_ABASTECIMENTO, VAL_PENALIDADE_ATRASOS, VAL_DEBITO, VAL_TOTAL_CREDITOS, ' + 'VAL_TOTAL_DEBITOS, VAL_TOTAL_GERAL, DOM_PAGO, DAT_PAGO, DOM_FECHADO, DAT_FECHAMENTO, NOM_EXECUTANTE, DAT_MANUTENCAO) ' + 'VALUES (' + ':TIPO, :EXTRATO, :CLIENTE, :BASE, :INICIO, :TERMINO, :CADASTRO, :CODDISTRIBUIDOR, :NOMDISTRIBUIDOR, ' + ':PERCENTUALDISTRIBUIDOR, :CODENTREGADOR, :NOMENTREGADOR, :PERCENTUALENTREGADOR, :VALVERBA, :VOLUMES, :VOLUMESEXTRA, ' + ':ENTREGA, :ATRASOS, :VERBATOTAL, :VALVOLUMESEXTRA, :VALCREDITO, :VALRESTRICAO, :VALABASTECIMENTO, ' + ':VALPENALIDADEATRASOS, :VALDEBITO, :VALTOTALCREDITOS, :VALTOTALDEBITOS, :VALTOTALGERAL, :PAGO, :DATPAGO, :FECHADO, ' + ':DATFECHAMENTO, :EXECUTANTE, :MANUTENCAO);'; Connection.ExecSQL(sSQL,[aExtrato.Tipo, aExtrato.NumeroExtrato, aExtrato.Cliente, aExtrato.DataBase, aExtrato.DataInicio, aExtrato.DataTermino, aExtrato.Cadastro, aExtrato.Codigodistribuidor, aExtrato.NomeDistribuidor, aExtrato.PercentualDistribuidor, aExtrato.CodigoEntregador, aExtrato.NomeEntregador, aExtrato.PercentualEntregador, aExtrato.Verba, aExtrato.Volumes, aExtrato.VolumesExtra, aExtrato.Entregas, aExtrato.Atrasos, aExtrato.VerbaTotal, aExtrato.ValorVolumesExtra, aExtrato.Creditos, aExtrato.Restricao, aExtrato.Abastecimentos, aExtrato.PenalizadaAtrasos, aExtrato.Debitos, aExtrato.TotalCreaditos, aExtrato.TotalDebitos, aExtrato.TotalGeral, aExtrato.Pago, aExtrato.DataPago, aExtrato.Fechado, aExtrato.DataFechado, aExtrato.Executante, aExtrato.Manutencao], [ftInteger, ftString, ftInteger, ftDate, ftDate, ftDate, ftInteger, ftInteger, ftString, ftFloat, ftInteger, ftString, ftFloat, ftFloat, ftInteger, ftFloat, ftInteger, ftInteger, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftString, ftDate, ftString, ftDate, ftString, ftDateTime]); Result := True; end; function TExtratoExpressasDAO.Update(aExtrato: TExtratoExpressas): Boolean; var sSQL: String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + 'SET ' + 'COD_TIPO = :TIPO, NUM_EXTRATO :EXTRATO:, COD_CLIENTE = :CLIENTE, DAT_BASE = :DATABASE, DAT_INICIO = :INICIO, ' + 'DAT_TERMINO = :TERMINO, COD_CADASTRO = :CADASTRO, COD_DISTRIBUIDOR = :CODDISTRIBUIDOR, ' + 'NOM_DISTRIBUIDOR = :NOMDISTRIBUIDOR, VAL_PERCENTUAL_DISTRIBUIDOR = :PERCENTUALDISTRIBUIDOR, ' + 'COD_ENTREGADOR = :CODENTREGADOR, NOM_ENTREGADOR = :NOMENTREGADOR, VAL_PERCENTUAL_ENTREGADOR = :PERCENTUALENTREGADOR, ' + 'VAL_VERBA = :VALVERBA, QTD_VOLUMES = :VOLUMES, QTD_VOLUMES_EXTRA = :VOLUMESEXTRA, QTD_ENTREGA = :ENTREGA, ' + 'QTD_ATRASOS = :ATRASOS, VAL_VERBA_TOTAL = :VERBATOTAL, VAL_VOLUMES_EXTRA = :VALVOLUMESEXTRA, ' + 'VAL_CREDITO = :VALCREDITO, VAL_RESTRICAO = :VALRESTRICAO, VAL_ABASTECIMENTO = :VALABASTECIMENTO, ' + 'VAL_PENALIDADE_ATRASOS = :VALPENALIDADEATRASOS, VAL_DEBITO = :VALDEBITO, VAL_TOTAL_CREDITOS = :VALTOTALCREDITOS, ' + 'VAL_TOTAL_DEBITOS = :VALTOTALDEBITOS, VAL_TOTAL_GERAL = :VALTOTALGERAL, DOM_PAGO = :PAGO, DAT_PAGO = :DATPAGO, ' + 'DOM_FECHADO = :FECHADO, DAT_FECHAMENTO = :DATFECHAMENTO, NOM_EXECUTANTE = :EXECUTANTE, DAT_MANUTENCAO = :MANUTENCAO ' + 'WHERE COD_TIPO = :TIPO AND COD_CLIENTE = :CLIENTE AND DAT_INICIO = :INICIO AND DAT_TERMINO = :TERMINO AND ' + 'COD_DISTRIBUIDOR = :CODDISTRIBUIDOR AND COD_ENTREGADOR = :CODENTREGADOR;'; Connection.ExecSQL(sSQL,[aExtrato.Tipo, aExtrato.NumeroExtrato, aExtrato.Cliente, aExtrato.DataBase, aExtrato.DataInicio, aExtrato.DataTermino, aExtrato.Cadastro, aExtrato.Codigodistribuidor, aExtrato.NomeDistribuidor, aExtrato.PercentualDistribuidor, aExtrato.CodigoEntregador, aExtrato.NomeEntregador, aExtrato.PercentualEntregador, aExtrato.Verba, aExtrato.Volumes, aExtrato.VolumesExtra, aExtrato.Entregas, aExtrato.Atrasos, aExtrato.VerbaTotal, aExtrato.ValorVolumesExtra, aExtrato.Creditos, aExtrato.Restricao, aExtrato.Abastecimentos, aExtrato.PenalizadaAtrasos, aExtrato.Debitos, aExtrato.TotalCreaditos, aExtrato.TotalDebitos, aExtrato.TotalGeral, aExtrato.Pago, aExtrato.DataPago, aExtrato.Fechado, aExtrato.DataFechado, aExtrato.Executante, aExtrato.Manutencao], [ftInteger, ftString, ftInteger, ftDate, ftDate, ftDate, ftInteger, ftInteger, ftString, ftFloat, ftInteger, ftString, ftFloat, ftFloat, ftInteger, ftFloat, ftInteger, ftInteger, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftFloat, ftString, ftDate, ftString, ftDate, ftString, ftDateTime]); Result := True; end; function TExtratoExpressasDAO.Delete(sFiltro: String): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Result := True; end; function TExtratoExpressasDAO.FindExtrato(sFiltro: String): TObjectList<TExtratoExpressas>; var FDQuery: TFDQuery; Extratos: TObjectList<TExtratoExpressas>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); Extratos := TObjectList<TExtratoExpressas>.Create(); while not FDQuery.Eof do begin Extratos.Add(TExtratoExpressas.Create(FDQuery.FieldByName('COD_TIPO').AsInteger, FDQuery.FieldByName('NUM_EXTRATO').AsString, FDQuery.FieldByName('COD_CLIENTE').AsInteger, FDQuery.FieldByName('DAT_BASE').AsDateTime, FDQuery.FieldByName('DAT_INICIO').AsDateTime, FDQuery.FieldByName('DAT_TERMINO').AsDateTime, FDQuery.FieldByName('COD_CADASTRO').AsInteger, FDQuery.FieldByName('COD_DISTRIBUIDOR').AsInteger, FDQuery.FieldByName('NOM_DISTRIBUIDOR').AsString, FDQuery.FieldByName('VAL_PERCENTUAL_DISTRIBUIDOR').AsFloat, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('NOM_ENTREGADOR').AsString, FDQuery.FieldByName('VAL_PERCENTUAL_ENTREGADOR').AsFloat, FDQuery.FieldByName('VAL_VERBA').AsFloat, FDQuery.FieldByName('QTD_VOLUMES').AsInteger, FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat, FDQuery.FieldByName('QTD_ENTREGA').AsInteger, FDQuery.FieldByName('QTD_ATRASOS').AsInteger, FDQuery.FieldByName('VAL_VERBA_TOTAL').AsFloat, FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat, FDQuery.FieldByName('VAL_CREDITO').AsFloat, FDQuery.FieldByName('VAL_RESTRICAO').AsFloat, FDQuery.FieldByName('VAL_ABASTECIMENTO').AsFloat, FDQuery.FieldByName('VAL_PENALIDADE_ATRASOS').AsFloat, FDQuery.FieldByName('VAL_DEBITO').AsFloat, FDQuery.FieldByName('VAL_TOTAL_CREDITOS').AsFloat, FDQuery.FieldByName('VAL_TOTAL_DEBITOS').AsFloat, FDQuery.FieldByName('VAL_TOTAL_GERAL').AsFloat, FDQuery.FieldByName('DOM_PAGO').AsString, FDQuery.FieldByName('DAT_PAGO').AsDateTime, FDQuery.FieldByName('DOM_FECHADO').AsString, FDQuery.FieldByName('DAT_FECHAMENTO').AsDateTime, FDQuery.FieldByName('NOM_EXECUTANTE').AsString, FDQuery.FieldByName('DAT_MANUTENCAO').AsDateTime)); FDQuery.Next; end; finally FDQuery.Free; end; Result := Extratos; end; function TExtratoExpressasDAO.FindDatas(): TStringList; var FDQuery: TFDQuery; lLista: TStringlist; begin try Result := TStringList.Create(); lLista := TStringlist.Create(); FDQuery := TFDQuery.Create(nil); FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT DISTINCT DAT_PAGO FROM ' + TABLENAME); FDQuery.Open(); if not FDQuery.IsEmpty then begin while not FDQuery.Eof do begin lLista.Add(FDQuery.FieldByName('DAT_PAGO').AsString); FDQuery.Next; end; end; Result.Text := lLista.Text; finally FDQuery.Free; lLista.Free; end; end; end.
// ---------------------------------------------------------------------------- // Unit : PxThread.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2004-10-27 // Version : 1.0 // Description : A thread class. // Changes log ; 2004-10-27 - Initial version. // 2005-09-28 - Removed deps with PxLog unit // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxThread; {$I PxDefines.inc} interface uses Windows, Classes, SysUtils; type // // A thread class // TPxThread = class (TThread) private FTerminationEvent: THandle; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; // // A sleep function that terminates if a specific event is raised // Use this instead of Windows.Sleep() if you want that the wait // process will be stopped if the thread is terminated // // Return values: // True if the sleep process has not been interrupted // False if the sleep process has been interrupted // function Sleep(Timeout: Integer): Boolean; // // Stops the Sleep function. If a Sleep function was waiting // it returns immediately with False. // procedure CancelSleep; // overriden to call CancelSleep; procedure Terminate; // inherited properties property Terminated; end; implementation { TPxThread } { Private declarations } { Public declarations } constructor TPxThread.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FTerminationEvent := CreateEvent(nil, False, False, nil); end; destructor TPxThread.Destroy; begin CancelSleep; CloseHandle(FTerminationEvent); FTerminationEvent := 0; inherited Destroy; end; function TPxThread.Sleep(Timeout: Integer): Boolean; begin Result := WaitForSingleObject(FTerminationEvent, Timeout) = WAIT_TIMEOUT; if not Result then ResetEvent(FTerminationEvent); end; procedure TPxThread.CancelSleep; begin if (FTerminationEvent <> 0) and (FTerminationEvent <> INVALID_HANDLE_VALUE) then SetEvent(FTerminationEvent); end; procedure TPxThread.Terminate; begin inherited Terminate; CancelSleep; end; end.
unit xmplayer_server; {$mode delphi} interface uses windows, Classes, SysUtils, xmplayer_defines, cefuncproc, globals; resourcestring rsXmplayerExeIsMissing = 'xmplayer.exe is missing'; rsFailedCreatingTheAudioPipe = 'Failed creating the audio pipe'; type TXMPlayer=class private finitialized: boolean; fisPlaying: boolean; loadedevent: THandle; audiopipe: THandle; public procedure initialize; procedure playXM(filename: string; noloop: boolean=false); overload; procedure playXM(stream: TStream; noloop: boolean=false); overload; procedure pause; procedure resume; procedure stop; procedure setVolume(v: integer); published property Initialized: boolean read finitialized; property IsPlaying: boolean read fisplaying; end; var xmplayer: TXMPlayer; implementation procedure TXMPlayer.initialize; var uid: string; g: TGUID; i: integer; z: dword; begin if not fileexists(cheatenginedir+'xmplayer.exe') then raise exception.create(rsXmplayerExeIsMissing); //create an unique ID CreateGUID(g); uid:='CEA'+inttohex(g.data1,8)+'_'+inttohex(g.data2,4)+'_'+inttohex(g.data3,4)+'_'; for i:=0 to 7 do uid:=uid+inttohex(g.data4[i],2); loadedevent:=CreateEvent(nil, false, false, pchar(uid)); audiopipe:=CreateNamedPipe(pchar('\\.\pipe\'+uid), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE or PIPE_READMODE_BYTE or PIPE_WAIT, 255, 128*1024, 8, INFINITE, nil); if audiopipe=INVALID_HANDLE_VALUE then raise exception.create( rsFailedCreatingTheAudioPipe); //launches the xmplayer client ShellExecute(0, PChar('open'), PChar(cheatenginedir+'xmplayer.exe'), PChar(uid), PChar(''), SW_SHOW); //wait for it to acquire the pipe WaitForSingleObject(loadedevent, infinite); finitialized:=true; end; procedure TXMPlayer.playXM(filename: string; noloop: boolean); var f: Tfilestream; begin if not initialized then initialize; if FileExists(filename) then begin f:=TFilestream.create(filename, fmOpenRead or fmShareDenyNone); playXM(f, noloop); f.free; end; end; procedure TXMPlayer.playXM(stream: TStream; noloop: boolean=false); var buf: TMemorystream; command: byte; size: integer; w: dword; extraparam: byte; begin if not initialized then initialize; stream.Position:=0; buf:=TMemorystream.create; //setup the message command:=xmplayer_defines.XMPLAYER_PLAYXM; size:=stream.size; buf.WriteBuffer(command, sizeof(command)); buf.WriteBuffer(size, sizeof(size)); //data buf.CopyFrom(stream, stream.size); //send buffer to the audiopipe extraparam:=0; if noloop then extraparam:=extraparam or 8; //no_loop buf.WriteBuffer(extraparam, 1); WriteFile(audiopipe, buf.memory^, buf.size, w, nil); buf.free; fisPlaying:=true; end; procedure TXMPlayer.pause; var command: byte; w: dword; begin if not initialized then initialize; command:=XMPLAYER_PAUSE; writefile(audiopipe, command, 1,w, nil); fisPlaying:=false; end; procedure TXMPlayer.resume; var command: byte; w: dword; begin if not initialized then initialize; command:=XMPLAYER_RESUME; writefile(audiopipe, command, 1,w, nil); fisPlaying:=true; end; procedure TXMPlayer.stop; var command: byte; w: dword; begin if not initialized then initialize; command:=XMPLAYER_STOP; writefile(audiopipe, command, 1,w, nil); fisPlaying:=false; end; procedure TXMPlayer.setVolume(v: integer); var command: packed record command: byte; volume: byte; end; w: dword; begin if not initialized then initialize; command.command:=XMPLAYER_SETVOLUME; command.volume:=v; writefile(audiopipe, command, 2,w, nil); fisPlaying:=false; end; initialization xmplayer:=TXMPlayer.create; end.
unit LoginFormImpl; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxImage, dxGDIPlusClasses, cxGroupBox, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxLabel, cxTextEdit; type TLoginForm = class(TForm) cxLoginData: TcxGroupBox; cxUserName: TcxTextEdit; cxPassword: TcxTextEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; cxOK: TcxButton; cxCancel: TcxButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); strict private procedure LoadSettings(); procedure SaveSettings(); end; implementation uses Registry; {$R *.dfm} { TLoginForm } procedure TLoginForm.FormCreate(Sender: TObject); begin LoadSettings(); end; procedure TLoginForm.FormDestroy(Sender: TObject); begin SaveSettings(); end; procedure TLoginForm.FormShow(Sender: TObject); begin if cxUserName.Text <> '' then cxPassword.SetFocus(); end; procedure TLoginForm.LoadSettings; var reg : TRegistry; begin reg := TRegistry.Create(); try reg.RootKey := HKEY_CURRENT_USER; if not reg.OpenKey('Software\H&H Inc\unipiAdmin', False) then Exit; if reg.ValueExists('LastLogin') then begin cxUserName.Text := reg.ReadString('LastLogin'); end; finally reg.Free(); end; end; procedure TLoginForm.SaveSettings; var reg : TRegistry; begin reg := TRegistry.Create(); try reg.RootKey := HKEY_CURRENT_USER; if not reg.OpenKey('Software\H&H Inc\unipiAdmin', True) then Exit; reg.WriteString('LastLogin', cxUserName.Text); finally reg.Free(); end; end; end.
unit Unit_menu; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, ADODB; type TForm_menu = class(TForm) btn_cadcursos: TBitBtn; btn_cadinstrutores: TBitBtn; btn_cadturmas: TBitBtn; btn_cadalunos: TBitBtn; btn_matriculas: TBitBtn; btn_aulas: TBitBtn; btn_frequencias: TBitBtn; btn_paginstrutores: TBitBtn; btn_relatorios: TBitBtn; btn_controle: TBitBtn; btn_fechar: TBitBtn; ADOQuery_aux: TADOQuery; procedure FormShow(Sender: TObject); procedure btn_controleClick(Sender: TObject); procedure btn_fecharClick(Sender: TObject); procedure btn_cadcursosClick(Sender: TObject); procedure btn_cadinstrutoresClick(Sender: TObject); procedure btn_cadturmasClick(Sender: TObject); procedure btn_cadalunosClick(Sender: TObject); procedure btn_matriculasClick(Sender: TObject); procedure btn_aulasClick(Sender: TObject); procedure btn_frequenciasClick(Sender: TObject); procedure btn_paginstrutoresClick(Sender: TObject); procedure btn_relatoriosClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure permissoes; end; var Form_menu: TForm_menu; implementation uses Unit_logon, Unit_usuarios, Unit_cursos, Unit_instrutores, Unit_turmas, Unit_alunos, Unit_matriculas, Unit_lanca_aulas, Unit_lanca_presenca, Unit_pag_instrutores, Unit_relatorios; {$R *.dfm} { TForm_menu } procedure TForm_menu.permissoes; begin ADOQuery_aux.SQL.Text := ' SELECT COD_FUNCAO FROM PERMISSOES ' + ' WHERE USUARIO = ' + QuotedStr(Form_logon.usuario_logado); ADOQuery_aux.Open; if ADOQuery_aux.Locate('COD_FUNCAO','CADCUR',[loCaseInsensitive]) then btn_cadcursos.Enabled := True else btn_cadcursos.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','CADINS',[loCaseInsensitive]) then btn_cadinstrutores.Enabled := True else btn_cadinstrutores.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','CADTUR',[loCaseInsensitive]) then btn_cadturmas.Enabled := True else btn_cadturmas.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','CADALU',[loCaseInsensitive]) then btn_cadalunos.Enabled := True else btn_cadalunos.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','CADMAT',[loCaseInsensitive]) then btn_matriculas.Enabled := True else btn_matriculas.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','LANAUL',[loCaseInsensitive]) then btn_aulas.Enabled := True else btn_aulas.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','LANFRE',[loCaseInsensitive]) then btn_frequencias.Enabled := True else btn_frequencias.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','PAGINS',[loCaseInsensitive]) then btn_paginstrutores.Enabled := True else btn_paginstrutores.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','RELATO',[loCaseInsensitive]) then btn_relatorios.Enabled := True else btn_relatorios.Enabled := False; if ADOQuery_aux.Locate('COD_FUNCAO','CONTRO',[loCaseInsensitive]) then btn_controle.Enabled := True else btn_controle.Enabled := False; ADOQuery_aux.Close; end; procedure TForm_menu.FormShow(Sender: TObject); begin permissoes; end; procedure TForm_menu.btn_controleClick(Sender: TObject); begin form_usuarios.showmodal; end; procedure TForm_menu.btn_fecharClick(Sender: TObject); begin Application.Terminate; end; procedure TForm_menu.btn_cadcursosClick(Sender: TObject); begin form_cursos.showmodal; end; procedure TForm_menu.btn_cadinstrutoresClick(Sender: TObject); begin Form_instrutores.showmodal; end; procedure TForm_menu.btn_cadturmasClick(Sender: TObject); begin Form_turmas.showmodal; end; procedure TForm_menu.btn_cadalunosClick(Sender: TObject); begin Form_alunos.showmodal; end; procedure TForm_menu.btn_matriculasClick(Sender: TObject); begin form_matriculas.showmodal; end; procedure TForm_menu.btn_aulasClick(Sender: TObject); begin form_lanca_aulas.showmodal; end; procedure TForm_menu.btn_frequenciasClick(Sender: TObject); begin Form_lanca_presenca.showmodal; end; procedure TForm_menu.btn_paginstrutoresClick(Sender: TObject); begin form_pag_instrutores.showmodal; end; procedure TForm_menu.btn_relatoriosClick(Sender: TObject); begin Form_relatorios.showmodal; end; end.
unit circularBuffer; {$MODE Delphi} { Circular buffer for only 1 writer and 1 reader thread Do not use with multiple writers or multiple readers (or at least protect the read and write yourself then) } interface uses {$ifdef darwin}macport,{$endif} {$ifdef windows}windows,{$endif} LCLIntf, syncobjs,classes, sysutils; type TCircularObjectBuffer=class private buffer: array of TObject; ReadIndex: integer; WriteIndex: integer; maxTimeout: integer; hasData: Tevent; hasSpace: TEvent; function getCount: integer; public function Write(o: TObject): boolean; function Read: TObject; constructor create(InitialSize, maxTimeout: integer); destructor destroy; override; property count: integer read getCount; end; implementation constructor TCircularObjectBuffer.create(InitialSize, maxTimeout: integer); begin setlength(buffer,initialsize); ReadIndex:=0; WriteIndex:=0; HasData:=Tevent.create(nil,false,false,''); HasSpace:=Tevent.create(nil,false,true,''); self.maxTimeout:=MaxTimeout; end; destructor TCircularObjectBuffer.destroy; begin setlength(buffer,0); if HasData<>nil then HasData.Free; if HasSpace<>nil then HasSpace.Free; end; function TCircularObjectBuffer.getCount: integer; begin if ReadIndex=WriteIndex then result:=0 else if ReadIndex<WriteIndex then result:=WriteIndex-ReadIndex else result:=(length(buffer)-ReadIndex)+WriteIndex; end; function TCircularObjectBuffer.Write(o: TObject): boolean; var nextwriteindex: integer; begin result:=false; nextwriteindex:=(WriteIndex+1) mod length(buffer); if (nextwriteindex=ReadIndex) then begin //buffer full sleep(5000); if (hasspace.WaitFor(maxTimeout)<>wrsignaled) then exit; end; buffer[WriteIndex]:=o; writeindex:=nextwriteindex; HasData.SetEvent; result:=true; end; function TCircularObjectBuffer.Read: TObject; begin result:=nil; if (readindex=writeindex) and (hasdata.WaitFor(MaxTimeout)<>wrSignaled) then exit; result:=Buffer[ReadIndex]; ReadIndex:=(readindex+1) mod length(buffer); HasSpace.SetEvent; end; end.
unit qplugins_fmx_messages; interface {$HPPEMIT '#pragma link "qplugins_vcl_messages"'} // 判断宿主程序是否是VCL程序 function HostIsVCL: Boolean; const IID_FMX_MESSAGEHOST: TGuid = '{06132435-6E52-44C7-9128-AF14BA92B5CB}'; implementation uses classes, sysutils, syncobjs, qstring, qplugins, qplugins_base, qplugins_params, qplugins_messages, qdac_postqueue, system.messaging, fmx.types, fmx.platform, fmx.controls, fmx.forms, fmx.canvas.d2d {$IFDEF MSWINDOWS}, fmx.platform.Win, windows, messages{$ENDIF}; resourcestring SMsgFilterRootMissed = '请求的服务路径 /Services/Messages 未注册'; type TQFMXMessageService = class(TQService, IQMessageService, IQNotify, IFMXApplicationService) private FAppReadyId: Cardinal; FTerminating: Boolean; FOldAppService: IFMXApplicationService; function HostService: IQHostService; public constructor Create(const AId: TGuid; AName: QStringW); override; procedure Notify(const AId: Cardinal; AParams: IQParams; var AFireNext: Boolean); stdcall; function Accept(AInstance: HMODULE): Boolean; virtual; stdcall; procedure HandleMessage(var AMsg: TMsg; var AHandled: Boolean); overload; stdcall; procedure HandleIdle; virtual; stdcall; function IsShowModal: Boolean; stdcall; procedure Run; function Running: Boolean; function HandleMessage: Boolean; overload; procedure WaitMessage; function GetDefaultTitle: string; function GetTitle: string; procedure SetTitle(const Value: string); /// <summary>Gets a string representing the version number of the application</summary> function GetVersionString: string; procedure Terminate; function Terminating: Boolean; procedure RestoreHook; end; TQHostMessageService = class(TQService, IQHostService, IQNotify, IFMXApplicationService) protected FTerminating: Boolean; FRunning: Boolean; FOldAppService: IFMXApplicationService; function IsFilterShowModal: Boolean; procedure Notify(const AId: Cardinal; AParams: IQParams; var AFireNext: Boolean); stdcall; function IsShareForm(AFormClass: Pointer): Boolean; public constructor Create; override; destructor Destroy; override; // IQHostService function GetAppWnd: HWND; // IFMXApplicationService procedure Run; function Running: Boolean; function HandleMessage: Boolean; procedure WaitMessage; function GetDefaultTitle: string; function GetTitle: string; procedure SetTitle(const Value: string); /// <summary>Gets a string representing the version number of the application</summary> function GetVersionString: string; procedure Terminate; function Terminating: Boolean; function Terminated: Boolean; end; var MsgFilters: IQService; _MsgFilter: TQFMXMessageService; NID_APPREADY: Cardinal; {$IFDEF MSWINDOWS} function FindAppHandle: HWND; var AService: IQHostService; begin // 如果主程序使用 IQHostService,则使用该服务,如果未使用,则返回0 // 如果要在子程序使用窗体服务,则主程序必需实现 IQHostService if Supports(PluginsManager, IQHostService, AService) then begin Result := AService.GetAppWnd; if MainInstance = 0 then MainInstance := (AService as IQService).GetOwnerInstance; end else Result := 0; end; {$ENDIF} function HostIsVCL: Boolean; {$IFDEF MSWINDOWS} var AppWnd: HWND; AClassName: array [0 .. 255] of WideChar; begin AppWnd := FindAppHandle; windows.GetClassNameW(AppWnd, AClassName, 255); Result := StrCmpW(@AClassName[0], VCLAppClass, True) = 0; end; {$ELSE} // 移动平台宿主不可能是VCL begin Result := false; end; {$ENDIF} function QueryAppState: TApplicationState; var AHostService: IQHostService; begin Result := TApplicationState.None; if Supports(PluginsManager, IQHostService, AHostService) then begin if not AHostService.Terminating then Result := TApplicationState.Running else Result := TApplicationState.Terminating; end; end; procedure ProcessAppMsg(var AMsg: TMsg; var AHandled: Boolean); var AIsUnicode: Boolean; begin AIsUnicode := (AMsg.HWND = 0) or IsWindowUnicode(AMsg.HWND); TranslateMessage(AMsg); if AIsUnicode then DispatchMessageW(AMsg) else DispatchMessageA(AMsg); AHandled := True; end; function FilterRoot: IQServices; var AMgr: IQNotifyManager; begin Result := PluginsManager.Services.ByPath('Messages') as IQServices; if not Assigned(Result) then begin Result := TQServices.Create(NewId, 'Messages'); PluginsManager.Services.Add(Result as IQService); AMgr := (PluginsManager as IQNotifyManager); AMgr.Send(AMgr.IdByName(NAME_APPREADY), NIL); end; end; function ProcessFMXAppMsg(var AIsQuit: Boolean): Boolean; var AWndInstance: HMODULE; AFilters: IQServices; AFilter: IQMessageService; I: Integer; AMsg: TMsg; procedure DebugWnd(AWnd: HWND); var AClassName: array [0 .. 255] of WideChar; AText: array [0 .. 255] of WideChar; S: String; begin if AWnd <> 0 then begin GetClassName(AWnd, @AClassName, 255); GetWindowText(AWnd, @AText, 255); S := 'Class:' + PChar(@AClassName) + ',Text=' + PChar(@AText); OutputDebugString(PChar(S)); end; end; begin Result := false; AIsQuit := false; if PeekMessage(AMsg, 0, 0, 0, PM_REMOVE) then begin if AMsg.message = WM_QUIT then begin Result := True; AIsQuit := True; Exit; end else begin AFilters := FilterRoot; if AMsg.HWND = 0 then AWndInstance := MainInstance else AWndInstance := GetClassLong(AMsg.HWND, GCL_HMODULE); if AWndInstance <> HInstance then begin // DebugWnd(AMsg.HWND); for I := 0 to AFilters.Count - 1 do begin AFilter := AFilters[I] as IQMessageService; if AFilter.Accept(AWndInstance) then begin Result := True; AFilter.HandleMessage(AMsg, Result); if Result then Break; end; end; end; end; if not Result then ProcessAppMsg(AMsg, Result); ProcessAsynCalls; end; end; function IsFMXModalShowing: Boolean; var AForm: TCommonCustomForm; begin AForm := Screen.ActiveForm; if Assigned(AForm) then Result := TFmxFormState.Modal in AForm.FormState else Result := false; end; function FormInstance: HMODULE; type TTestMethod = procedure of object; TJmpInst = packed record Inst: Word; Offset: PPointer; end; PJmpInst = ^TJmpInst; var AMethod: TTestMethod; AJump: PJmpInst; AForm: TFormFactor; begin AForm := TFormFactor.Create; try AMethod := AForm.AdjustToScreenSize; AJump := PJmpInst(TMethod(AMethod).Code); if AJump.Inst = $25FF then Result := FindHInstance(AJump.Offset^) else // 不是跳转,则说明是自己 Result := HInstance; finally FreeAndNil(AForm); end; end; function IsSharePackage: Boolean; var AService: IQHostService; begin // 如果主程序使用 IQHostService,则使用该服务,如果未使用,则返回0 // 如果要在子程序使用窗体服务,则主程序必需实现 IQHostService if Supports(PluginsManager, IQHostService, AService) then begin Result := AService.IsShareForm(TForm); end else Result := false; end; { TQFMXMessageService } function TQFMXMessageService.Accept(AInstance: HMODULE): Boolean; begin Result := AInstance = HInstance; end; constructor TQFMXMessageService.Create(const AId: TGuid; AName: QStringW); begin inherited Create(AId, AName); RegisterApplicationHWNDProc(FindAppHandle); FOldAppService := TPlatformServices.Current.GetPlatformService (IFMXApplicationService) as IFMXApplicationService; TPlatformServices.Current.RemovePlatformService(IFMXApplicationService); TPlatformServices.Current.AddPlatformService(IFMXApplicationService, Self); Application.ApplicationStateQuery := QueryAppState; end; function TQFMXMessageService.GetDefaultTitle: string; begin Result := FOldAppService.DefaultTitle; end; function TQFMXMessageService.GetTitle: string; {$IFDEF MSWINDOWS} var AHandle: HWND; AHostSvc: IQHostService; {$ENDIF} begin if HInstance = MainInstance then Result := FOldAppService.Title else begin {$IFDEF MSWINDOWS} AHostSvc := HostService; if Assigned(AHostSvc) then begin AHandle := AHostSvc.GetAppWnd; SetLength(Result, GetWindowTextLength(AHandle)); if Length(Result) > 0 then GetWindowText(AHandle, PChar(Result), Length(Result)); end else SetLength(Result, 0); {$ENDIF} end; end; function TQFMXMessageService.GetVersionString: string; begin Result := FOldAppService.AppVersion; end; procedure TQFMXMessageService.HandleIdle; begin TMessageManager.DefaultManager.SendMessage(Self, TIdleMessage.Create); end; function TQFMXMessageService.HandleMessage: Boolean; begin Result := ProcessFMXAppMsg(FTerminating); end; function TQFMXMessageService.HostService: IQHostService; var ARoot: IQServices; I: Integer; begin if not Supports(Self, IQHostService, Result) then begin ARoot := FilterRoot; for I := 0 to ARoot.Count - 1 do begin if Supports(ARoot[I], IQHostService, Result) then Exit; end; end; end; procedure TQFMXMessageService.HandleMessage(var AMsg: TMsg; var AHandled: Boolean); begin ProcessAppMsg(AMsg, AHandled); FTerminating := AMsg.message = WM_QUIT; end; function TQFMXMessageService.IsShowModal: Boolean; begin Result := IsFMXModalShowing; end; procedure TQFMXMessageService.Notify(const AId: Cardinal; AParams: IQParams; var AFireNext: Boolean); begin if AId = FAppReadyId then RegisterApplicationHWNDProc(FindAppHandle); end; procedure TQFMXMessageService.RestoreHook; begin Terminate; TPlatformServices.Current.RemovePlatformService(IFMXApplicationService); TPlatformServices.Current.AddPlatformService(IFMXApplicationService, FOldAppService); RegisterApplicationHWNDProc(nil); end; procedure TQFMXMessageService.Run; begin FOldAppService.Run; end; function TQFMXMessageService.Running: Boolean; begin Result := FOldAppService.Running; end; procedure TQFMXMessageService.SetTitle(const Value: string); var AHostSvc: IQHostService; begin if MainInstance = HInstance then FOldAppService.Title := Value else begin AHostSvc := HostService; if Assigned(AHostSvc) then SetWindowText(AHostSvc.GetAppWnd, Value); end; end; procedure TQFMXMessageService.Terminate; begin FOldAppService.Terminate; end; function TQFMXMessageService.Terminating: Boolean; begin Result := FTerminating or FOldAppService.Terminating; end; procedure TQFMXMessageService.WaitMessage; begin FOldAppService.WaitMessage; end; { TQHostMessageService } constructor TQHostMessageService.Create; begin inherited Create(IID_FMX_MESSAGEHOST, 'MessageHost.FMX'); FOldAppService := TPlatformServices.Current.GetPlatformService (IFMXApplicationService) as IFMXApplicationService; TPlatformServices.Current.RemovePlatformService(IFMXApplicationService); TPlatformServices.Current.AddPlatformService(IFMXApplicationService, Self); end; destructor TQHostMessageService.Destroy; begin inherited; end; function TQHostMessageService.GetAppWnd: HWND; begin Result := ApplicationHWND; end; function TQHostMessageService.GetDefaultTitle: string; begin Result := FOldAppService.DefaultTitle; end; function TQHostMessageService.GetTitle: string; begin Result := FOldAppService.Title; end; function TQHostMessageService.GetVersionString: string; begin Result := FOldAppService.AppVersion; end; function TQHostMessageService.HandleMessage: Boolean; begin Result := ProcessFMXAppMsg(FTerminating); end; function TQHostMessageService.IsFilterShowModal: Boolean; var AFilters: IQServices; AFilter: IQMessageService; I: Integer; begin AFilters := FilterRoot; Result := false; for I := 0 to AFilters.Count - 1 do begin AFilter := AFilters[I] as IQMessageService; Result := AFilter.IsShowModal; if Result then Break; end; end; function TQHostMessageService.IsShareForm(AFormClass: Pointer): Boolean; function FormInstance: HMODULE; type TTestMethod = procedure of object; TJmpInst = packed record Inst: Word; Offset: PPointer; end; PJmpInst = ^TJmpInst; var AMethod: TTestMethod; AJump: PJmpInst; AForm: TFormFactor; begin AForm := TFormFactor.Create; try AMethod := AForm.AdjustToScreenSize; AJump := PJmpInst(TMethod(AMethod).Code); if AJump.Inst = $25FF then Result := FindHInstance(AJump.Offset^) else // 不是跳转,则说明是自己 Result := HInstance; finally FreeAndNil(AForm); end; end; begin Result := true; // FormInstance = AFormClassInstance; end; procedure TQHostMessageService.Notify(const AId: Cardinal; AParams: IQParams; var AFireNext: Boolean); begin // Do Nothing end; procedure TQHostMessageService.Run; begin FOldAppService.Run; end; function TQHostMessageService.Running: Boolean; begin Result := FOldAppService.Running; end; procedure TQHostMessageService.SetTitle(const Value: string); begin FOldAppService.Title := Value; end; procedure TQHostMessageService.Terminate; begin FTerminating := True; FOldAppService.Terminate; end; function TQHostMessageService.Terminated: Boolean; begin Result := Application.Terminated; end; function TQHostMessageService.Terminating: Boolean; begin Result := FTerminating or FOldAppService.Terminating; end; procedure TQHostMessageService.WaitMessage; begin FOldAppService.WaitMessage; end; function EnumFMXAppWnd(AWnd: HWND; AParam: LParam): Boolean; stdcall; var AClassName: array [0 .. 255] of WideChar; begin Result := True; windows.GetClassName(AWnd, @AClassName, 256); if StrCmpW(@AClassName, FMXAppClass, True) = 0 then begin if GetClassLong(AWnd, GWL_HINSTANCE) = HInstance then begin PNativeUInt(AParam)^ := AWnd; Result := false; end; end; end; procedure HideFMXAppWindow; var FmxAppWnd: HWND; begin FmxAppWnd := 0; EnumThreadWindows(GetCurrentThreadId, @EnumFMXAppWnd, LParam(@FmxAppWnd)); if (FmxAppWnd <> 0) and (windows.IsWindowVisible(FmxAppWnd)) then ShowWindow(FmxAppWnd, SW_HIDE); end; procedure RegisterMessageService; var AppHandle: HWND; ANotifyMgr: IQNotifyManager; begin if not IsSharePackage then begin AppHandle := FindAppHandle; _MsgFilter := TQFMXMessageService.Create(NewId, 'MessageFilter.FMX'); RegisterServices('Services/Messages', [_MsgFilter]); if AppHandle <> 0 then begin if HostIsVCL or IsLibrary then HideFMXAppWindow; end else begin ANotifyMgr := (PluginsManager as IQNotifyManager); NID_APPREADY := ANotifyMgr.IdByName(NAME_APPREADY); ANotifyMgr.Subscribe(NID_APPREADY, _MsgFilter as IQNotify); end; end else _MsgFilter := nil; end; procedure UnregisterMessageService; begin if Assigned(_MsgFilter) then begin (PluginsManager as IQNotifyManager).Unsubscribe(NID_APPREADY, _MsgFilter as IQNotify); _MsgFilter.RestoreHook; _MsgFilter.GetParent.Remove(_MsgFilter as IQService); _MsgFilter := nil; end; end; initialization if HInstance <> MainInstance then begin MsgFilters := nil; RegisterMessageService; end else begin FilterRoot; MsgFilters := TQHostMessageService.Create; end; finalization if HInstance <> MainInstance then begin UnregisterMessageService; end else MsgFilters := nil; end.
unit Vector2iComparatorTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type TVector2iComparatorTest = class(TVectorBaseTestCase) private nt2i1, nt2i2, nt2i3, nt2i4: TNativeBZVector2i; at2i1, at2i2, at2i3, at2i4: TBZVector2i; protected procedure Setup; override; published procedure TestCompare; procedure TestCompareFalse; procedure TestOpAdd; procedure TestOpSub; procedure TestOpDiv; procedure TestOpMul; procedure TestOpMulSingle; procedure TestOpAddInteger; procedure TestOpSubInteger; procedure TestOpDivInteger; procedure TestOpMulInteger; procedure TestOpDivideSingle; procedure TestOpNegate; procedure TestEquals; procedure TestNotEquals; procedure TestMod; procedure TestMin; procedure TestMax; procedure TestMinInteger; procedure TestMaxInteger; procedure TestClamp; procedure TestClampInteger; procedure TestMulAdd; procedure TestMulDiv; procedure TestLength; procedure TestLengthSquare; procedure TestDistance; procedure TestDistanceSquare; procedure TestNormalize; procedure TestDotProduct; procedure TestAngleBetween; procedure TestAngleCosine; procedure TestAbs; end; implementation procedure TVector2iComparatorTest.Setup; begin inherited Setup; at2i1.Create(2,6); at2i2.Create(1,1); at2i4.Create(8,8); nt2i1.V := at2i1.V; nt2i2.V := at2i2.V; nt2i4.V := at2i4.V; end; procedure TVector2iComparatorTest.TestCompare; begin AssertTrue('Test Values do not match'+nt2i1.ToString+' --> '+at2i1.ToString, Compare(nt2i1,at2i1)); end; procedure TVector2iComparatorTest.TestCompareFalse; begin AssertFalse('Test Values do not match'+nt2i1.ToString+' --> '+at2i2.ToString, Compare(nt2i1,at2i2)); end; procedure TVector2iComparatorTest.TestOpAdd; begin nt2i3 := nt2i1 + nt2i2; at2i3 := at2i1 + at2i2; AssertTrue('Vector2i: Op Add does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpSub; begin nt2i3 := nt2i1 - nt2i2; at2i3 := at2i1 - at2i2; AssertTrue('Vector2i: Op Sub does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpDiv; begin nt2i3 := nt2i1 div nt2i2; at2i3 := at2i1 div at2i2; AssertTrue('Vector2i: Op Div does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpMul; begin nt2i3 := nt2i1 * nt2i2; at2i3 := at2i1 * at2i2; AssertTrue('Vector2i: Op Mul does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpMulSingle; begin nt2i3 := nt2i1 * 2.3; at2i3 := at2i1 * 2.3; AssertTrue('Vector2i: Op Mul Single does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpAddInteger; begin nt2i3 := nt2i1 + 2; at2i3 := at2i1 + 2; AssertTrue('Vector2i: Op Add Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpSubInteger; begin nt2i3 := nt2i1 - 2; at2i3 := at2i1 - 2; AssertTrue('Vector2i: Op Sub Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpDivInteger; begin nt2i3 := nt2i1 div 2; at2i3 := at2i1 div 2; AssertTrue('Vector2i: Op Div Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpMulInteger; begin nt2i3 := nt2i1 div 2; at2i3 := at2i1 div 2; AssertTrue('Vector2i: Op Mul Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpDivideSingle; begin nt2i3 := nt2i1 / 2.3; at2i3 := at2i1 / 2.3; AssertTrue('Vector2i: Op Divide Single does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestOpNegate; begin nt2i3 := -nt2i1; at2i3 := -at2i1; AssertTrue('Vector2i: Op Divide Single does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestEquals; begin nb := nt2i1 = nt2i1; ab := at2i1 = at2i1; AssertTrue('Vector2i = does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := nt2i1 = nt2i2; ab := at2i1 = at2i2; AssertTrue('Vector2i = does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; procedure TVector2iComparatorTest.TestNotEquals; begin nb := nt2i1 <> nt2i1; ab := at2i1 <> at2i1; AssertTrue('Vector2i <> does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := nt2i1 <> nt2i2; ab := at2i1 <> at2i2; AssertTrue('Vector2i <> does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; procedure TVector2iComparatorTest.TestMod; begin nt2i3 := nt2i1 mod nt2i2; at2i3 := at2i1 mod at2i2; AssertTrue('Vector2i: Mod does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMin; begin nt2i3 := nt2i1.Min(nt2i2); at2i3 := at2i1.Min(at2i2); AssertTrue('Vector2i: Min does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMax; begin nt2i3 := nt2i1.Max(nt2i2); at2i3 := at2i1.Max(at2i2); AssertTrue('Vector2i: Max does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMinInteger; begin nt2i3 := nt2i1.Min(2); at2i3 := at2i1.Min(2); AssertTrue('Vector2i: Min Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMaxInteger; begin nt2i3 := nt2i1.Max(2); at2i3 := at2i1.Max(2); AssertTrue('Vector2i: Max Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestClamp; begin nt2i3 := nt2i1.Clamp(nt2i2,nt2i4); at2i3 := at2i1.Clamp(at2i2,at2i4); AssertTrue('Vector2i: Clamp does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestClampInteger; begin nt2i3 := nt2i1.Clamp(1,5); at2i3 := at2i1.Clamp(1,5); AssertTrue('Vector2i: Clamp Integer does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMulAdd; begin nt2i3 := nt2i1.MulAdd(nt2i2,nt2i4); at2i3 := at2i1.MulAdd(at2i2,at2i4); AssertTrue('Vector2i: MulAdd does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestMulDiv; begin nt2i3 := nt2i1.MulDiv(nt2i2,nt2i4); at2i3 := at2i1.MulDiv(at2i2,at2i4); AssertTrue('Vector2i: MulDiv does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; procedure TVector2iComparatorTest.TestLength; begin fs1 := nt2i1.Length; fs2 := at2i1.Length; AssertTrue('Vector2i Lengths do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestLengthSquare; begin fs1 := nt2i1.LengthSquare; fs2 := at2i1.LengthSquare; AssertTrue('Vector2i Length Squared do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestDistance; begin fs1 := nt2i1.Distance(nt2i2); fs2 := at2i1.Distance(at2i2); AssertTrue('Vector2i Distances do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestDistanceSquare; begin fs1 := nt2i1.DistanceSquare(nt2i2); fs2 := at2i1.DistanceSquare(at2i2); AssertTrue('Vector2i Distance Squared do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestNormalize; begin ntt1 := nt2i1.Normalize; vtt1 := at2i1.Normalize; AssertTrue('Vector2iHelper Normalize do not match : '+ntt1.ToString+' --> '+vtt1.ToString, Compare(ntt1,vtt1)); end; procedure TVector2iComparatorTest.TestDotProduct; begin fs1 := nt2i1.DotProduct(nt2i2); fs2 := at2i1.DotProduct(at2i2); AssertTrue('Vector2i DotProducts do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestAngleBetween; begin fs1 := nt2i1.AngleBetween(nt2i2,nt2i4); fs2 := at2i1.AngleBetween(at2i2,at2i4); AssertTrue('Vector2i AngleBetweens do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestAngleCosine; begin fs1 := nt2i1.AngleCosine(nt2i2); fs2 := at2i1.AngleCosine(at2i2); AssertTrue('Vector2i AngleCosines do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2,1e-4)); end; procedure TVector2iComparatorTest.TestAbs; begin nt2i3 := nt2i1.Abs; at2i3 := at2i1.Abs; AssertTrue('Vector2i: Abs does not match'+nt2i3.ToString+' --> '+at2i3.ToString, Compare(nt2i3,at2i3)); end; initialization RegisterTest(REPORT_GROUP_VECTOR2I, TVector2iComparatorTest); end.
unit UPessoas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TFPessoas = class(TForm) LblLocalizarUsuarios: TLabel; EdtLocalizarPessoas: TEdit; G1Grid: TDBGrid; PainelUsuarios1: TPanel; PainelUsuarios2: TPanel; BtnIncluir: TBitBtn; BtnAlterar: TBitBtn; BtnExcluir: TBitBtn; BtnSair: TButton; procedure BtnSairClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnIncluirClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BtnAlterarClick(Sender: TObject); procedure BtnExcluirClick(Sender: TObject); procedure G1GridDblClick(Sender: TObject); procedure EdtLocalizarPessoasKeyPress(Sender: TObject; var Key: Char); procedure btnMostrarTodosClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FPessoas: TFPessoas; implementation {$R *.dfm} uses UDM, UCadProduto, UCadPessoa;{units que podem ser acessadas e utilizadas} procedure TFPessoas.FormCreate(Sender: TObject);//ao abrir tela de produtos begin if dm.sql_pessoa.Params.ParamByName('TIPO_PESSOA').AsString = 'C' then begin Self.Caption:='Cadastro de Cliente'; DM.sql_pessoaDOCUMENTO_PESSOA.EditMask:='999.999.999-99;0;'; G1Grid.Columns.Items[2].Title.Caption := 'CPF'; end else begin Self.Caption:='Cadastro de Fornecedor'; DM.sql_pessoaDOCUMENTO_PESSOA.EditMask:='99.999.999/9999-99;0;'; G1Grid.Columns.Items[2].Title.Caption := 'CNPJ'; end; end; procedure TFPessoas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=VK_ESCAPE then //se a tecla ESC for pressionada então Close; end; procedure TFPessoas.G1GridDblClick(Sender: TObject); begin BtnAlterar.Click; end; //fim procedure TFPessoas.BtnAlterarClick(Sender: TObject); begin if not DM.sql_pessoa.IsEmpty then begin Self.Visible :=False; DM.sql_pessoa.Edit; dm.CriarFormulario(TFCadPessoas,FCadPessoas); Self.Visible:=True; end; end; procedure TFPessoas.BtnExcluirClick(Sender: TObject); begin if not DM.sql_pessoa.IsEmpty then begin if dm.MessageDlgDefault('Confirmar a Exclusão',mtInformation,[mbYes,mbNo],0)=mrYes then //se ao informar a mensagem 'Confirmar a Exclusão' for igual a Yes então begin DM.sql_pessoa.Delete; ShowMessage('Informações Excluídas com Sucesso!'); end; end; end; procedure TFPessoas.BtnIncluirClick(Sender: TObject); begin //Firebird Self.Visible :=False; DM.sql_pessoa.Active := True; DM.sql_pessoa.Insert; DM.sql_pessoaTIPO_PESSOA.AsString := DM.sql_pessoa.Params[0].AsString; dm.CriarFormulario(TFCadPessoas,FCadPessoas); Self.Visible:=True; end; procedure TFPessoas.btnMostrarTodosClick(Sender: TObject); begin {dm.sql_pessoa.Close; DM.sql_pessoa.SQL.Clear; dm.sql_pessoa.SQL.Add('select * from pessoas'); //dm.sql_pessoaTIPO_PESSOA.AsString := 'C'; Self.Caption:='Clientes e Fornecedores'; dm.sql_pessoa.Open; } end; procedure TFPessoas.BtnSairClick(Sender: TObject); begin Close; end; procedure TFPessoas.EdtLocalizarPessoasKeyPress(Sender: TObject; var Key: Char); begin if Key =#13 then begin if dm.sql_pessoa.Params.ParamByName('TIPO_PESSOA').AsString = 'C' then begin DM.sql_pessoa.Close; DM.sql_pessoa.SQL.Clear; DM.sql_pessoa.SQL.Add('select * from pessoas'); DM.sql_pessoa.SQL.Add('where TIPO_PESSOA= :TIPO_PESSOA AND NOME_PESSOA LIKE :NOME_PESSOA'); DM.sql_pessoa.SQL.Add('ORDER BY NOME_PESSOA'); dm.sql_pessoa.Params.ParamByName('TIPO_PESSOA').AsString := 'C'; DM.sql_pessoa.Params.ParamByName('NOME_PESSOA').AsString := EdtLocalizarPessoas.Text+'%'; Self.Caption:='Cadastro de Cliente'; DM.sql_pessoa.Open; end else begin DM.sql_pessoa.Close; DM.sql_pessoa.SQL.Clear; DM.sql_pessoa.SQL.Add('select * from pessoas'); DM.sql_pessoa.SQL.Add('where TIPO_PESSOA= :TIPO_PESSOA AND NOME_PESSOA LIKE :NOME_PESSOA'); DM.sql_pessoa.SQL.Add('ORDER BY NOME_PESSOA'); dm.sql_pessoa.Params.ParamByName('TIPO_PESSOA').AsString := 'F'; DM.sql_pessoa.Params.ParamByName('NOME_PESSOA').AsString := EdtLocalizarPessoas.Text+'%'; Self.Caption:='Cadastro de Fornecedor'; DM.sql_pessoa.Open; end; end; end; end.
unit Unit_matriculas; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, ADODB; type TForm_matriculas = class(TForm) btn_novo: TBitBtn; btn_salvar: TBitBtn; btn_alterar: TBitBtn; btn_cancelar: TBitBtn; btn_excluir: TBitBtn; btn_fechar: TBitBtn; edt_aluno: TEdit; edt_turma: TEdit; Label1: TLabel; Label2: TLabel; ADOQuery_aux: TADOQuery; btn_aluno: TBitBtn; btn_turma: TBitBtn; btn_localizar: TBitBtn; procedure btn_alunoClick(Sender: TObject); procedure btn_turmaClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btn_novoClick(Sender: TObject); procedure btn_salvarClick(Sender: TObject); procedure btn_alterarClick(Sender: TObject); procedure btn_cancelarClick(Sender: TObject); procedure btn_excluirClick(Sender: TObject); procedure btn_fecharClick(Sender: TObject); procedure btn_localizarClick(Sender: TObject); private { Private declarations } public { Public declarations } pk_aluno, pk_turma, operacao, cod_aluno, cod_turma : string; procedure desabilita_salvar(Sender: TObject); procedure habilita_salvar(Sender: TObject); procedure bloqueia_campos; procedure libera_campos; procedure limpa_campos; end; var Form_matriculas: TForm_matriculas; implementation uses Unit_logon, Unit_pesquisa, Unit_pesquisa_turmas; {$R *.dfm} { TForm_matriculas } procedure TForm_matriculas.bloqueia_campos; var i : integer; begin for i := 1 to Form_matriculas.ComponentCount -1 do begin if Form_matriculas.Components[i] is TEdit then begin (Form_matriculas.Components[i] as TEdit).Enabled := False; (Form_matriculas.Components[i] as TEdit).Color := clInfoBk; end; end; end; procedure TForm_matriculas.desabilita_salvar(Sender: TObject); begin btn_novo.Enabled := True; btn_salvar.Enabled := False; btn_alterar.Enabled := True; btn_cancelar.Enabled := False; btn_excluir.Enabled := True; btn_aluno.Enabled := False; btn_turma.Enabled := False; if Sender = btn_novo then operacao := 'novo' else if Sender = btn_salvar then operacao := 'salvar' else if Sender = btn_alterar then operacao := 'alterar' else if Sender = btn_cancelar then operacao := 'cancelar' else if Sender = btn_excluir then operacao := 'excluir'; end; procedure TForm_matriculas.habilita_salvar(Sender: TObject); begin btn_novo.Enabled := False; btn_salvar.Enabled := True; btn_alterar.Enabled := False; btn_cancelar.Enabled := True; btn_excluir.Enabled := False; btn_aluno.Enabled := True; btn_turma.Enabled := True; if Sender = btn_novo then operacao := 'novo' else if Sender = btn_salvar then operacao := 'salvar' else if Sender = btn_alterar then operacao := 'alterar' else if Sender = btn_cancelar then operacao := 'cancelar' else if Sender = btn_excluir then operacao := 'excluir'; end; procedure TForm_matriculas.libera_campos; var i : integer; nome_obj : string; begin for i := 1 to Form_matriculas.ComponentCount -1 do begin if Form_matriculas.Components[i] is TEdit then begin nome_obj := (Form_matriculas.Components[i] as TEdit).Name; if (nome_obj <> 'edt_aluno') and (nome_obj <> 'edt_turma') then begin (Form_matriculas.Components[i] as TEdit).Enabled := True; (Form_matriculas.Components[i] as TEdit).Color := clWindow; end; end; end; end; procedure TForm_matriculas.limpa_campos; var i : integer; begin for i := 1 to Form_matriculas.ComponentCount -1 do begin if Form_matriculas.Components[i] is TEdit then (Form_matriculas.Components[i] as TEdit).Clear; end; end; procedure TForm_matriculas.btn_alunoClick(Sender: TObject); begin edt_aluno.Clear; Form_pesquisa.sql_pesquisa:='SELECT * FROM ALUNOS '; Form_pesquisa.ShowModal; if Form_pesquisa.chave <> '' then begin cod_aluno := Form_pesquisa.chave; ADOQuery_aux.SQL.Text := ' SELECT NOME FROM ALUNOS '+ ' WHERE COD_ALUNO = ' + cod_aluno; ADOQuery_aux.Open; edt_aluno.Text := ADOQuery_aux.fieldbyname('NOME').AsString; end; end; procedure TForm_matriculas.btn_turmaClick(Sender: TObject); begin edt_turma.Clear; Form_pesquisa_turmas.ShowModal; if Form_pesquisa_turmas.chave <> '' then begin cod_turma := Form_pesquisa_turmas.chave; edt_turma.Text := cod_turma; end; end; procedure TForm_matriculas.FormShow(Sender: TObject); begin pk_aluno := ''; pk_turma := ''; cod_aluno := ''; cod_turma := ''; operacao := ''; limpa_campos; bloqueia_campos; desabilita_salvar(sender); end; procedure TForm_matriculas.btn_novoClick(Sender: TObject); begin libera_campos; limpa_campos; pk_aluno := ''; pk_turma := ''; cod_aluno := ''; cod_turma := ''; habilita_salvar(sender); end; procedure TForm_matriculas.btn_salvarClick(Sender: TObject); var deuerro : boolean; begin if (cod_aluno='') or (edt_turma.Text='') then begin Showmessage('Informe todos os campos!'); end else begin if operacao = 'novo' then adoquery_aux.SQL.Text := ' INSERT INTO MATRICULAS VALUES ' + '('+ QuotedStr(cod_turma) + ','+ cod_aluno + ')' else if operacao = 'alterar' then adoquery_aux.SQL.Text := 'UPDATE MATRICULAS SET '+ ' COD_TURMA ='+ QuotedStr(cod_turma) + ', COD_ALUNO ='+ cod_aluno + ' WHERE COD_TURMA = '+ QuotedStr(pk_turma) + ' AND COD_ALUNO = '+ pk_aluno; Form_logon.ConexaoBD.BeginTrans; try ADOQuery_aux.ExecSQL; deuerro := false; except on E : Exception do begin deuerro := true; if Form_logon.ErroBD(E.Message,'PK_Matriculas') = 'Sim' then ShowMessage('Matrícula já cadastrada!') else if Form_logon.ErroBD(E.Message,'FK_Frequencias_Matriculas') = 'Sim' then Showmessage('Existem frequencias lançadas para esta matrícula!') else ShowMessage('Ocorreu o seguinte erro: ' + E.Message); end; end; if deuerro = true then begin Form_logon.ConexaoBD.RollbackTrans; end else begin Form_logon.ConexaoBD.CommitTrans; pk_turma := cod_turma; pk_aluno := cod_aluno; desabilita_salvar(sender); bloqueia_campos; end; end; end; procedure TForm_matriculas.btn_alterarClick(Sender: TObject); begin if (pk_turma = '') or (pk_aluno = '') then Showmessage('Impossível alterar!') else begin libera_campos; habilita_salvar(sender); end; end; procedure TForm_matriculas.btn_cancelarClick(Sender: TObject); begin if operacao = 'novo' then limpa_campos; desabilita_salvar(sender); bloqueia_campos; end; procedure TForm_matriculas.btn_excluirClick(Sender: TObject); var deuerro : boolean; begin if (pk_turma = '') or (pk_aluno = '') then Showmessage('Impossível excluir!') else begin adoquery_aux.SQL.Text := ' DELETE FROM MATRICULAS ' + ' WHERE COD_TURMA = ' + QuotedStr(pk_turma) + ' AND COD_ALUNO = ' + cod_aluno; Form_logon.ConexaoBD.BeginTrans; try ADOQuery_aux.ExecSQL; deuerro := false; except on E : Exception do begin deuerro := true; if Form_logon.ErroBD(E.Message,'FK_Frequencias_Matriculas') = 'Sim' then Showmessage('Existem frequências lançadas para esta matrícula!') else Showmessage('Ocorreu o seguinte erro: ' + E.Message); end; end; if deuerro = true then begin Form_logon.ConexaoBD.RollbackTrans; end else begin Form_logon.ConexaoBD.CommitTrans; pk_turma := ''; pk_aluno := ''; cod_turma := ''; cod_aluno := ''; desabilita_salvar(sender); limpa_campos; bloqueia_campos; end; end; end; procedure TForm_matriculas.btn_fecharClick(Sender: TObject); begin Close; end; procedure TForm_matriculas.btn_localizarClick(Sender: TObject); var sql : string; begin limpa_campos; bloqueia_campos; desabilita_salvar(sender); sql := ' SELECT MATRICULAS.COD_TURMA, '+ ' MATRICULAS.COD_ALUNO, '+ ' ALUNOS.NOME '+ ' FROM MATRICULAS '+ ' INNER JOIN ALUNOS '+ ' ON MATRICULAS.COD_ALUNO = ALUNOS.COD_ALUNO '; Form_pesquisa.sql_pesquisa:= sql; Form_pesquisa.ShowModal; if Form_pesquisa.chave <> '' then begin pk_turma := Form_pesquisa.chave; pk_aluno := Form_pesquisa.chave_aux; ADOQuery_aux.SQL.Text := sql + ' WHERE COD_TURMA = ' + QuotedStr(pk_turma) + ' AND MATRICULAS.COD_ALUNO = ' + pk_aluno; ADOQuery_aux.Open; edt_aluno.Text := ADOQuery_aux.fieldbyname('NOME').AsString; edt_turma.Text := pk_turma; cod_turma := pk_turma; cod_aluno := pk_aluno; end; end; end.
unit TabFunctions; interface uses SysUtils; function GetSep(str: string): string; function GetCols(str: string; ColN, ColCount:integer; Spc:byte; ReplaceSeps: boolean): string; overload; function GetCols(str: string; ColN, ColCount:integer; Sep:char; ReplaceSeps: boolean): string; overload; function GetColN(str, sep: string; n: integer): integer; overload; function GetColN(str: string; sep: integer; n: integer): integer; overload; function GetColCount(str, sep: string): integer; overload; function GetColCount(str: string; sep: integer): integer; overload; function ReplaceDecimals(S :String):string; overload; function ReplaceDecimals(S :String; sep :char):string; overload; const TabChar = #$9; implementation function GetSep(str: string): string; const n = 6; seps: array [1..n] of string = (':','/','\','-','.',','); var i:integer; begin Result:=''; for i:=1 to n do if Pos(seps[i],str)>1 then begin Result:=seps[i]; break; end; end; function GetColN(str, sep: string; n: integer): integer; overload; var j,stl,b :integer; begin Result:=0; stl:=0; b:=1; for j:=1 to n do if (copy(Str,j,1)=sep) and (copy(Str,j-1,1)<>sep) then begin inc(stl); b:=j+1; end; Result:=stl; end; function GetColN(str: string; sep: integer; n: integer): integer; overload; var j,stl,b :integer; sepS: char; begin Case Sep of 0: sepS:= ' '; 1: sepS:= TabChar; 2: sepS:= '/';// LoadRData.Spacer.Text[1]; 3: sepS:= ';'; 4: sepS:= ','; end; Result:=0; stl:=0; b:=1; for j:=1 to n do if (copy(Str,j,1)=sepS) and (copy(Str,j-1,1)<>sepS) then begin inc(stl); b:=j+1; end; Result:=stl; end; function GetColCount(str, sep: string): integer; overload; begin Result := GetColN(str, sep, length(str)); end; function GetColCount(str: string; sep: integer): integer; overload; begin Result := GetColN(str, sep, length(str)); end; procedure PrepareString(var str:string; sep: string); var I: integer; begin if (Sep = TabChar) or (Sep = ' ') then exit; for I := Length(Str) DownTo 2 Do if (Str[I-1] = Sep) and (Str[I] = Sep) then Insert(' ', Str, I); end; function GetCols(str: string; ColN, ColCount:integer; Spc:byte; ReplaceSeps: boolean): string; var j,stl,b :integer; sep :String; begin result:=''; stl:=0; b:=1; sep:=' '; Case Spc of 0: sep:=' '; 1: sep:=TabChar; 2: sep:='/';// LoadRData.Spacer.Text[1]; 3: sep:=';'; 4: sep:=','; end; PrepareString(str, sep); for j:=1 to length(Str)+1 do Begin if ((copy(Str,j,1)=sep)or(j=length(Str)+1))and(copy(Str,j-1,1)<>sep) then begin if (stl>=ColN) and (Stl<ColN+ColCount) then Begin if result='' then Result:=(Copy(Str,b,j-b)) else Result:=Result+' '+(Copy(Str,b,j-b)); End; inc(stl); b:=j+1; if stl>ColN+ColCount then break; end; End; if ReplaceSeps then if Sep<>DecimalSeparator then Result := ReplaceDecimals(Result); end; function GetCols(str: string; ColN, ColCount:integer; Sep:char; ReplaceSeps: boolean): string; var j,stl,b, i :integer; begin result:=''; stl:=0; b:=1; PrepareString(str, sep); for j:=1 to length(Str)+1 do Begin if ((copy(Str,j,1)=sep)or(j=length(Str)+1))and(copy(Str,j-1,1)<>sep) then begin if (stl>=ColN) and (Stl<ColN+ColCount) then Begin if result='' then Result:=(Copy(Str,b,j-b)) else Result:=Result+' '+(Copy(Str,b,j-b)); End; inc(stl); b:=j+1; if stl>ColN+ColCount then break; end; End; if ReplaceSeps then if Sep<>DecimalSeparator then Result := ReplaceDecimals(Result); for I := length(Result) DownTo 1 Do if Result[I] <> sep then break; Result := Copy(Result, 1, I+1); for I := 1 To length(Result)-1 Do if Result[I] <> sep then break; Result := Copy(Result, I, Length(Result) - I+1); end; function ReplaceDecimals(S:String):string; var j: integer; begin Result := S; if result <> '' then for j := 1 to length(Result)+1 do if ((result[j] = '.') or (result[j] = ',')) then result[j] := DecimalSeparator; end; function ReplaceDecimals(S :String; sep :char):string; var j: integer; begin Result := S; if result <> '' then for j := 1 to length(Result)+1 do if ((result[j] = '.') or (result[j] = ',')) then result[j] := Sep; end; {function CopToStr ( var cc ): String ; // ÈÍÍÎÊÅÍÒÈÉ var c : Array [0..1000] of char absolute cc ; i : Integer ; s : string ; begin i := 0; s := '' ; while c[i] <> #0 do begin s := s + c[i]; i := i +1; end ; CopToStr := s; end; procedure StrLong ( Data : int64; var str : String ); //ÈÍÍÎÊÅÍÒÈÉ var s, s1 : string ; fl : boolean; begin s := ''; fl := FALSE ; repeat system.Str ( Data mod 1000, s1 ); while Length ( s1 ) <3 do s1 := '0'+s1; IF FL THEN s := s1 + '.'+s ELSE s := s1 ; Data := Data div 1000; FL := TRUE ; until Data <1000; system.str ( data, s1 ); while Length ( s1 ) <3 do s1 := '0'+s1; s := s1 + '.'+s; str := s ; end; } function HexToInt(Value: String): LongInt; var L : Longint; B : Byte; begin Result := 0; if Length(Value) <> 0 then begin L := 1; B := Length(Value) + 1; repeat dec(B); if Value[B] <= '9' then Result := Result + StrToInt(Value[B]) * L else Result := Result + (Ord(Value[B]) - 65) * L; L := L * 16; until B = 1; end; end; end.
unit WeightRecord; interface uses SysUtils, Variants, Dialogs; type TWeightRecord = class private public id: Integer; glideNo: string; carNo: string; weightType: string; faHuo: string; shouHuo: string; goods: string; spec: string; gross: Double; tare: Double; net: Double; bundle: Double; real: Double; price: Double; sum: Double; scale: Double; quanter: Double; cost: Double; grossMan: string; tareMan: string; grossAddr: string; tareAddr: string; grossTime: TDateTime; tareTime: TDateTime; firstTime: TDateTime; secondTime: TDateTime; updateUser: string; updateTime: TDateTime; memo: string; printCount: Integer; upload: Boolean; backup1: string; backup2: string; backup3: string; backup4: string; backup5: string; backup6: Double; backup7: Double; backup8: Double; backup9: Double; backup10: string; backup11: string; backup12: string; backup13: string; backup14: string; backup15: Double; backup16: Double; backup17: Double; backup18: Double; function toString(): string; end; TWeightRecordUtil = class private public class function save(var w: TWeightRecord): Boolean; //保存称重记录 class function get(glideNo: string; var w: TWeightRecord): Boolean; end; implementation uses QueryDM, WeightUtil, Classes; { TWeightUtil } class function TWeightRecordUtil.get(glideNo: string; var w: TWeightRecord): Boolean; begin Result := False; with QueryDataModule.ADOQExec do begin Close; SQL.Text := 'select * from 称重信息 where 流水号=:glideNo'; Parameters.ParamByName('glideNo').Value := glideNo; Open; if not IsEmpty then begin w.id := FieldByName('序号').AsInteger; w.glideNo := FieldByName('流水号').AsString; w.carNo := FieldByName('车号').AsString; w.faHuo := FieldByName('发货单位').AsString; w.shouHuo := FieldByName('收货单位').AsString; w.goods := FieldByName('货名').AsString; w.spec := FieldByName('规格').AsString; w.grossMan := FieldByName('毛重司磅员').AsString; w.tareMan := FieldByName('皮重司磅员').AsString; w.grossAddr := FieldByName('毛重磅号').AsString; w.tareAddr := FieldByName('皮重磅号').AsString; if not FieldByName('毛重时间').IsNull then w.grossTime := FieldByName('毛重时间').AsDateTime; if not FieldByName('皮重时间').IsNull then w.tareTime := FieldByName('皮重时间').AsDateTime; w.gross := FieldByName('毛重').AsFloat; w.tare := FieldByName('皮重').AsFloat; w.net := FieldByName('净重').AsFloat; w.bundle := FieldByName('扣重').AsFloat; w.real := FieldByName('实重').AsFloat; w.price := FieldByName('单价').AsFloat; w.sum := FieldByName('金额').AsFloat; w.scale := FieldByName('折方系数').AsFloat; w.quanter := FieldByName('方量').AsFloat; w.cost := FieldByName('过磅费').AsFloat; w.firstTime := FieldByName('一次过磅时间').AsDateTime; w.secondTime := FieldByName('二次过磅时间').AsDateTime; w.updateUser := FieldByName('更新人').AsString; w.updateTime := FieldByName('更新时间').AsDateTime; w.memo := FieldByName('备注').AsString; w.printCount := FieldByName('打印次数').AsInteger; w.upload := FieldByName('上传否').AsBoolean; w.backup1 := FieldByName('备用1').AsString; w.backup2 := FieldByName('备用2').AsString; w.backup3 := FieldByName('备用3').AsString; w.backup4 := FieldByName('备用4').AsString; w.backup5 := FieldByName('备用5').AsString; w.backup6 := FieldByName('备用6').AsFloat; w.backup7 := FieldByName('备用7').AsFloat; w.backup8 := FieldByName('备用8').AsFloat; w.backup9 := FieldByName('备用9').AsFloat; w.backup10 := FieldByName('备用10').AsString; w.backup11 := FieldByName('备用11').AsString; w.backup12 := FieldByName('备用12').AsString; w.backup13 := FieldByName('备用13').AsString; w.backup14 := FieldByName('备用14').AsString; w.backup15 := FieldByName('备用15').AsFloat; w.backup16 := FieldByName('备用16').AsFloat; w.backup17 := FieldByName('备用17').AsFloat; w.backup18 := FieldByName('备用18').AsFloat; Result := True; end; end; end; class function TWeightRecordUtil.save(var w: TWeightRecord): Boolean; var sqlStr: string; begin if w.glideNo = '' then begin sqlStr := 'insert into 称重信息(流水号,车号,过磅类型,发货单位,收货单位,' + '货名,规格,毛重,皮重,净重,扣重,实重,单价,金额,折方系数,方量,过磅费,' + '毛重司磅员,皮重司磅员,毛重磅号,皮重磅号,毛重时间,皮重时间,一次过磅时间,' + '二次过磅时间,更新人,更新时间,备注,打印次数,上传否,备用1,备用2,备用3,' + '备用4,备用5,备用6,备用7,备用8,备用9,备用10,备用11,备用12,备用13,' + '备用14,备用15,备用16,备用17,备用18)'; sqlStr := sqlStr + ' values(:glideNo,:car,:weightType,:fahuo,:shouhuo,:goods,' + ':spec,:gross,:tare,:net,:bundle,:real,:price,:sum,:scale,:quanter,:cost,' + ':grossMan,:tareMan,:grossAddr,:tareAddr,:grosstime,:taretime,:firstTime,:secondTime,' + ':updateUser,:updateTime,:memo,:printCount,:upload,:backup1,:backup2,:backup3,' + ':backup4,:backup5,:backup6,:backup7,:backup8,:backup9,:backup10,:backup11,:backup12,' + ':backup13,:backup14,:backup15,:backup16,:backup17,:backup18)'; w.glideNo := TWeightUtil.getMaxGlideNo; end else begin sqlStr := 'update 称重信息 set 流水号=:glideNo,车号=:car,过磅类型=:weightType,' + '发货单位=:fahuo,收货单位=:shouhuo,货名=:goods,规格=:spec,毛重=:gross,' + '皮重=:tare,净重=:net,扣重=:bundle,实重=:real,单价=:price,金额=:sum,' + '折方系数=:scale,方量=:quanter,过磅费=:cost,毛重司磅员=:grossMan,' + '皮重司磅员=:tareMan,毛重磅号=:grossAddr,皮重磅号=:tareAddr,毛重时间=:grosstime,' + '皮重时间=:taretime,一次过磅时间=:firstTime,二次过磅时间=:secondTime,' + '更新人=:updateUser,更新时间=:updateTime,备注=:memo,打印次数=:printCount,' + '上传否=:upload,备用1=:backup1,备用2=:backup2,备用3=:backup3,' + '备用4=:backup4,备用5=:backup5,备用6=:backup6,备用7=:backup7,备用8=:backup8,' + '备用9=:backup9,备用10=:backup10,备用11=:backup11,备用12=:backup12,备用13=:backup13,' + '备用14=:backup14,备用15=:backup15,备用16=:backup16,备用17=:backup17,备用18=:backup18 ' + 'where 序号=:id'; end; with QueryDataModule.ADOQExec do begin Close; SQL.Text := sqlStr; if w.id <> 0 then Parameters.ParamByName('id').Value := w.id; Parameters.ParamByName('glideno').Value := w.glideNo; Parameters.ParamByName('car').Value := w.carNo; Parameters.ParamByName('weightType').Value := w.weightType; Parameters.ParamByName('fahuo').Value := w.faHuo; Parameters.ParamByName('shouhuo').Value := w.shouHuo; Parameters.ParamByName('goods').Value := w.goods; Parameters.ParamByName('spec').Value := w.spec; Parameters.ParamByName('gross').Value := w.gross; Parameters.ParamByName('tare').Value := w.tare; Parameters.ParamByName('net').Value := w.net; Parameters.ParamByName('bundle').Value := w.bundle; Parameters.ParamByName('real').Value := w.real; Parameters.ParamByName('price').Value := w.price; Parameters.ParamByName('sum').Value := w.sum; Parameters.ParamByName('cost').Value := w.cost; Parameters.ParamByName('scale').Value := w.scale; Parameters.ParamByName('quanter').Value := w.quanter; if (w.gross <> 0) and (w.tare <> 0) then begin Parameters.ParamByName('grossMan').Value := w.grossMan; Parameters.ParamByName('tareMan').Value := w.tareMan; Parameters.ParamByName('grosstime').Value := w.grossTime; Parameters.ParamByName('taretime').Value := w.tareTime; Parameters.ParamByName('grossAddr').Value := w.grossAddr; Parameters.ParamByName('tareAddr').Value := w.tareAddr; end else if (w.gross <> 0) then begin Parameters.ParamByName('grossMan').Value := w.grossMan; Parameters.ParamByName('grosstime').Value := w.grossTime; Parameters.ParamByName('taretime').Value := null; Parameters.ParamByName('grossAddr').Value := w.grossAddr; end else if (w.tare <> 0) then begin Parameters.ParamByName('tareMan').Value := w.tareMan; Parameters.ParamByName('grosstime').Value := null; Parameters.ParamByName('taretime').Value := w.tareTime; Parameters.ParamByName('tareAddr').Value := w.tareAddr; end; Parameters.ParamByName('updateUser').Value := w.updateUser; Parameters.ParamByName('updateTime').Value := Now; Parameters.ParamByName('memo').Value := w.memo; Parameters.ParamByName('printCount').Value := w.printCount; Parameters.ParamByName('upload').Value := w.upload; Parameters.ParamByName('backup1').Value := w.backup1; Parameters.ParamByName('backup2').Value := w.backup2; Parameters.ParamByName('backup3').Value := w.backup3; Parameters.ParamByName('backup4').Value := w.backup4; Parameters.ParamByName('backup5').Value := w.backup5; Parameters.ParamByName('backup6').Value := w.backup6; Parameters.ParamByName('backup7').Value := w.backup7; Parameters.ParamByName('backup8').Value := w.backup8; Parameters.ParamByName('backup9').Value := w.backup9; Parameters.ParamByName('backup10').Value := w.backup10; Parameters.ParamByName('backup11').Value := w.backup11; Parameters.ParamByName('backup12').Value := w.backup12; Parameters.ParamByName('backup13').Value := w.backup13; Parameters.ParamByName('backup14').Value := w.backup14; Parameters.ParamByName('backup15').Value := w.backup15; Parameters.ParamByName('backup16').Value := w.backup16; Parameters.ParamByName('backup17').Value := w.backup17; Parameters.ParamByName('backup18').Value := w.backup18; try ExecSQL; Result := True; except on e: Exception do begin MessageDlg(PChar(Format('数据保存失败!%s', [e.Message])), mtError, [mbOK], 0); Result := False; end; end; end; end; { TWeightRecord } function TWeightRecord.toString: string; var s: string; begin s := s + glideNo + ',' + carNo + ',' + faHuo + ',' + shouHuo + ',' + goods + ',' + spec + ',' + FloatToStr(gross) + ',' + FloatToStr(tare) + ',' + FloatToStr(net) + ',' + FloatToStr(bundle) + ',' + FloatToStr(real) + ',' + FloatToStr(price) + ',' + FloatToStr(sum) + ',' + FloatToStr(scale) + ',' + FloatToStr(quanter) + ',' + FloatToStr(cost) + ',' + grossMan + ',' + tareMan + ',' + grossAddr + ',' + tareAddr + ',' + memo + ',' + backup1 + ',' + backup2 + ',' + backup3 + ',' + backup4 + ',' + backup5 + ',' + FloatToStr(backup6) + ',' + FloatToStr(backup7) + ',' + FloatToStr(backup8) + ',' + FloatToStr(backup9) + ',' + backup10 + ',' + backup11 + ',' + backup12 + ',' + backup13 + ',' + backup14 + ',' + FloatToStr(backup15) + ',' + FloatToStr(backup16) + ',' + FloatToStr(backup17) + ',' + FloatToStr(backup18); Result := s; end; end.
unit Domain.Entity.Produto; interface uses System.Classes, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types, EF.Mapping.Atributes, Domain.Consts; type [Table('Produto')] TProduto = class( TEntityBase ) private FDescricao: Tstring; public [Column('Descricao',varchar50,false)] property Descricao: Tstring read FDescricao write FDescricao; end; implementation initialization RegisterClass(TProduto); finalization UnRegisterClass(TProduto); end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [FIN_LANCAMENTO_PAGAR] The MIT License Copyright: Copyright (C) 2014 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 FinLancamentoPagarVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ViewPessoaFornecedorVO, FinParcelaPagarVO, FinDocumentoOrigemVO, FinLctoPagarNtFinanceiraVO; type [TEntity] [TTable('FIN_LANCAMENTO_PAGAR')] TFinLancamentoPagarVO = class(TVO) private FMesclarPagamento: String; FID: Integer; FID_FIN_DOCUMENTO_ORIGEM: Integer; FID_FORNECEDOR: Integer; FPAGAMENTO_COMPARTILHADO: String; FQUANTIDADE_PARCELA: Integer; FVALOR_TOTAL: Extended; FVALOR_A_PAGAR: Extended; FDATA_LANCAMENTO: TDateTime; FNUMERO_DOCUMENTO: String; FIMAGEM_DOCUMENTO: String; FPRIMEIRO_VENCIMENTO: TDateTime; FCODIGO_MODULO_LCTO: String; FINTERVALO_ENTRE_PARCELAS: Integer; FMESCLADO_PARA: Integer; //Transientes FFornecedorNome: String; FDocumentoOrigemSigla: String; FFornecedorVO: TViewPessoaFornecedorVO; FDocumentoOrigemVO: TFinDocumentoOrigemVO; FListaParcelaPagarVO: TObjectList<TFinParcelaPagarVO>; FListaLancPagarNatFinanceiraVO: TObjectList<TFinLctoPagarNtFinanceiraVO>; public constructor Create; override; destructor Destroy; override; [TColumn('CheckBox',' ',16,[ldGrid], True)] [TColumn('MesclarPagamento','Mesclar',16,[], True)] property MesclarPagamento: String read FMesclarPagamento write FMesclarPagamento; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_FIN_DOCUMENTO_ORIGEM', 'Id Fin Documento Origem', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFinDocumentoOrigem: Integer read FID_FIN_DOCUMENTO_ORIGEM write FID_FIN_DOCUMENTO_ORIGEM; [TColumnDisplay('FIN_DOCUMENTO_ORIGEM.SIGLA_DOCUMENTO', 'Sigla Documento', 60, [ldGrid, ldLookup], ftString, 'FinDocumentoOrigemVO.TFinDocumentoOrigemVO', True)] property DocumentoOrigemSigla: String read FDocumentoOrigemSigla write FDocumentoOrigemSigla; [TColumn('ID_FORNECEDOR', 'Id Fornecedor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR; [TColumnDisplay('FORNECEDOR.NOME', 'Nome Fornecedor', 150, [ldGrid, ldLookup], ftString, 'ViewPessoaFornecedorVO.TViewPessoaFornecedorVO', True)] property FornecedorNome: String read FFornecedorNome write FFornecedorNome; [TColumn('PAGAMENTO_COMPARTILHADO', 'Pagamento Compartilhado', 8, [ldGrid, ldLookup, ldCombobox], False)] property PagamentoCompartilhado: String read FPAGAMENTO_COMPARTILHADO write FPAGAMENTO_COMPARTILHADO; [TColumn('QUANTIDADE_PARCELA', 'Quantidade Parcela', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property QuantidadeParcela: Integer read FQUANTIDADE_PARCELA write FQUANTIDADE_PARCELA; [TColumn('VALOR_TOTAL', 'Valor Total', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; [TColumn('VALOR_A_PAGAR', 'Valor A Pagar', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorAPagar: Extended read FVALOR_A_PAGAR write FVALOR_A_PAGAR; [TColumn('DATA_LANCAMENTO', 'Data Lancamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataLancamento: TDateTime read FDATA_LANCAMENTO write FDATA_LANCAMENTO; [TColumn('NUMERO_DOCUMENTO', 'Numero Documento', 400, [ldGrid, ldLookup, ldCombobox], False)] property NumeroDocumento: String read FNUMERO_DOCUMENTO write FNUMERO_DOCUMENTO; [TColumn('IMAGEM_DOCUMENTO', 'Imagem Documento', 450, [ldGrid, ldLookup, ldCombobox], False)] property ImagemDocumento: String read FIMAGEM_DOCUMENTO write FIMAGEM_DOCUMENTO; [TColumn('PRIMEIRO_VENCIMENTO', 'Primeiro Vencimento', 80, [ldGrid, ldLookup, ldCombobox], False)] property PrimeiroVencimento: TDateTime read FPRIMEIRO_VENCIMENTO write FPRIMEIRO_VENCIMENTO; [TColumn('CODIGO_MODULO_LCTO', 'Codigo Modulo Lcto', 24, [ldGrid, ldLookup, ldCombobox], False)] property CodigoModuloLcto: String read FCODIGO_MODULO_LCTO write FCODIGO_MODULO_LCTO; [TColumn('INTERVALO_ENTRE_PARCELAS', 'Intervalo Entre Parcelas', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IntervaloEntreParcelas: Integer read FINTERVALO_ENTRE_PARCELAS write FINTERVALO_ENTRE_PARCELAS; [TColumn('MESCLADO_PARA', 'Mesclado Para', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property MescladoPara: Integer read FMESCLADO_PARA write FMESCLADO_PARA; //Transientes [TAssociation('ID', 'ID_FORNECEDOR')] property FornecedorVO: TViewPessoaFornecedorVO read FFornecedorVO write FFornecedorVO; [TAssociation('ID', 'ID_FIN_DOCUMENTO_ORIGEM')] property DocumentoOrigemVO: TFinDocumentoOrigemVO read FDocumentoOrigemVO write FDocumentoOrigemVO; [TManyValuedAssociation('ID_FIN_LANCAMENTO_PAGAR', 'ID')] property ListaParcelaPagarVO: TObjectList<TFinParcelaPagarVO> read FListaParcelaPagarVO write FListaParcelaPagarVO; [TManyValuedAssociation('ID_FIN_LANCAMENTO_PAGAR', 'ID')] property ListaLancPagarNatFinanceiraVO: TObjectList<TFinLctoPagarNtFinanceiraVO> read FListaLancPagarNatFinanceiraVO write FListaLancPagarNatFinanceiraVO; end; implementation constructor TFinLancamentoPagarVO.Create; begin inherited; FDocumentoOrigemVO := TFinDocumentoOrigemVO.Create; FFornecedorVO := TViewPessoaFornecedorVO.Create; FListaParcelaPagarVO := TObjectList<TFinParcelaPagarVO>.Create; FListaLancPagarNatFinanceiraVO := TObjectList<TFinLctoPagarNtFinanceiraVO>.Create; end; destructor TFinLancamentoPagarVO.Destroy; begin FreeAndNil(FFornecedorVO); FreeAndNil(FDocumentoOrigemVO); FreeAndNil(FListaParcelaPagarVO); FreeAndNil(FListaLancPagarNatFinanceiraVO); inherited; end; initialization Classes.RegisterClass(TFinLancamentoPagarVO); finalization Classes.UnRegisterClass(TFinLancamentoPagarVO); end.
unit doHTTP; interface uses Classes, Windows, idHTTP, FTTypes, IdSSLOpenSSL; type xxx = integer; function doHTTPPutString(sJSON: string; Url: string; slDebug: TStringList): integer; function doHTTPDeleteString(sJSON: string; Url: string; slDebug: TStringList): integer; function doHTTPDelete(Url: string): integer; function doHTTPPutMemoryStream(mStream: TMemoryStream; Url: string; slDebug: TStringList): integer; function doHTTPGetByteArraySL(Url: string;sl: TStringList): byteArray; implementation uses SysUtils; const IMAGE_FILE_LARGE_ADDRESS_AWARE = $0020; {$SETPEFLAGS IMAGE_FILE_LARGE_ADDRESS_AWARE} function doHTTPGetByteArraySL(Url: string;sl: TStringList): byteArray; var HTTP: TIdHttp; p: integer; b: byteArray; mStream: TMemoryStream; dummy: integer; begin // test HTTP Get // INDY SSL // das ist die notwendige Ergänzung für die Verwendung von SSL // HTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create; HTTP := TIdHttp.Create; HTTP.ConnectTimeout := 400000; HTTP.ReadTimeout := 400000; mStream := TMemoryStream.Create; try try try try HTTP.Get(Url, mStream); mStream.Position := 0; // memo1.Lines.LoadFromStream(mStream); p := mStream.Size; SetLength(b, p); mStream.Read(b[0], p); result := b; except on E: Exception do begin try sl.Add(E.Message); except dummy := 1; end; end; end; finally mStream.Free; end; except //dieser Teil wird vermutlich nie ausgeführt on E: EIdHTTPProtocolException do begin sl.Add(E.Message + #13#10#13#10 + E.ErrorMessage); end; on E: Exception do begin sl.Add(E.Message); end; end; finally HTTP.Free; end; end; function doHTTPPutMemoryStream(mStream: TMemoryStream; Url: string; slDebug: TStringList): integer; var HTTP: TIdHttp; fehler: integer; begin fehler := 0; slDebug.Clear; slDebug.Add('start'); HTTP := TIdHttp.Create; HTTP.ConnectTimeout := 400000; HTTP.ReadTimeout := 400000; // HTTP.Request.customheaders.AddValue('Content-Type', 'text/plain; charset=UTF-8'); // HTTP.Request.ContentEncoding:= 'text/plain; charset=UTF-8'; falsch try try try slDebug.Add('vor put'); slDebug.Add(HTTP.put(Url, mStream)); slDebug.Add('nach put'); slDebug.Add(HTTP.ResponseText); slDebug.Add('x'); finally // RequestBody.Free; end; except on E: EIdHTTPProtocolException do begin slDebug.Add('F:HTTPPutMemoryStream:' + E.Message + #13#10#13#10 + E.ErrorMessage); fehler := 1; mStream.savetofile(ExtractFilePath(paramstr(0)) + 'HTTPFehler1.bin'); end; on E: Exception do begin // Socket-Fehler #10060 Zeitüberschreitung bei Verbindung slDebug.Add('F:HTTPPutMemoryStream:' + E.Message); fehler := 1; mStream.savetofile(ExtractFilePath(paramstr(0)) + 'HTTPFehler2.bin'); // fs := TFileStream.Create(ExtractFilePath(paramstr(0))+'HTTPFehler2.bin', fmCreate); // fs.CopyFrom(mStream, mStream.Size); // fs.Free; end; end; finally slDebug.Add('HTTP.free'); HTTP.Free; end; slDebug.Add('Result:' + inttostr(fehler)); result := fehler; end; function doHTTPPutString(sJSON: string; Url: string; slDebug: TStringList): integer; var HTTP: TIdHttp; RequestBody: TStringStream; ast: AnsiString; fehler: integer; begin fehler := 0; slDebug.Clear; slDebug.Add('start'); HTTP := TIdHttp.Create; HTTP.ConnectTimeout := 400000; HTTP.ReadTimeout := 400000; HTTP.Request.customheaders.AddValue('Content-Type', 'text/plain; charset=UTF-8'); // HTTP.Request.ContentEncoding:= 'text/plain; charset=UTF-8'; falsch try try ast := AnsiString(sJSON); // move(ast[1], ba[1], 2 * length(ast)); RequestBody := TStringStream.Create(ast, TEncoding.UTF8); try slDebug.Add(HTTP.put(Url, RequestBody)); slDebug.Add(HTTP.ResponseText); finally RequestBody.Free; end; except on E: EIdHTTPProtocolException do begin slDebug.Add(E.Message + #13#10#13#10 + E.ErrorMessage); fehler := 1; end; on E: Exception do begin slDebug.Add(E.Message); fehler := 1; end; end; finally HTTP.Free; end; result := fehler; end; function doHTTPDeleteString(sJSON: string; Url: string; slDebug: TStringList): integer; var HTTP: TIdHttp; RequestBody: TStringStream; ast: AnsiString; fehler: integer; begin fehler := 0; slDebug.Clear; slDebug.Add('start'); HTTP := TIdHttp.Create; HTTP.ConnectTimeout := 400000; HTTP.ReadTimeout := 400000; HTTP.Request.customheaders.AddValue('Content-Type', 'text/plain; charset=UTF-8'); // HTTP.Request.ContentEncoding:= 'text/plain; charset=UTF-8'; falsch try try ast := AnsiString(sJSON); // move(ast[1], ba[1], 2 * length(ast)); RequestBody := TStringStream.Create(ast, TEncoding.UTF8); try slDebug.Add('Delete:' + Url); HTTP.delete(Url, RequestBody); slDebug.Add(HTTP.ResponseText); finally RequestBody.Free; end; except on E: EIdHTTPProtocolException do begin slDebug.Add(E.Message + #13#10#13#10 + E.ErrorMessage); fehler := 1; end; on E: Exception do begin slDebug.Add(E.Message); fehler := 1; end; end; finally HTTP.Free; end; result := fehler; end; function doHTTPDelete(Url: string): integer; var HTTP: TIdHttp; RequestBody: TStringStream; ast: AnsiString; fehler: integer; begin fehler := 0; // slDebug.Clear; // slDebug.Add('start'); HTTP := TIdHttp.Create; HTTP.ConnectTimeout := 400000; HTTP.ReadTimeout := 400000; HTTP.Request.customheaders.AddValue('Content-Type', 'text/plain; charset=UTF-8'); // HTTP.Request.ContentEncoding:= 'text/plain; charset=UTF-8'; falsch try try ast := AnsiString('?'); // move(ast[1], ba[1], 2 * length(ast)); RequestBody := TStringStream.Create(ast, TEncoding.UTF8); try // slDebug.Add('Delete:'+url); HTTP.delete(Url, RequestBody); // slDebug.Add(HTTP.ResponseText); finally RequestBody.Free; end; except on E: EIdHTTPProtocolException do begin // slDebug.Add(E.Message + #13#10#13#10 + E.ErrorMessage); fehler := 1; end; on E: Exception do begin // slDebug.Add(E.Message); fehler := 1; end; end; finally HTTP.Free; end; result := fehler; end; end.
{ ---------------------------------------------------------------------------- Window resizer tool for Windows https://zipplet.co.uk/ Copyright (c) Michael Nixon 2018. Launcher unit Licensed under the MIT license; please see the LICENSE file for full license terms and conditions. ---------------------------------------------------------------------------- } unit unitlaunch; interface uses unitcommon; procedure LaunchProgram; function TryWindowResize(movewindow: boolean): boolean; function EnsureWindowLock(movewindow: boolean): boolean; function FindProgramWindow(matchPID: boolean; pid: cardinal; matchName: boolean; name: ansistring): tHWND; function WindowTitlesMatch(windowtitle: ansistring; mask: ansistring): boolean; function NeedToFindWindow: boolean; function DoFindWindow: boolean; procedure GetDisplaySize; function MoveAndResizeWindow(movewindow: boolean): boolean; procedure CalculateDesiredWindowSize; implementation uses sysutils, windows, shellapi, mmsystem; { ---------------------------------------------------------------------------- Calculate the desired size to resize the application window to ---------------------------------------------------------------------------- } procedure CalculateDesiredWindowSize; var fw, fh: single; aspectRatio: single; allowedw, allowedh: longint; begin case _settings.scalingMethod of esDefined: begin _state.desiredWindowWidth := _settings.windowWidth; _state.desiredWindowHeight := _settings.windowHeight; end; esWindowScale: begin fw := (_state.originalWindowWidth / 100) * _settings.scale; fh := (_state.originalWindowHeight / 100) * _settings.scale; _state.desiredWindowWidth := round(fw); _state.desiredWindowHeight := round(fh); end; esDisplayScale: begin if not _settings.maintainAspectRatio then begin fw := (_state.displayWidth / 100) * _settings.scale; fh := (_state.displayHeight / 100) * _settings.scale; _state.desiredWindowWidth := round(fw); _state.desiredWindowHeight := round(fh); end else begin if _settings.aspectRatio = 0 then begin aspectRatio := _state.originalWindowClientWidth / _state.originalWindowClientHeight; DebugOut('Aspect ratio [autodetect] (w/h): ' + floattostr(aspectRatio)); end else begin aspectRatio := _settings.aspectRatio; DebugOut('Aspect ratio [forced] (w/h): ' + floattostr(aspectRatio)); end; // If the tweaks->scalingignorebordersize setting is false, we take the // border size into consideration when scaling. // If using clientresize, subtract the border size from the display size // to get the available scaling area, as we will add the border later if (not _settings.scalingIgnoreBorderSize) and _settings.clientResize then begin allowedw := _state.displayWidth - _state.borderWidth; allowedh := _state.displayHeight - _state.borderHeight; end else begin // If not using clientresize or tweaks->scalingignorebordersize is true, // available scaling area is the display. allowedw := _state.displayWidth; allowedh := _state.displayHeight; end; // First scale to maximum width and see if that fits fw := (allowedw / 100) * _settings.scale; fh := fw / aspectRatio; // If the window is now too tall, scale by height instead if round(fh) > allowedh then begin DebugOut('Window too tall when scaled by width, scaling by height'); fh := (allowedh / 100) * _settings.scale; fw := fh * aspectRatio; end; _state.desiredWindowWidth := round(fw); _state.desiredWindowHeight := round(fh); end; end; esPixelScale: begin fw := (_settings.windowWidth / 100) * _settings.scale; fh := (_settings.windowHeight / 100) * _settings.scale; _state.desiredWindowWidth := round(fw); _state.desiredWindowHeight := round(fh); end; end; // In client resize mode, add the border sizes to the desired size so that we // are adjusting the size of the client area. if _settings.clientResize then begin inc(_state.desiredWindowWidth, _state.borderWidth); inc(_state.desiredWindowHeight, _state.borderHeight); end; DebugOut('Desired window size: ' + inttostr(_state.desiredWindowWidth) + ' x ' + inttostr(_state.desiredWindowHeight)); // Crop window if too large if _state.desiredWindowWidth > _state.displayWidth then begin DebugOut('Warning: Desired window width is wider than the display; cropping'); _state.desiredWindowWidth := _state.displayWidth; end; if _state.desiredWindowHeight > _state.displayHeight then begin DebugOut('Warning: Desired window height is taller than the display; cropping'); _state.desiredWindowHeight := _state.displayHeight; end; end; { ---------------------------------------------------------------------------- Resizes the application window to the desired size. If <movewindow> is true, the window is also moved. Returns TRUE on success, FALSE on failure. ---------------------------------------------------------------------------- } function MoveAndResizeWindow(movewindow: boolean): boolean; var newx, newy: longint; windowrect: trect; begin result := false; // Need to initialise newx / newy with something even if we don't move the window newx := 0; newy := 0; if movewindow then begin if _settings.moveWindow = emFixed then begin newx := _settings.windowX; newy := _settings.windowY; end else if _settings.moveWindow = emCentre then begin newx := (_state.displayWidth div 2) - (_state.desiredWindowWidth div 2); newy := (_state.displayHeight div 2) - (_state.desiredWindowHeight div 2); if (newx < 0) then begin DebugOut('Warning: Window would have been offscreen (new X position = ' + inttostr(newx)); newx := 0; end; if (newy < 0) then begin DebugOut('Warning: Window would have been offscreen (new Y position = ' + inttostr(newy)); newy := 0; end; end else begin ErrorMessage('Internal error in MoveAndResizeWindow: movewindow mode invalid'); halt; end; if SetWindowPos(_state.windowHandle, HWND_TOP, newx, newy, _state.desiredWindowWidth, _state.desiredWindowHeight, SWP_NOACTIVATE or SWP_NOZORDER) then begin result := true; end else begin // Lost window handle _state.windowHandle := INVALID_HANDLE_VALUE; end; end else begin if SetWindowPos(_state.windowHandle, HWND_TOP, 0, 0, _state.desiredWindowWidth, _state.desiredWindowHeight, SWP_NOMOVE or SWP_NOACTIVATE or SWP_NOZORDER) then begin result := true; end else begin // Lost window handle _state.windowHandle := INVALID_HANDLE_VALUE; end; end; // Get and save new window size GetWindowRect(_state.windowHandle, windowrect); _state.windowX := windowrect.Left; _state.windowY := windowrect.Top; // Bug fix: resize command might be ignored, so set the window width / height to what we attempted to set // if the call fails, we will end up trying again _state.windowWidth := _state.desiredWindowWidth; _state.windowHeight := _state.desiredWindowHeight; //_state.windowWidth := windowrect.Right - windowrect.Left; //_state.windowHeight := windowrect.Bottom - windowrect.Top; end; { ---------------------------------------------------------------------------- Get the display size and set _state.displayWidth / _state.displayHeight ---------------------------------------------------------------------------- } procedure GetDisplaySize; begin _state.displayWidth := GetSystemMetrics(SM_CXSCREEN); _state.displayHeight := GetSystemMetrics(SM_CYSCREEN); DebugOut('Display resolution: ' + inttostr(_state.displayWidth) + ' x ' + inttostr(_state.displayHeight)); end; { ---------------------------------------------------------------------------- Do we need to find the target window? Returns TRUE if we do, FALSE if we don't. ---------------------------------------------------------------------------- } function NeedToFindWindow: boolean; begin if _state.windowHandle <> INVALID_HANDLE_VALUE then begin // There is no point calling IsWindow() to check if the handle exists as we // open ourselves to a race condition. Instead we will detect window loss // later on. result := false; end else begin result := true; end; end; { ---------------------------------------------------------------------------- Try to find the target window. If successful, sets _state.windowHandle and returns TRUE. ---------------------------------------------------------------------------- } function DoFindWindow: boolean; var handle: hwnd; windowrect: trect; windowrectclient: trect; begin result := false; _state.windowHandle := INVALID_HANDLE_VALUE; _state.borderSizeKnown := false; handle := FindProgramWindow(_settings.matchPID, _state.pid, _settings.matchName, _settings.windowNameMask); if handle = INVALID_HANDLE_VALUE then begin // Window probably temporarily absent (being recreated) exit; end; // Get window border dimensions // Used for client dimension resizing mode GetWindowRect(handle, windowrect); GetClientRect(handle, windowrectclient); if _settings.autoDetectBorderSize then begin _state.borderWidth := (windowrect.Right - windowrect.Left) - (windowrectclient.Right - windowrectclient.Left); _state.borderHeight := (windowrect.Bottom - windowrect.Top) - (windowrectclient.Bottom - windowrectclient.Top); DebugOut('Border size [autodetect]: ' + inttostr(_state.borderWidth) + ' x ' + inttostr(_state.borderHeight)); end else begin _state.borderWidth := _settings.borderWidth; _state.borderHeight := _settings.borderHeight; DebugOut('Border size [forced]: ' + inttostr(_state.borderWidth) + ' x ' + inttostr(_state.borderHeight)); end; if not _state.originalSizeKnown then begin // Save original window size _state.originalWindowWidth := windowrect.Right - windowrect.Left; _state.originalWindowHeight := windowrect.Bottom - windowrect.Top; DebugOut('Original window size: ' + inttostr(_state.originalWindowWidth) + ' x ' + inttostr(_state.originalWindowHeight)); _state.originalWindowClientWidth := windowrectclient.Right - windowrectclient.Left; _state.originalWindowClientHeight := windowrectclient.Bottom - windowrectclient.Top; DebugOut('Original window client size: ' + inttostr(_state.originalWindowClientWidth) + ' x ' + inttostr(_state.originalWindowClientHeight)); end; // Recalculate desired window size CalculateDesiredWindowSize; // Successfully retrieved window properties _state.windowHandle := handle; result := true; end; { ---------------------------------------------------------------------------- Launch the program and resize the window as required ---------------------------------------------------------------------------- } procedure LaunchProgram; const TICK_INTERVAL = 10; var processExitCode: dword; currenttime: longint; firstResize: boolean; abortResize: boolean; shouldMoveWindow: boolean; startupinfo: tstartupinfoa; processinfo: tprocessinformation; canTryResize: boolean; begin startupinfo := Default(tstartupinfoa); startupinfo.cb := sizeof(startupinfo); if not CreateProcessA(pansichar(_settings.programFileName), pansichar(_settings.programParameters), nil, nil, false, 0, nil, pansichar(_settings.programPath), startupinfo, processinfo ) then begin ErrorMessage('Failed to execute program: ' + _settings.programFileName); exit; end; // Record PID for later _state.pid := processinfo.dwProcessId; DebugOut('Program started, PID = ' + inttostr(_state.pid)); currenttime := 0; // Waiting for first resize firstResize := true; // Used to stop future resize attempts abortResize := false; // Should we move the window on the first attempt? if _settings.moveWindow <> emNone then begin shouldMoveWindow := true; end else begin shouldMoveWindow := false; end; if _settings.lockWindow then begin DebugOut('Will lock window size'); end; if _settings.alwaysMoveWindow then begin DebugOut('Will lock window position'); end; // Request high resolution system timer timebeginperiod(1); while WaitForSingleObject(processinfo.hProcess, 1) > 0 do begin // Note: The timing is not exact, but it's enough for our purposes. // I didn't want to pull in more external dependencies. sleep(TICK_INTERVAL); inc(currenttime, TICK_INTERVAL); // Assume we cannot attempt to resize the window. // We will set this to true if the window has already been found *or* we // successfully find it. canTryResize := false; if not abortResize then begin // If we need to find the window to resize, attempt to do so if NeedToFindWindow then begin DebugOut('NeedToFindWindow!'); if not DoFindWindow then begin DebugOut('FindWindow failed'); end else begin DebugOut('FindWindow succeeded'); canTryResize := true; end; end else begin // We *should* have the window handle. canTryResize := true; end; if canTryResize then begin if firstResize then begin if currenttime >= _settings.firstResizeDelayMS then begin DebugOut('Trying to resize window (first time)'); if TryWindowResize(shouldMoveWindow) then begin // Successfully completed first window resize. firstResize := false; DebugOut('First window resize successful'); if not _settings.alwaysMoveWindow then begin // Don't move the window anymore shouldMoveWindow := false; DebugOut('No longer repositioning the window'); end; end; end; if currenttime >= _settings.firstResizeTimeoutMS then begin // Resize timeout! DebugOut('Timed out resizing window (first time)'); ErrorMessage('Failed to resize the target window, timed out. Giving up.'); // Allow the application to keep running, but don't try to resize anymore abortResize := true; end; end else begin if _settings.lockWindow then begin // Ensure the window remains locked to the correct position EnsureWindowLock(shouldMoveWindow); end; end; end; end; end; // Finish using high resolution timer / task switching timeendperiod(1); GetExitCodeProcess(processinfo.hProcess, processExitCode); DebugOut('Program stopped with exit code: ' + inttostr(processExitCode)); CloseHandle(processinfo.hProcess); CloseHandle(processinfo.hThread); end; { ---------------------------------------------------------------------------- Try to resize the target window. Returns TRUE on success. ---------------------------------------------------------------------------- } function TryWindowResize(movewindow: boolean): boolean; begin // Move and resize application window result := MoveAndResizeWindow(movewindow); DebugOut('New window position: ' + inttostr(_state.windowX) + ', ' + inttostr(_state.windowY) + ' - ' + inttostr(_state.windowWidth) + ' x ' + inttostr(_state.windowHeight)); end; { ---------------------------------------------------------------------------- Try to locate a target window. Returns the window handle if successful. ---------------------------------------------------------------------------- } function FindProgramWindow(matchPID: boolean; pid: cardinal; matchName: boolean; name: ansistring): tHWND; const MAX_TITLE_LEN = 1024; var temphandle: HWND; windowtitletemp: array[0..MAX_TITLE_LEN - 1] of ansichar; windowtitlelength: longint; windowtitle: ansistring; windowpid: cardinal; begin result := INVALID_HANDLE_VALUE; // Enumerate all windows temphandle := FindWindow(nil, nil); while temphandle <> 0 do begin windowtitlelength := GetWindowTextA(temphandle, windowtitletemp, MAX_TITLE_LEN); windowtitle := windowtitletemp; windowtitle := copy(windowtitle, 1, windowtitlelength); windowpid := 0; GetWindowThreadProcessId(temphandle, windowpid); // Matching on PID only? if _settings.matchPID and (not _settings.matchName) then begin if windowpid = pid then begin // Found our window. result := temphandle; exit; end; end; // Matching on PID and name? if _settings.matchPID and _settings.matchName then begin if WindowTitlesMatch(windowtitle, _settings.windowNameMask) and (windowpid = pid) then begin // Found our window. result := temphandle; exit; end; end; // Match on name only if (not _settings.matchPID) and (_settings.matchName) then begin if WindowTitlesMatch(windowtitle, _settings.windowNameMask) then begin // Found our window. result := temphandle; exit; end; end; temphandle := GetWindow(temphandle, GW_HWNDNEXT); end; end; { ---------------------------------------------------------------------------- Returns true if <windowtitle> matches the <mask>. The mask can be a full name, or begin/end with * to match a partial title. ---------------------------------------------------------------------------- } function WindowTitlesMatch(windowtitle: ansistring; mask: ansistring): boolean; var s: ansistring; begin result := false; // Impossible if length(mask) < 1 then exit; // Always match if mask = '*' then begin result := true; exit; end; // Special 1 char case if length(mask) = 1 then begin if windowtitle = mask then begin // Match. result := true; exit; end; end; // Check for *middle* match if length(mask) >= 3 then begin if (mask[1] = '*') and (mask[length(mask)] = '*') then begin s := copy(mask, 2, length(mask) - 2); if pos(s, windowtitle) <> 0 then begin // Match. result := true; exit; end; end; end; // No match yet, but mask is >= 2 so safe to assume that. // Windowtitle ends with mask if mask[1] = '*' then begin s := copy(mask, 2, length(mask) - 1); if length(windowtitle) < length(s) then exit; if copy(windowtitle, length(windowtitle) - length(s) + 1, length(s)) = s then begin // Match. result := true; exit; end; end; // Windowtitle begins with mask if mask[length(mask)] = '*' then begin s := copy(mask, 1, length(mask) - 1); if length(windowtitle) < length(s) then exit; if copy(windowtitle, 1, length(s)) = s then begin // Match. result := true; exit; end; end; // Windowtitle is mask if windowtitle = mask then begin // Match. result := true; exit; end; end; { ---------------------------------------------------------------------------- Check if the program window has been resized/moved, and fix if required. ---------------------------------------------------------------------------- } function EnsureWindowLock(movewindow: boolean): boolean; var windowrect: trect; needAdjustment: boolean; begin result := false; needAdjustment := false; // Get current window size GetWindowRect(_state.windowHandle, windowrect); // Do we need to move the window? if movewindow then begin if (windowrect.Left <> _state.windowX) or (windowrect.Top <> _state.windowY) then begin needAdjustment := true; end; end; // Do we need to resize the window? if ((windowrect.Right - windowrect.Left) <> _state.windowWidth) or ((windowrect.Bottom - windowrect.Top) <> _state.windowHeight) then begin needAdjustment := true; end; // If we don't need to do anything, bail if not needAdjustment then exit; // Move and resize application window result := MoveAndResizeWindow(movewindow); end; end.
unit VBServer_Methods; interface uses System.SysUtils, System.Classes, System.Json, System.StrUtils, System.Types, DataSnap.DSServer, System.Win.Registry, Winapi.Windows, System.IOUtils, System.Variants, System.IniFiles, DataSnap.DSAuth, Data.FireDACJSONReflect, MyClasses, FireDAC.Stan.StorageJSON, DataSnap.DSProviderDataModuleAdapter, 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.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageBin, FireDAC.Phys.ODBCBase, FireDAC.Comp.UI, {FireDAC.Phys.IBDef,}FireDAC.Phys.IBBase, FireDAC.Phys.IB, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.Phys.IBWrapper; type {$METHODINFO ON} TVBServerMethods = class(TDSServerModule) conFB: TFDConnection; FDGUIxWaitCursor: TFDGUIxWaitCursor; FDPhysMSSQLDriverLink: TFDPhysMSSQLDriverLink; FDStanStorageJSONLink: TFDStanStorageJSONLink; FDStanStorageBinLink: TFDStanStorageBinLink; qrySQL: TFDQuery; cmdGeneric: TFDCommand; sprGeneric: TFDStoredProc; trnFB: TFDTransaction; qryInsert: TFDQuery; procedure DSServerModuleCreate(Sender: TObject); procedure DSServerModuleDestroy(Sender: TObject); procedure conFBBeforeConnect(Sender: TObject); procedure conFBError(ASender, AInitiator: TObject; var AException: Exception); private { Private declarations } FErrorMsg: string; FObjectList: TStringList; function ParseServerErrorMsg(ServerErrorMsg: string): string; public { Public declarations } function GetData(Request, ParameterList, Generatorname, Tablename, DataSetName: string; var Response: string): TFDJSONDataSets; function ExecuteSQLCommand(Request: string): string; function ExecuteStoredProcedure(ProcedureName, ParameterList, ParameterValues: string; var OutputValues: string): string; function GetFileVersion(Request: string; var Response: string): string; function DownloadFile(Request: string; var Response: string; var Size: Int64): TStream; function ModifyRecord(Request: string; var Response: string): string; // IDRank value: // 0 = Last inserted ID value; // 1 = Next ID value. function GetID(GeneratorName: string; IDRank: Integer): string; function GetUseCount(Request: string): string; function GetFieldValue(Request: string; FieldTypeID: Integer; var Response: string): string; function ApplyDataUpdates(const DeltaList: TFDJSONDeltas; var ReplyMessage: string; GeneratorName, TableName: string; ScriptID: Integer; NeedReturnID: Boolean): string; end; {$METHODINFO Off} Query = class(TFDQuery); implementation {$R *.dfm} uses RUtils, CommonServiceValues; { TVBServerMethods } procedure TVBServerMethods.DSServerModuleCreate(Sender: TObject); begin FObjectList := TStringList.Create; end; procedure TVBServerMethods.DSServerModuleDestroy(Sender: TObject); begin FObjectList.Free; end; function TVBServerMethods.ModifyRecord(Request: string; var Response: string): string; var DBAction: string; begin try DBAction := Response; Result := '0'; if SameText(DBAction, 'INSERT') then begin qrySQL.Open(Request); Result := IntToStr(qrySQL.FieldByName('ID').AsInteger); end else begin qrySQL.SQL.Clear; qrySQL.SQL.Text := Request; qrySQL.ExecSQL(Request); end; Response := 'RESPONSE=SUCCESS'; except on E: Exception do begin Response := 'RESPONSE=ERROR' + PIPE + 'ERROR_MESSAGE=' + E.Message; conFB.Rollback; end; end; end; function TVBServerMethods.GetData(Request, ParameterList, Generatorname, Tablename, DataSetName: string; var Response: string): TFDJSONDataSets; var InputList, ScriptIDList, ParameterListing, SingleParameter, DataSetNameList: TStringList; I, X: Integer; Query: TFDQuery; SQL, TheDataSetName: string; begin { Notes to developer: 2. The request for data comes from the client in the form of delimited string values. 3. InputList contains the full un-parsed request string. 4. ScriptIDList contains the list of ID's used to retrieve the SQL statement needed to fetch data from the server. } Response := ''; InputList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); ScriptIDList := RUtils.CreateStringList(COMMA, DOUBLE_QUOTE); ParameterListing := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); SingleParameter := RUtils.CreateStringList(SEMI_COLON, DOUBLE_QUOTE); DataSetNameList := RUtils.CreateStringList(SEMI_COLON, DOUBLE_QUOTE); try InputList.DelimitedText := Request; ParameterListing.DelimitedText := ParameterList; SingleParameter.DelimitedText := ParameterListing.Values['PARAMETER_LIST']; for I := SingleParameter.Count - 1 downto 0 do if Length(SingleParameter[I]) = 0 then SingleParameter.Delete(I); // Create the Dataset list that will contain the data to be passed back to // the client. Result := TFDJSONDataSets.Create; FObjectList.Clear; ScriptIDList.DelimitedText := InputList.Values['SQL_STATEMENT_ID']; // Iterate the list of ID's to retriev the SQL Statements. for I := 0 to ScriptIDList.Count - 1 do begin SQL := Format(SQL_STATEMENT, [ScriptIDList[I]]); qrySQL.Open(SQL); // Code added by CVG on 26/06/2019. This is to accommodate datasets // with different names but getting their data from the same DB table // on the client side. DataSetNameList.DelimitedText := qrySQL.FieldByName('DATASET_NAME').AsString; for X := 0 to DataSetNameList.Count - 1 do if SameText(DataSetName, DataSetNameList[X]) then begin TheDataSetName := DataSetname; // qrySQL.FieldByName('DATASET_NAME').AsString; Break; end; Query := TFDQuery.Create(nil); Query.Name := TheDataSetName; // End of code added by CVG on 26/06/2019 // Code deprecated by CVG on 26/06/2019 // Query := TFDQuery.Create(nil); // Query.Name := qrySQL.FieldByName('DATASET_NAME').AsString; // Set generator name so that we can send the newly generted GEN_ID // back to the client. if Length(Trim(Generatorname)) > 0 then Query.UpdateOptions.Generatorname := Generatorname; // NB!! Must set the table/view name here. if Length(Trim(Tablename)) > 0 then Query.UpdateOptions.UpdateTableName := Tablename; Query.Connection := conFB; Query.FilterOptions := [foCaseInsensitive]; Query.FormatOptions.DataSnapCompatibility := True; FObjectList.Add(ComponentToString(Query)); Query := (StringToComponent(FObjectList[I]) as TFDQuery); SQL := qrySQL.FieldByName('SQL_STATEMENT').AsString; if SingleParameter.Count > 0 then SQL := Format(SQL, BuildFormatArray(SingleParameter.Count, SingleParameter)); Query.Open(SQL); Response := 'DATA_FOUND'; if Query.IsEmpty then Response := 'NO_DATA'; // Add the data to the dataset list to be returned to the client. TFDJSONDataSetsWriter.ListAdd(Result, Query.Name, Query); end; finally InputList.Free; ScriptIDList.Free; ParameterListing.Free; SingleParameter.Free; end; end; //function TVBServerMethods.AMethod(Request: string; var Response: string): string; //begin // Result := 'AMethod'; //end; function TVBServerMethods.ApplyDataUpdates(const DeltaList: TFDJSONDeltas; var ReplyMessage: string; GeneratorName, TableName: string; ScriptID: Integer; NeedReturnID: Boolean): string; var ApplyDeltaUpdate: IFDJSONDeltasApplyUpdates; ListCount, I, ErrorCount: Integer; S, SQL: string; Query: TFDQuery; ApplyErrors: TFDJSONErrors; ErrorList: TStringList; begin Result := ''; FErrorMsg := ''; ErrorCount := 0; ErrorList := RUtils.CreateStringList(COMMA, DOUBLE_QUOTE); ReplyMessage := 'ID=0'; // Create the apply object and populate it with the delta from the // FDMemTable(s) generated by the client. ApplyDeltaUpdate := TFDJSONDeltasApplyUpdates.Create(DeltaList); // Get a count of the number of datasets to be updated. ListCount := ApplyDeltaUpdate.Count; FObjectList.Clear; for I := 0 to ListCount - 1 do begin // Get the Query name for the dataset that is used to transact. S := ApplyDeltaUpdate.Items[I].Key; SQL := Format(SQL_STATEMENT, [ScriptID.ToString]); // Get the SQL statement used to generate field data. qrySQL.Open(Format(SQL_STATEMENT, [ScriptID.ToString])); SQL := qrySQL.FieldByName('SQL_STATEMENT').AsString; // Create the query that will be used to perform the transaction. Query := TFDQuery.Create(nil); // Setup various properties. Query.Name := S; Query.Connection := conFB; Query.FilterOptions := [foCaseInsensitive]; Query.FormatOptions.DataSnapCompatibility := True; // Render the query component to it's string representation. FObjectList.Add(ComponentToString(Query)); // Now set the query to the correct one for applying updates. Query := (StringToComponent(FObjectList[I]) as TFDQuery); if Length(Trim(GeneratorName)) > 0 then Query.UpdateOptions.Generatorname := GeneratorName; // NB!! Must set the table/view name here. if Length(Trim(TableName)) > 0 then Query.UpdateOptions.UpdateTableName := TableName; // Add the SQL text for this query. This is required for FireDAC to be // able to update the correct table in the DB. Query.SQL.Add(SQL); // Do the actual updates for this dataset. ErrorCount := ApplyDeltaUpdate.ApplyUpdates(S, Query.Command); ApplyErrors := ApplyDeltaUpdate.Errors; ErrorList.AddStrings(ApplyErrors.Strings) end; if ErrorCount > 0 then Result := 'RESPONSE=ERROR|ERROR_MESSAGE=' + ParseServerErrorMsg(ErrorList.Text) else begin // Get the value of the newly inserted ID. if NeedReturnID then begin if Length(Trim(GeneratorName)) > 0 then begin SQL := 'SELECT GEN_ID(' + GeneratorName + ', 0) AS ID FROM RDB$DATABASE;'; Query.Open(SQL); if not VarIsNull(Query.FieldByName('ID').AsInteger) then ReplyMessage := 'ID=' + IntToStr(Query.FieldByName('ID').AsInteger); end; end; Result := 'RESPONSE=SUCCESS'; end; end; function TVBServerMethods.ParseServerErrorMsg(ServerErrorMsg: string): string; var Posn: Integer; begin Result := ServerErrorMsg; Posn := Pos(AnsiUpperCase('violation of primary'), AnsiUpperCase(ServerErrorMsg)); if Posn > 0 then begin Result := 'Violation of primary key on table: %s '; Posn := Pos(AnsiUpperCase('problematic key value'), AnsiUpperCase(ServerErrorMsg)); if Posn > 0 then Result := Result + AnsiRightStr(ServerErrorMsg, Length(ServerErrorMsg) - Posn + 1); end; Posn := Pos(AnsiUpperCase('attempt to store duplicate value'), AnsiUpperCase(ServerErrorMsg)); if Posn > 0 then begin Result := 'Attempt to store duplicate field values: '; Posn := Pos(AnsiUpperCase('Problematic key value is'), AnsiUpperCase(ServerErrorMsg)); if Posn > 0 then begin Result := Result + AnsiRightStr(ServerErrorMsg, Length(ServerErrorMsg) - Posn + 1); // Result := ReplaceText(Result, 'Problematic key value is', 'Duplicate field values: '); Result := ReplaceText(Result, 'Problematic key value is', ''); Result := ReplaceText(Result, '(', ''); Result := ReplaceText(Result, ')', ''); Result := ReplaceText(Result, '"', ''); Result := ReplaceText(Result, '''', ''); end; end; end; function TVBServerMethods.ExecuteSQLCommand(Request: string): string; //var // InputList: TStringList; begin // InputList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); // InputList.DelimitedText := Request; cmdGeneric.CommandText.Clear; cmdGeneric.CommandText.Add(Request); // cmdGeneric.CommandText.Add(InputList.Values['REQUEST']); // try conFB.StartTransaction; try cmdGeneric.Execute; conFB.Commit; Result := 'RESPONSE=SUCCESS'; except on E: Exception do begin Result := 'RESPONSE=ERROR' + PIPE + 'ERROR_MESSAGE=' + E.Message; conFB.Rollback; end; end; // finally // InputList.Free; // end; end; //function TRCShellServerMethods.ExecuteStoredProcedure(ProcedureName, // Parameterlist, ParameterValues: string): string; //var // ParamList, ParamValues: TStringList; // I: Integer; // Param: TFDParam; //begin // Result := 'RESPONSE=SUCCESS'; // ParamList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); // ParamValues := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); // sprGeneric.StoredProcName := ProcedureName; // ParamList.DelimitedText := ParameterList; // ParamValues.DelimitedText := ParameterValues; // sprGeneric.Prepare; // // for I := 0 to ParamList.Count - 1 do // begin // sprGeneric.ParamByName(ParamList[I]).Value := ParamValues[I]; //// sprGeneric.ParamByName(ParamList[I]).Value := ParamValues.ValueFromIndex[I]; // end; // // conMSSQL.StartTransaction; // // try // sprGeneric.ExecProc; // conMSSQL.Commit; // except on E: Exception do // begin // Result := 'RESPONSE=ERROR|ERROR_MESSAGE=' + E.Message; // conMSSQL.Rollback; // end; // end; //end; function TVBServerMethods.ExecuteStoredProcedure(ProcedureName, ParameterList, ParameterValues: string; var OutputValues: string): string; var ParamList: TStringList; // PIPE Delimited list of parameter names ParamValues: TStringList; // PIPE Delimited list of parameter values I: Integer; begin Result := 'RESPONSE=SUCCESS'; ParamList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); ParamValues := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); sprGeneric.StoredProcName := ProcedureName; ParamList.DelimitedText := ParameterList; ParamValues.DelimitedText := ParameterValues; sprGeneric.Prepare; try // if Length(Trim(ParameterList)) > 0 then // begin // InputList.DelimitedText := ParameterList; // sprGeneric.Close; // sprGeneric.StoredProcName := ''; // sprGeneric.Params.Clear; // sprGeneric.StoredProcName := ProcedureName; // sprGeneric.Prepare; for I := 0 to ParamList.Count - 1 do begin sprGeneric.ParamByName(ParamList[I]).Value := ParamValues[I]; // sprGeneric.ParamByName(ParamList[I]).Value := ParamValues.ValueFromIndex[I]; end; // if SameText(ProcedureName, 'SP_GEN_BILLABLE_SUMMARY_TABLE') then // begin // sprGeneric.ParamByName('USER_ID').Value := InputList[0]; // sprGeneric.ParamByName('THE_PERIOD').Value := InputList[1]; // end // // else if SameText(ProcedureName, 'SP_DELETE_ZERO_BILLABLE_VALUES') then // sprGeneric.ParamByName('USER_ID').Value := InputList[0]; try sprGeneric.Execute; except on E: Exception do Result := 'RESPONSE=ERROR|ERROR_MESSAGE=' + E.Message; end; for I := 0 to ParamList.Count - 1 do begin if sprGeneric.Params[I].ParamType = ptOutput then if I > 0 then OutputValues := OutputValues + PIPE; OutputValues := OutputValues + sprGeneric.ParamByName(ParamList[I]).Name + '=' + VarToStr(sprGeneric.ParamByName(ParamList[I]).Value); end; finally ParamList.Free; ParamValues.Free; end; end; procedure TVBServerMethods.conFBBeforeConnect(Sender: TObject); var ConIniFile: TIniFile; IniList: TStringList; SectionName: string; RegKey: TRegistry; begin // conFB.Params.Clear; // conFB.Params.LoadFromFile('C:\Data\Firebird\VB\ConnectionDefinitions.ini'); // conFB.Params.LoadFromFile(CONNECTION_DEFINITION_FILE { + 'ConnectionDefinitions.ini'}); IniList := RUtils.CreateStringList(COMMA, DOUBLE_QUOTE); RegKey := TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY); RegKey.RootKey := HKEY_CURRENT_USER; try RegKey.OpenKey(KEY_DATABASE, True); if not RegKey.ValueExists('Con Def Name') then RegKey.WriteString('Con Def Name', 'VB'); {$IFDEF DEV} Sectionname := 'VB Dev'; {$ELSE} SectionName := RegKey.ReadString('Con Def Name'); {$ENDIF} finally RegKey.Free end; ConIniFile := TIniFile.Create(CONNECTION_DEFINITION_FILE); try ConIniFile.ReadSectionValues(SectionName, IniList); conFB.Params.Values['DriverID'] := IniList.Values['DriverID']; conFB.Params.Values['Server'] := IniList.Values['Server']; conFB.Params.Values['Database'] := IniList.Values['Database']; conFB.Params.Values['User_Name'] := IniList.Values['User_Name']; conFB.Params.Values['Password'] := IniList.Values['Password']; conFB.Params.Values['Protocol'] := IniList.Values['Protocol']; conFB.Params.Values['Pooled'] := IniList.Values['Pooled']; conFB.Params.Values['CharacterSet'] := IniList.Values['CharacterSet']; conFB.Params.Values['CreateDatabase'] := IniList.Values['CreateDatabase']; conFB.ResourceOptions.AssignedValues := [rvAutoReconnect]; conFB.ResourceOptions.AutoReconnect := StringToBoolean(IniList.Values['ResourceOptions.AutoReconnect']); finally IniList.Free; ConIniFile.Free; end; end; procedure TVBServerMethods.conFBError(ASender, AInitiator: TObject; var AException: Exception); var MyException: EFDDBEngineException; begin if AException is EFDDBEngineException then begin MyException := EFDDBEngineException(AException); if MyException.Kind = ekRecordLocked then MyException.Message := 'Please, try the operation later. At moment, the record is busy' else if (MyException.Kind = ekUKViolated) and SameText(MyException[0].ObjName, 'UniqueKey_Orders') then MyException.Message := 'Please, provide the unique order information. It seems, your order was already put'; end; end; function TVBServerMethods.GetFieldValue(Request: string; FieldTypeID: Integer; var Response: string): string; begin Result := ''; qrySQL.Open(Request); case FieldTypeID of 0: Result := qrySQL.FieldByName('FIELD_VALUE').AsString; 1: Result := IntToStr(qrySQL.FieldByName('FIELD_VALUE').AsInteger); 2: Result := FloatToStr(qrySQL.FieldByName('FIELD_VALUE').AsFloat); 3: Result := FormatDateTime('yyyy-MM-dd hh:mm:ss', qrySQL.FieldByName('FIELD_VALUE').AsDateTime); end; // if FieldTypeName = 'String' then // Result := qrySQL.FieldByName('FIELD_VALUE').AsString // // else if FieldTypeName = 'Integer' then // Result := IntToStr(qrySQL.FieldByName('FIELD_VALUE').AsInteger) // // else if FieldTypeName = 'Float' then // Result := FloatToStr(qrySQL.FieldByName('FIELD_VALUE').AsFloat) // // else if FieldTypeName = 'DateTime' then // Result := FormatDateTime('yyyy-MM-dd hh:mm:ss', qrySQL.FieldByName('FIELD_VALUE').AsDateTime); end; //function TVBServerMethods.GetFielValue(Request, FieldTypeName: string; var Response): 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 // // Result := ''; // qrySQL.Open(Request); // // if FieldTypeName = 'String' then // Result := qrySQL.FieldByName('FIELD_VALUE').AsString // // else if FieldTypeName = 'Integer' then // Result := IntToStr(qrySQL.FieldByName('FIELD_VALUE').AsInteger) // // else if FieldTypeName = 'Float' then // Result := FloatToStr(qrySQL.FieldByName('FIELD_VALUE').AsFloat) // // else if FieldTypeName = 'DateTime' then // Result := FormatDateTime('yyyy-MM-dd hh:mm:ss', qrySQL.FieldByName('FIELD_VALUE').AsDateTime); // // // case FieldType of // // ftString, ftWideString: // // Result := qrySQL.FieldByName('FIELD_VALUE').AsString; // // // // ftSmallint, ftInteger, ftWord, ftBoolean: // // Result := IntToStr(qrySQL.FieldByName('FIELD_VALUE').AsInteger); // // // // // ftBoolean: // // // begin // // // // // // end; // // // // ftFloat, ftCurrency, ftExtended, ftBCD: // // Result := FloatToStr(qrySQL.FieldByName('FIELD_VALUE').AsFloat); // // // // ftDate, ftTime, ftDateTime: // // Result := FormatDateTime('yyyy-MM-dd', qrySQL.FieldByName('FIELD_VALUE').AsDateTime); // // end; //end; //function TVBServerMethods.GetFieldValue(Request: string; FieldType: TFieldType; var Response: string): string; //begin // Result := 'Get field value'; //end; function TVBServerMethods.GetFileVersion(Request: string; var Response: string): string; var InputList, IniList: TStringList; SourceFileTimeStamp, TargetFileTimeStamp: TDateTime; Folder, {aFileName, }SourceFileName, SourceTimeStampStr, TargetTimeStampStr: string; // IniFile: TIniFile; ComputerName: string; RegKey: TRegistry; begin InputList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); IniList := RUtils.CreateStringList(COMMA, DOUBLE_QUOTE); RegKey := TRegistry.Create(KEY_ALL_ACCESS); RegKey := System.Win.Registry.TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY); RegKey.RootKey := HKEY_CURRENT_USER; //{$IFDEF SHELX} // IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'VSServiceX.ini'); //{$ELSE} // IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'VSService.ini'); //{$ENDIF} try RegKey.OpenKey(KEY_RESOURCE, True); InputList.DelimitedText := Request; // IniFile.ReadSectionValues(KEY_RESOURCE, IniList); ComputerName := RUtils.GetComputer; // Deprecated by CVG on 17/08/2020 // Using ini file. // if not IniFile.ValueExists(KEY_RESOURCE, 'VB Shell Repository') then // IniFile.WriteString(KEY_RESOURCE, 'VB Shell Repository', '\\' + ComputerName + '\Data\VB\Repository\'); // // Folder := IniFile.ReadString(KEY_RESOURCE, 'VB Shell Repository', '\\' + ComputerName + '\Data\VB\Repository\'); if not RegKey.ValueExists('VB Shell Repository') then RegKey.WriteString('VB Shell Repository', '\\' + ComputerName + '\Data\VB\Repository\'); Folder := RegKey.ReadString('VB Shell Repository'); RegKey.CloseKey; TDirectory.CreateDirectory(Folder); SourceFileName := Folder + InputList.Values['FILE_NAME']; if not TFile.Exists(SourceFileName, True) then begin Result := 'RESPONSE=FILE_NOT_FOUND'; Exit; end; // Get the target file name sent by the client. This is the file on the // client side that needs to be updated. // Get the timestamp of this file. // Note to developer: DON'T USE THE DateTimeToStr function!! For some reason // even if the locale settings for date format have been set it still reads // this info in mm/dd/yyyy and NOT dd/mm/yyyy format. TargetFileTimeStamp := VarToDateTime(InputList.Values['TARGET_FILE_TIMESTAMP']); TargetTimeStampStr := FormatDateTime('yyyy-MM-dd hh:mm:ss', TargetFileTimeStamp); // Get timestamp of source file. FileAge(SourceFileName, SourceFileTimeStamp); // Get string representation of source file timestamp. SourceTimeStampStr := FormatDateTime('yyyy-MM-dd hh:mm:ss', SourceFileTimeStamp); // Compare source & target file timestamps. Send this info back to the client. // Need to send the new version timestamp back to client so that once the // new file has been copied the correct timestamp is applied to the newly // copied file. This is because when you write a stream to file the current // OS timestamp is applied and this is NOT what we want. (See client for // more info on this subject). if SourceTimeStampStr > TargetTimeStampStr then Result := 'RESPONSE=FOUND_NEW_VERSION' + PIPE + 'FILE_TIMESTAMP=' + SourceTimeStampStr else Result := 'RESPONSE=NEW_VERSION_NOT_FOUND'; finally RegKey.Free; InputList.Free; IniList.Free; // IniFile.Free; end; end; // IDRank value: // 0 = Last inserted ID value; // 1 = Next ID value. function TVBServerMethods.GetID(GeneratorName: string; IDRank: Integer): string; const INSERTED_ID = 'SELECT GEN_ID(%s, 0) AS ID FROM RDB$DATABASE'; NEXT_ID = 'SELECT GEN_ID(%s, 1) AS ID FROM RDB$DATABASE'; begin qrySQL.Close; case IDRank of 0: qrySQL.Open(Format(INSERTED_ID, [GeneratorName])); 1: qrySQL.Open(Format(NEXT_ID, [GeneratorName])); end; Result := IntToStr(qrySQL.FieldByName('ID').AsInteger); end; function TVBServerMethods.GetUseCount(Request: string): string; begin qrySQL.Close; qrySQL.Open(Request); Result := IntToStr(qrySQL.FieldByName('USE_COUNT').AsInteger); end; function TVBServerMethods.DownloadFile(Request: string; var Response: string; var Size: Int64): TStream; var Folder, aFileName, ComputerName: string; IniFile: TIniFile; RequestList: TStringList; begin IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'VSServiceX.ini'); Result := nil; ComputerName := RUtils.GetComputer; RequestList := RUtils.CreateStringList(PIPE, DOUBLE_QUOTE); RequestList.DelimitedText := Request; if not IniFile.ValueExists(KEY_RESOURCE, 'VB Shell Repository') then IniFile.WriteString(KEY_RESOURCE, 'VB Shell Repository', '\\' + ComputerName + '\Data\VB\Repository\'); Folder := IniFile.ReadString(KEY_RESOURCE, 'VB Shell Repository', '\\' + ComputerName + '\Data\VB\Repository\'); // Make sure these folders exist TDirectory.CreateDirectory(Folder); aFileName := Folder + RequestList.Values['FILE_NAME']; Response := 'RESPONSE=' + RequestList.Values['FILE_NAME']; if not TFile.Exists(aFileName, True) then begin Response := 'RESPONSE=FILE_NOT_FOUND'; Exit; end; try Result := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyNone); Size := Result.Size; Result.Position := 0; finally RequestList.Free; end; end; initialization // Specify full path to source otherwise it will try to use the RegisterClass // method from the WinApi.Windows unit. System.Classes.RegisterClass(Query); end.
unit Unit2; interface uses Graphics; var ColrBack: Tcolor; Type Tviz=class(TObject) ColrLine: Tcolor; Canvas: Tcanvas; x,y,r1,r2,l: word; Procedure Ris; virtual; abstract; Procedure Draw(bl:boolean); Procedure Show; Procedure Hide; Procedure MovTo(dx,dy:integer); end; Tkrug=class(Tviz) x1,x2,y2,y1,x10,y10: word; Constructor Create(x0,y0,r10,r20,l0:word; ColrLine0:TColor; canvas0:TCanvas); Procedure Ris;override; Procedure Bah(x10,y10:word); end; implementation Procedure Tviz.Draw; begin with Canvas do begin if bl then begin pen.Color:=colrLine; brush.Color:=clYellow; end else begin pen.Color:=ColrBack; Brush.Color:=ColrBack; end; Ris; end; end; Procedure Tviz.Show; begin Draw(true); end; Procedure Tviz.Hide; begin Draw(False); end; Procedure Tviz.MovTo; begin Hide; x:=x+dx; y:=y+dy; Show; end; Constructor TKrug.Create; begin colrLine:=colrLine0; canvas:=canvas0; x:=x0; y:=y0; x10:=x0; y10:=y0; r1:=r10; r2:=r20; l:=l0; end; Procedure Tkrug.Ris; begin x1:=x-r1; x2:=x+r1; y1:=y-r2; y2:=y+r2; with canvas do begin Ellipse(x1,y1,x2,y2); MoveTo(x,y2); LineTo(x,y2+l); end; end; Procedure Tkrug.Bah; begin Hide; with Canvas do begin Font.Size:=30; Brush.Color:=clWhite; TextOut(x10,y10,'ÁÀÕ-ÁÀÕ!!!'); end; end; end.
unit uTestResult; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, GdiPlus, GdiPlusHelpers, uData, uUTTDiagram, uTaskDiagram, uGlobals, uTasks; type TfrmTestResult = class(TForm) pnlTools: TPanel; btExit: TSpeedButton; btSaveAndSend: TSpeedButton; pnlOptions: TPanel; Label1: TLabel; btYes: TSpeedButton; btNo: TSpeedButton; chkRandom: TCheckBox; pnlDiagram: TPanel; btSaveresults: TSpeedButton; btClearResults: TSpeedButton; procedure btExitClick(Sender: TObject); procedure btClearResultsClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure chkRandomClick(Sender: TObject); procedure btNoClick(Sender: TObject); procedure btYesClick(Sender: TObject); procedure btSaveresultsClick(Sender: TObject); procedure btSaveAndSendClick(Sender: TObject); private { Private declarations } mParent: TfrmTasks; frmUTTDiagram: TfrmUTTDiagram; frmTaskDiagram: TfrmTaskDiagram; public { Public declarations } class function showUTTResults(): TModalResult; class function showTaskResults(Parent: TfrmTasks): TModalResult; end; implementation uses uOGE, math, uWait; {$R *.dfm} procedure TfrmTestResult.btClearResultsClick(Sender: TObject); begin if messageBox(handle, 'Вы уверены что хотите сбросить результаты?', 'ОГЕ', MB_YESNO or MB_ICONQUESTION) = mrYes then begin if Assigned(frmUTTDiagram) then begin frmOGE.UTT.clearUserResults(); frmUTTDiagram.refresh(chkRandom.Checked); btClearResults.Enabled := false; end else if assigned(frmTaskDiagram) then begin mParent.clearUserResults; frmTaskDiagram.Free; frmTaskDiagram := TfrmTaskDiagram.Create(self); frmTaskDiagram.Dock(pnlDiagram, pnlDiagram.ClientRect); frmTaskDiagram.showDiagram(chkRandom.Checked, true, mParent.ResultMask); btClearResults.Enabled := false; end end; end; procedure TfrmTestResult.FormResize(Sender: TObject); begin pnlOptions.Left := (pnlTools.Width div 2) - (pnlOptions.Width div 2); if Assigned(frmUTTDiagram) then begin frmUTTDiagram.refresh(chkRandom.Checked); end else if assigned(frmTaskDiagram) then begin frmTaskDiagram.refresh(chkRandom.Checked); end end; procedure TfrmTestResult.btSaveAndSendClick(Sender: TObject); begin frmWait.Show; Application.ProcessMessages; if btSaveresults.Enabled then btSaveresultsClick(Sender); try try if Assigned(frmUTTDiagram) then begin frmOGE.UTT.send; btSaveAndSend.Enabled := false; end else if assigned(frmTaskDiagram) then begin mParent.send; btSaveAndSend.Enabled := false; end; finally if not btSaveAndSend.Enabled then begin frmWait.Hide; Application.ProcessMessages; messageBox(handle, 'Отправлено.', 'ОГЭ', MB_OK or MB_ICONINFORMATION); end; end; except frmOGE.Sync.saveLog; frmWait.Hide; Application.ProcessMessages; messageBox(handle, 'Во время отправления произошла ошибка. '#13 + 'Попробуйте снова через несколько минут.', 'ОГЭ', MB_OK or MB_ICONERROR); end; end; procedure TfrmTestResult.btSaveresultsClick(Sender: TObject); begin if Assigned(frmUTTDiagram) then begin frmOGE.UTT.saveResults(); btSaveresults.Enabled := false; end else if assigned(frmTaskDiagram) then begin mParent.saveResults; btSaveresults.Enabled := false; end end; procedure TfrmTestResult.btExitClick(Sender: TObject); begin if btSaveresults.Enabled and (MessageBox(handle, 'Сохранить результаты?', 'ОГЭ', MB_YESNO or MB_ICONQUESTION) = mrYes) then btSaveresultsClick(Sender); modalResult := mrCancel end; procedure TfrmTestResult.btNoClick(Sender: TObject); begin modalResult := mrNo; end; procedure TfrmTestResult.btYesClick(Sender: TObject); begin modalResult := mrYes; end; procedure TfrmTestResult.chkRandomClick(Sender: TObject); begin if Assigned(frmUTTDiagram) then begin frmUTTDiagram.refresh(chkRandom.Checked); end; end; class function TfrmTestResult.showTaskResults(Parent: TfrmTasks): TModalResult; var frmTestResult: TfrmTestResult; begin frmTestResult := TFrmTestResult.Create(frmOGE); frmTestResult.mParent := Parent; frmTestResult.frmTaskDiagram := TfrmTaskDiagram.Create(frmTestResult); try frmTestResult.frmTaskDiagram.Dock( frmTestResult.pnlDiagram, frmTestResult.pnlDiagram.ClientRect); frmTestResult.frmTaskDiagram.showDiagram( frmTestResult.chkRandom.Checked, false, Parent.ResultMask); result := frmTestResult.ShowModal; finally freeAndNil(frmTestResult.frmTaskDiagram); freeAndNil(frmTestResult); end; end; class function TfrmTestResult.showUTTResults: TModalResult; var frmTestResult: TfrmTestResult; begin // if not Assigned(frmTestResult) then frmTestResult := TFrmTestResult.Create(frmOGE); frmTestResult.frmUTTDiagram := TfrmUTTDiagram.Create(frmTestResult); try frmTestResult.frmUTTDiagram.Dock( frmTestResult.pnlDiagram, frmTestResult.pnlDiagram.ClientRect); frmTestResult.frmUTTDiagram.showUTTDiagram(frmOGE.UTT); result := frmTestResult.showModal; finally freeAndNil(frmTestResult.frmUTTDiagram); freeAndNil(frmTestResult) end; end; end.
unit GuestBookPlugin; interface uses PluginManagerIntf, PluginIntf, ControlPanelElementIntf, Graphics, DataModuleIntf; type TGuestBookPlugin = class (TPlugin, IPlugin, IControlPanelElement, IDataModule) private FDisplayName: string; FBitmap: TBitmap; FDataPath: String; public constructor Create(Module: HMODULE; PluginManager: IPluginManager); destructor Destroy; override; function Execute: Boolean; function GetDescription: string; function GetDisplayName: string; function GetBitmap: TBitmap; function GetName: string; function Load: Boolean; procedure SetDisplayName(const Value: string); function UnLoad: Boolean; { IDataModule } function GetDataPath: String; procedure SetDataPath(const Value: String); end; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; exports RegisterPlugin; implementation uses Windows, gbMainForm, SysUtils; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; var Plugin: IInterface; begin Plugin := TGuestBookPlugin.Create(Module, PluginManager); Result := PluginManager.RegisterPlugin(Plugin); end; { TGuestBookPlugin } constructor TGuestBookPlugin.Create(Module: HMODULE; PluginManager: IPluginManager); begin inherited; FBitmap := Graphics.TBitmap.Create; FDisplayName := 'Гостевая книга'; FBitmap.Handle := LoadBitmap(Module, 'PLUGIN_ICON'); end; destructor TGuestBookPlugin.Destroy; begin FBitmap.Free; inherited; end; function TGuestBookPlugin.Execute: Boolean; begin Result := GetMainForm(FPluginManager, FDataPath) = IDOK; end; function TGuestBookPlugin.GetBitmap: Graphics.TBitmap; begin Result := FBitmap; end; function TGuestBookPlugin.GetDataPath: String; begin Result := FDataPath; end; function TGuestBookPlugin.GetDescription: string; begin Result := 'Гостевая книга'; end; function TGuestBookPlugin.GetDisplayName: string; begin Result := FDisplayName; end; function TGuestBookPlugin.GetName: string; begin Result := 'GuestBookPlugin'; end; function TGuestBookPlugin.Load: Boolean; begin Result := True; end; procedure TGuestBookPlugin.SetDataPath(const Value: String); begin FDataPath := Value; end; procedure TGuestBookPlugin.SetDisplayName(const Value: string); begin FDisplayName := Value; end; function TGuestBookPlugin.UnLoad: Boolean; begin Result := True; end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT high level routines related to searches } unit dhtsearchManager; interface uses classes,classes2,int128,dhtconsts,dhttypes,dhtsearch,sysutils; procedure findNode(id:pCU_INT128); procedure findNodeComplete(id:pCU_Int128); function alreadySearchingFor(target:pCU_INT128):boolean; procedure processResponse(target:pCU_INT128; fromIP:cardinal; fromPort:word; results:tmylist; garbageList:TMylist); procedure CheckSearches(nowt:cardinal);//every second procedure PublishHash(phash:precord_DHT_hashfile); procedure processPublishHashAck(target:pCU_INT128; fromip:cardinal; fromporT:word); function num_searches(ttype:dhttypes.tdhtsearchtype):integer; procedure processPublishKeyAck(publishID:pCU_INT128; fromip:cardinal; fromPort:word); procedure SendPublishKeyFiles(s:TDHTSearch; TargetIP:cardinal; TargetPort:word); function has_KeywordSearchWithID(ID:word):boolean; procedure ClearContacts(list:TMylist); implementation uses vars_global,helper_datetime, windows,dhtSocket,mysupernodes,dhtcontact; function has_KeywordSearchWithID(ID:word):boolean; var i:integer; s:tDHTsearch; begin result:=false; for i:=0 to DHT_Searches.count-1 do begin s:=DHT_Searches[i]; if s.m_type<>dhttypes.KEYWORD then continue; if s.m_searchID<>ID then continue; result:=true; exit; end; end; function num_searches(ttype:dhttypes.tdhtsearchtype):integer; var i:integer; s:TDHTSearch; begin result:=0; for i:=0 to DHT_Searches.count-1 do begin s:=DHT_Searches[i]; if s.m_type=ttype then inc(result); end; end; procedure SendPublishKeyFiles(s:TDHTSearch; TargetIP:cardinal; TargetPort:word); var i,offset:integer; lenItem:word; payload:string; begin offset:=0; for i:=0 to s.m_publishKeyPayloads.count-1 do begin if offset=0 then begin CU_INT128_CopyToBuffer(@s.m_target,@DHT_Buffer[2]); move(vars_global.myport,DHT_Buffer[18],2); inc(offset,20); end; payload:=s.m_publishKeyPayloads.strings[i]; lenItem:=length(payload); move(lenItem,DHT_Buffer[offset],2); inc(offset,2); move(payload[1],DHT_Buffer[offset],lenItem); inc(offset,lenItem); if offset>=9000 then begin DHT_Len_tosend:=offset; DHT_Buffer[1]:=CMD_DHT_PUBLISHKEY_REQ; DHT_Send(TargetIP,TargetPort,True); offset:=0; end; end; if offset>20 then begin DHT_Len_tosend:=offset; DHT_Buffer[1]:=CMD_DHT_PUBLISHKEY_REQ; DHT_Send(TargetIP,TargetPort,(DHT_len_tosend>200)); end; end; procedure PublishHash(phash:precord_DHT_hashfile); var s:tDHTsearch; id:CU_INT128; begin CU_INT128_CopyFromBuffer(@phash^.hashValue[0],@id); if alreadySearchingFor(@id) then exit; s:=TDHTsearch.create; s.m_type:=DHTtypes.STOREFILE; CU_INT128_Fill(@s.m_target,@id); setLength(s.m_outPayload,26); move(phash^.hashValue[0],s.m_outPayload[1],20); move(vars_global.LANIPC,s.m_outPayload[21],4); move(vars_global.myport,s.m_outPayload[25],2); // add up to 5 supernodes (len=30) if vars_global.im_firewalled then s.m_outPayload:=s.m_outPayload+mysupernodes.mysupernodes_serialize; DHT_Searches.add(s); s.startIDSearch; end; procedure ClearContacts(list:TMylist); var c:TContact; begin while (list.count>0) do begin c:=list[list.count-1]; list.delete(list.count-1); c.free; end; end; procedure processResponse(target:pCU_INT128; fromIP:cardinal; fromPort:word; results:tmylist; garbageList:TMylist); var s:tDHTsearch; i:integer; found:boolean; begin found:=false; s:=nil; for i:=0 to DHT_searches.count-1 do begin s:=DHT_searches[i]; if CU_INT128_Compare(@s.m_target,target) then begin found:=true; break; end; end; if not found then begin ClearContacts(GarbageList); exit; end; s.processResponse(fromIP, fromPort, results); end; procedure processPublishKeyAck(publishID:pCU_INT128; fromip:cardinal; fromPort:word); var s:TDHTSearch; i:integer; begin for i:=0 to DHT_Searches.count-1 do begin s:=DHT_Searches[i]; if s.m_type<>dhttypes.STOREKEYWORD then continue; if not CU_INT128_Compare(@s.m_target,publishID) then continue; inc(s.m_answers); break; end; end; procedure processPublishHashAck(target:pCU_INT128; fromip:cardinal; fromporT:word); var s:TDHTSearch; i:integer; begin for i:=0 to DHT_Searches.count-1 do begin s:=DHT_Searches[i]; if s.m_type<>dhttypes.STOREFILE then continue; if CU_INT128_Compare(@s.m_target,target) then begin inc(s.m_answers); break; end; end; end; function alreadySearchingFor(target:pCU_INT128):boolean; var i:integer; s:tDHTsearch; begin result:=False; for i:=0 to DHT_Searches.count-1 do begin s:=DHT_Searches[i]; if CU_INT128_Compare(@s.m_target, target) then begin result:=true; exit; end; end; end; procedure findNodeComplete(id:pCU_Int128); var s:tDHTsearch; begin if alreadySearchingFor(id) then exit; s:=TDHTsearch.create; s.m_type:=DHTtypes.NODECOMPLETE; CU_INT128_fill(@s.m_target,id); DHT_Searches.add(s); s.startIDSearch; end; procedure findNode(id:pCU_INT128); var s:tDHTsearch; begin if alreadySearchingFor(id) then exit; s:=TDHTsearch.create; s.m_type:=DHTtypes.NODE; CU_INT128_fill(@s.m_target,id); DHT_Searches.add(s); s.StartIDSearch; end; procedure CheckSearches(nowt:cardinal);//every second var i:integer; s:TDHTSearch; begin i:=0; while (i<DHT_Searches.count) do begin s:=DHT_Searches[i]; case s.m_type of KEYWORD:begin if s.m_created+SEARCHKEYWORD_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; if ((s.m_answers>=SEARCHKEYWORD_TOTAL) or (s.m_created+SEARCHKEYWORD_LIFETIME-SEC(20)<nowt)) then begin s.expire; inc(i); continue; end; s.CheckStatus; end; FINDSOURCE:begin if s.m_created+SEARCHFINDSOURCE_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; if ((s.m_answers>=SEARCHFINDSOURCE_TOTAL) or (s.m_created+SEARCHFINDSOURCE_LIFETIME-SEC(20)<nowt)) then begin s.expire; inc(i); continue; end; s.CheckStatus; end; NODE:begin if s.m_created+SEARCHNODE_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; s.CheckStatus; end; NODECOMPLETE:begin if s.m_created+SEARCHNODE_LIFETIME<nowt then begin DHT_m_Publish:=true; DHT_Searches.delete(i); s.free; continue; end; if ((s.m_created+SEARCHNODECOMP_LIFETIME<nowt) and (s.m_answers>=SEARCHNODECOMP_TOTAL)) then begin DHT_m_Publish:=true; DHT_Searches.delete(i); s.free; continue; end; s.CheckStatus; end; STOREFILE:begin if s.m_created+SEARCHSTOREFILE_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; if ((s.m_answers>=SEARCHSTOREFILE_TOTAL) or (s.m_created+SEARCHSTOREFILE_LIFETIME-SEC(20)<nowt)) then begin s.expire; inc(i); continue; end; s.CheckStatus; end; STOREKEYWORD:begin if s.m_created+SEARCHSTOREKEYWORD_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; if ((s.m_answers>=SEARCHSTOREKEYWORD_TOTAL) or (s.m_created+SEARCHSTOREKEYWORD_LIFETIME-SEC(20)<nowt)) then begin s.expire; inc(i); continue; end; s.CheckStatus; end else begin if s.m_created+SEARCH_LIFETIME<nowt then begin DHT_Searches.delete(i); s.free; continue; end; s.CheckStatus; end; end; inc(i); end; end; end.
unit uMensagem; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvGlowButton, dxGDIPlusClasses, Vcl.ExtCtrls, AdvSmoothLabel, AdvSmoothPanel,Vcl.Clipbrd; type TMensagem = (MsgConfirmacao,MsgInformacao); TFrmMensagem = class(TForm) PnlGeral: TAdvSmoothPanel; PnlCentral: TAdvSmoothPanel; lblTextoMensagem: TAdvSmoothLabel; ImgConfirma: TImage; ImgInfo: TImage; BtnSim: TAdvGlowButton; BtnNao: TAdvGlowButton; BtnOk: TAdvGlowButton; AdvLblAguarde: TAdvSmoothLabel; procedure BtnSimClick(Sender: TObject); procedure BtnNaoClick(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FRetorno: Boolean; procedure DesabilitaBotoesMensagem; procedure HabilitaBotoesMensagem(AMensagem : TMensagem); procedure HabilitaImageMensagem; procedure DesabilitaImagemMensagem; procedure AjustaTamanhoTexto; public { Public declarations } function Confirmacao(ATexto : String): Boolean; procedure Informacao(ATexto : String); procedure MostraMensagem(ATexto : String); procedure FechaMensagem; end; var FrmMensagem: TFrmMensagem; implementation {$R *.dfm} procedure TFrmMensagem.HabilitaBotoesMensagem(AMensagem : TMensagem); begin BtnSim.Visible := (AMensagem = MsgConfirmacao); BtnNao.Visible := BtnSim.Visible; BtnOk.Visible := not (BtnNao.Visible); end; procedure TFrmMensagem.BtnSimClick(Sender: TObject); begin FRetorno := true; close; end; procedure TFrmMensagem.AjustaTamanhoTexto; begin if lblTextoMensagem.Caption.Text.Length > 100 then lblTextoMensagem.Caption.Font.Size := 10; if lblTextoMensagem.Caption.Text.Length <=100 then lblTextoMensagem.Caption.Font.Size := 12; if lblTextoMensagem.Caption.Text.Length <=50 then lblTextoMensagem.Caption.Font.Size := 14; end; procedure TFrmMensagem.BtnNaoClick(Sender: TObject); begin FRetorno := false; close; end; procedure TFrmMensagem.BtnOkClick(Sender: TObject); begin FRetorno := true; close; end; procedure TFrmMensagem.HabilitaImageMensagem; begin ImgConfirma.Visible := BtnSim.Visible; ImgInfo.Visible := not (ImgConfirma.Visible); end; function TFrmMensagem.Confirmacao(ATexto: String): Boolean; begin if Self.Visible then close; lblTextoMensagem.Caption.Text := ATexto; HabilitaBotoesMensagem(MsgConfirmacao); HabilitaImageMensagem; AjustaTamanhoTexto; ShowModal; result := FRetorno; end; procedure TFrmMensagem.DesabilitaBotoesMensagem; begin BtnSim.Visible := false; BtnNao.Visible := BtnSim.Visible; BtnOk.Visible := BtnNao.Visible; end; procedure TFrmMensagem.DesabilitaImagemMensagem; begin ImgConfirma.Visible := false; ImgInfo.Visible := ImgConfirma.Visible; end; procedure TFrmMensagem.FechaMensagem; begin close; end; procedure TFrmMensagem.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F10 then Clipboard.AsText := lblTextoMensagem.Caption.Text; end; procedure TFrmMensagem.FormShow(Sender: TObject); begin AdvLblAguarde.Visible := ((not BtnSim.Visible) and (not BtnNao.Visible) and (not BtnOk.Visible)); end; procedure TFrmMensagem.Informacao(ATexto: String); begin if Self.Visible then close; lblTextoMensagem.Caption.Text := ATexto; HabilitaBotoesMensagem(MsgInformacao); HabilitaImageMensagem; AjustaTamanhoTexto; ShowModal; end; procedure TFrmMensagem.MostraMensagem(ATexto: String); begin lblTextoMensagem.Caption.Text := ATexto; DesabilitaBotoesMensagem; DesabilitaImagemMensagem; AjustaTamanhoTexto; Self.Show; Self.BringToFront; end; end.
unit untFuncionario; interface uses untDependente, Generics.Collections, System.SysUtils; type TFuncionario = class private FId_Funcionario: Integer; FNome: String; FCPF: String; FSalario: Double; FListaDependentes: TObjectList<TDependente>; function GetId_Funcionario: Integer; function GetNome: String; function GetCPF: String; function GetSalario: Double; function GetListaDependentes: TObjectList<TDependente>; procedure SetId_Funcionario(const Value: Integer); procedure SetNome(const Value: String); procedure SetCPF(const Value: String); procedure SetSalario(const Value: Double); procedure SetListaDependentes(const Value: TObjectList<TDependente>); public constructor Create; destructor Destroy; override; property Id_Funcionario: Integer read GetId_Funcionario write SetId_Funcionario; property Nome: String read GetNome write SetNome; property CPF: String read GetCPF write SetCPF; property Salario: Double read GetSalario write SetSalario; property ListaDependentes: TObjectList<TDependente> read GetListaDependentes write SetListaDependentes; end; implementation { TFuncionario } constructor TFuncionario.Create; begin FListaDependentes := TObjectList<TDependente>.Create; end; destructor TFuncionario.Destroy; begin FreeAndNil(FListaDependentes); inherited; end; function TFuncionario.GetCPF: String; begin Result := FCPF; end; function TFuncionario.GetId_Funcionario: Integer; begin Result := FId_Funcionario; end; function TFuncionario.GetListaDependentes: TObjectList<TDependente>; begin Result := FListaDependentes; end; function TFuncionario.GetNome: String; begin Result := FNome; end; function TFuncionario.GetSalario: Double; begin Result := FSalario; end; procedure TFuncionario.SetCPF(const Value: String); begin FCPF := Value; end; procedure TFuncionario.SetId_Funcionario(const Value: Integer); begin FId_Funcionario := Value; end; procedure TFuncionario.SetListaDependentes(const Value: TObjectList<TDependente>); begin FListaDependentes := Value; end; procedure TFuncionario.SetNome(const Value: String); begin FNome := Value; end; procedure TFuncionario.SetSalario(const Value: Double); begin FSalario := Value; end; end.
unit ListMediaFiles; interface uses Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Grid, FMX.Layouts, MediaFile, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, System.Bindings.Expression, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, MediaFilesController; type TfrmListMediaFiles = class(TForm) TopLabel: TLabel; BottomLayout: TLayout; ButtonLayout: TLayout; btClose: TButton; btEdit: TButton; CenterLayout: TLayout; Grid: TStringGrid; StringColumn1: TStringColumn; StringColumn2: TStringColumn; StringColumn3: TStringColumn; StringColumn4: TStringColumn; btNewSong: TButton; btDelete: TButton; StringColumn5: TStringColumn; StringColumn6: TStringColumn; btNewVideo: TButton; BindScope1: TBindScope; BindingsList1: TBindingsList; BindGridList1: TBindGridList; procedure btEditClick(Sender: TObject); procedure btDeleteClick(Sender: TObject); procedure btNewSongClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btNewVideoClick(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BindGridList1AssigningValue(Sender: TObject; AssignValueRec: TBindingAssignValueRec; var Value: TValue; var Handled: Boolean); private FController: TMediaFilesController; FMediaFiles: TList<TMediaFile>; procedure LoadMediaFiles; function GetSelectedMediaFile: TMediaFile; end; implementation uses Song, Video, EditAlbum, EditSong, EditVideo; {$R *.fmx} procedure TfrmListMediaFiles.btEditClick(Sender: TObject); var MediaFile: TMediaFile; frmEditSong: TfrmEditSong; frmEditVideo: TfrmEditVideo; begin MediaFile := GetSelectedMediaFile; if MediaFile = nil then Exit; if MediaFile is TSong then begin frmEditSong := TfrmEditSong.Create(Self); try frmEditSong.SetSong(TSong(MediaFile).Id); frmEditSong.ShowModal; if frmEditSong.ModalResult = mrOk then LoadMediaFiles; finally frmEditSong.Free; end; end else if MediaFile is TVideo then begin frmEditVideo := TfrmEditVideo.Create(Self); try frmEditVideo.SetVideo(TVideo(MediaFile).Id); frmEditVideo.ShowModal; if frmEditVideo.ModalResult = mrOk then LoadMediaFiles; finally frmEditVideo.Free; end; end; end; procedure TfrmListMediaFiles.BindGridList1AssigningValue(Sender: TObject; AssignValueRec: TBindingAssignValueRec; var Value: TValue; var Handled: Boolean); begin if TBindingExpression(AssignValueRec.Expression).Source = BindGridList1.ColumnExpressions[0].FormatCellExpressions[0].SourceExpression then begin if Value.AsObject is TSong then Value := 'Song' else Value := 'Video'; end; end; procedure TfrmListMediaFiles.btDeleteClick(Sender: TObject); var MediaFile: TMediaFile; Msg: string; begin MediaFile := GetSelectedMediaFile; if MediaFile = nil then Exit; Msg := 'Are you sure you want to delete Media File "' + MediaFile.MediaName + '"?'; if MessageDlg(Msg, TMsgDlgType.mtWarning, mbYesNo, 0) = mrYes then begin FController.DeleteMediaFile(MediaFile); LoadMediaFiles; end; end; procedure TfrmListMediaFiles.btNewSongClick(Sender: TObject); var frmEditSong: TfrmEditSong; begin frmEditSong := TfrmEditSong.Create(Self); try frmEditSong.ShowModal; if frmEditSong.ModalResult = mrOk then LoadMediaFiles; finally frmEditSong.Free; end; end; procedure TfrmListMediaFiles.btNewVideoClick(Sender: TObject); var frmEditVideo: TfrmEditVideo; begin frmEditVideo := TfrmEditVideo.Create(Self); try frmEditVideo.ShowModal; if frmEditVideo.ModalResult = mrOk then LoadMediaFiles; finally frmEditVideo.Free; end; end; procedure TfrmListMediaFiles.LoadMediaFiles; begin BindScope1.Active := False; FMediaFiles.Free; FMediaFiles := FController.GetAllMediaFiles; BindScope1.DataObject := FMediaFiles; BindScope1.Active := True; end; procedure TfrmListMediaFiles.FormCreate(Sender: TObject); begin FController := TMediaFilesController.Create; LoadMediaFiles; end; procedure TfrmListMediaFiles.FormDestroy(Sender: TObject); begin FMediaFiles.Free; FController.Free; end; function TfrmListMediaFiles.GetSelectedMediaFile: TMediaFile; begin if Grid.Selected < 0 then Exit(nil); Result := FMediaFiles[Grid.Selected]; end; procedure TfrmListMediaFiles.GridDblClick(Sender: TObject); begin btEditClick(Sender); end; end.
namespace RemObjects.Elements.TLS; uses libmbedtls; type TLSException = public class(Exception) end; ProcFN = function(aCtx: ^Void; aData: ^Byte; aLen: IntPtr): IntPtr; X509Certificate = public class(IDisposable) assembly fCAValid: Boolean; fCA: mbedtls_x509_crt; public constructor; begin mbedtls_x509_crt_init(@fCA); fCAValid := true; end; method Load(aData: array of Byte); begin TLSStream.FailError('mbedtls_x509_crt_parse', mbedtls_x509_crt_parse(@fCA, (@aData[0]), length(aData))); end; method Load(aFN: String); begin using fs := new FileStream(aFN, FileMode.Open, FileAccess.Read) do begin var lByte := new Byte[fs.Length+1]; fs.Read(lByte, lByte.Length); Load(lByte); end; end; finalizer; begin Dispose; end; method Dispose; begin if fCAValid then mbedtls_x509_crt_free(@fCA); fCAValid := false; end; end; PrivateKey = public class(IDisposable) assembly fPKValid: Boolean; fPK: mbedtls_pk_context; public constructor; begin mbedtls_pk_init(@fPK); fPKValid := true; end; method Load(aData: array of Byte; aPassword: String); begin var lPW := if aPassword = nil then nil else Encoding.UTF8.GetBytes(aPassword); TLSStream.FailError('mbedtls_pk_parse_key', mbedtls_pk_parse_key(@fPK, (@aData[0]), length(aData), if (lPW = nil) or (length(lPW) = 0) then nil else @lPW[0], length(lPW))); end; method Load(aFN: String; aPassword:String); begin using fs := new FileStream(aFN, FileMode.Open, FileAccess.Read) do begin var lByte := new Byte[fs.Length+1]; fs.Read(lByte, lByte.Length); Load(lByte, aPassword); end; end; finalizer; begin Dispose; end; method Dispose; begin if fPKValid then mbedtls_pk_free(@fPK); fPKValid := false; end; end; TLSStream = public class(Stream) private fSession: mbedtls_ssl_context; fConfig: mbedtls_ssl_config; fMy, fCA: X509Certificate; fPW: PrivateKey; fVerify: Boolean; fDidHandshake: Boolean; fUnderlyingStream: Stream; class var fRNG: mbedtls_ctr_drbg_context; class var fEntropy: mbedtls_entropy_context; // This isn't used but forces the compiler to link these symbols. class method Dummy; begin rtl.lstrlenW(nil); rtl.FindClose(nil); rtl.QueryPerformanceCounter(nil); rtl.QueryPerformanceFrequency(nil); end; class constructor; begin mbedtls_entropy_init(@fEntropy); FailError('mbedtls_ctr_drbg_seed', mbedtls_ctr_drbg_seed(@fRNG, @mbedtls_entropy_func, @fEntropy, nil, 0)); end; public property CanRead: Boolean read true; override; property CanWrite: Boolean read true; override; property CanSeek: Boolean read false; override; method IsValid: Boolean; override; begin exit fUnderlyingStream <> nil; end; constructor(aStream: Stream; aServer: Boolean); begin if aStream = nil then raise new ArgumentException('aStraem is not set'); mbedtls_ssl_init(@fSession); mbedtls_ssl_config_init(@fConfig); mbedtls_ssl_conf_rng( @fConfig, @mbedtls_ctr_drbg_random, @fRNG ); FailError('mbedtls_ssl_config_defaults', mbedtls_ssl_config_defaults(@fConfig, if aServer then MBEDTLS_SSL_IS_SERVER else MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)); fUnderlyingStream := aStream; end; method SetVerifyTLS(aValue: Boolean); begin fVerify := aValue; mbedtls_ssl_conf_authmode(@fConfig, if aValue then MBEDTLS_SSL_VERIFY_OPTIONAL else MBEDTLS_SSL_VERIFY_NONE); end; method SetCAChain(aChain: X509Certificate); begin fCA := aChain; mbedtls_ssl_conf_ca_chain( @fConfig, @aChain.fCA, nil); end; method SetCertificate(aCert: X509Certificate; aPrivateKey: PrivateKey); begin fMy := aCert; fPW := aPrivateKey; FailError('mbedtls_ssl_conf_own_cert', mbedtls_ssl_conf_own_cert( @fConfig, @aCert.fCA, @aPrivateKey.fPK)); end; class method FailError(s: String; aError: Integer); assembly; begin if aError = 0 then exit; var lBuf: array[0..1024] of AnsiChar; mbedtls_strerror(aError, @lBuf[0], 1024); raise new TLSException('Method '+s+' failed with error '+String.FromPAnsiChars(@lBuf[0], 1024)+' ('+aError+')'); end; method Initialize(aHostname: String); begin if fDidHandshake then exit; fDidHandshake := true; FailError('mbedtls_ssl_setup', mbedtls_ssl_setup(@fSession, @fConfig)); FailError('mbedtls_ssl_set_hostname', mbedtls_ssl_set_hostname(@fSession, aHostname)); var lReceive: ProcFN := @IntReceive; var lSend: ProcFN := @IntSend; mbedtls_ssl_set_bio(@fSession, InternalCalls.Cast(self), ^Void(lSend), ^Void(lReceive), nil); loop begin var lRes := mbedtls_ssl_handshake(@fSession); if lRes = 0 then break; if lRes in [MBEDTLS_ERR_SSL_WANT_READ, MBEDTLS_ERR_SSL_WANT_WRITE] then continue; FailError('mbedtls_ssl_handshake', lRes); end; if fVerify then begin var flags := mbedtls_ssl_get_verify_result(@fSession); if &flags <> 0 then begin var vrfy_buf: array[0..512] of AnsiChar; mbedtls_x509_crt_verify_info(vrfy_buf, sizeof( vrfy_buf ), " ! ", flags ); raise new TLSException('Error verifying certificate '+String.FromPAnsiChars(vrfy_buf)); end; end; end; class method IntReceive(aCtx: ^Void; aData: ^Byte; aLen: IntPtr): IntPtr; begin var lSelf := InternalCalls.Cast<TLSStream>(aCtx); exit lSelf.fUnderlyingStream.Read(aData, aLen); end; class method IntSend(aCtx: ^Void; aData: ^Byte; aLen: IntPtr): IntPtr; begin var lSelf := InternalCalls.Cast<TLSStream>(aCtx); exit lSelf.fUnderlyingStream.Write(aData, aLen); end; method Close; override; begin if fUnderlyingStream <> nil then begin mbedtls_ssl_close_notify(@fSession); fUnderlyingStream.Close; mbedtls_ssl_free(@fSession); mbedtls_ssl_config_free(@fConfig); fUnderlyingStream := nil; end; end; finalizer; begin Close; end; method Seek(Offset: Int64; Origin: SeekOrigin): Int64; override; begin raise new NotSupportedException; end; method &Read(aSpan: Span<Byte>): Integer; override; begin result := mbedtls_ssl_read(@fSession, aSpan.Pointer, aSpan.Length); if result < 0 then exit 0; end; method &Write(aSpan: ImmutableSpan<Byte>): Integer; override; begin result := mbedtls_ssl_write(@fSession, aSpan.Pointer, aSpan.Length); if result < 0 then exit 0; end; end; end.
unit iaDemo.ThreadStateStress.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.SyncObjs, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, iaDemo.ExampleThread; Type TLogOutputChoices = (Undefined, NoLog, LogToDebugger, LogToCodeSite, LogToMemo); TLogDestination = set of TLogOutputChoices; TfrmThreadStateTest = class(TForm) tmrThreadEvent:TTimer; panTop:TPanel; butStartTimer:TButton; butStopTimer:TButton; panStats:TPanel; Label1:TLabel; Label2:TLabel; Label3:TLabel; Label4:TLabel; Label5:TLabel; Label6:TLabel; labThreadsCreated:TLabel; labThreadsStarted:TLabel; labThreadsStopped:TLabel; labIsActiveChecks:TLabel; labCanStartChecks:TLabel; labThreadsFreed:TLabel; labTimerActiveStatus:TLabel; labTimerStarted:TLabel; panLog:TPanel; memLog:TMemo; procedure butStartTimerClick(Sender:TObject); procedure butStopTimerClick(Sender:TObject); procedure FormCreate(Sender:TObject); procedure FormDestroy(Sender:TObject); procedure tmrThreadEventTimer(Sender:TObject); procedure FormCloseQuery(Sender:TObject; var CanClose:Boolean); private fWorkerThreads:TArray<TSimpleExample>; fSelectedWorker:Integer; fCountCreate:Int64; fCountFree:Int64; fCountStop:Int64; fCountStart:Int64; fCountIsActive:Int64; fCountCanStart:Int64; fClosed:Boolean; fLogDestinationChoices:TLogDestination; fLogOverride:TLogOutputChoices; procedure LogProgress(const LogEntry:string); procedure DoCreateThread; procedure DoFree; procedure DoStop; procedure DoStart; procedure DoIsActive; procedure DoCanStart; procedure TakeAction(const ForceAllStop:Boolean = False); end; var frmThreadStateTest:TfrmThreadStateTest; fActionLock:TCriticalSection; const MAX_THREADS = 150; implementation uses CodeSiteLogging, iaRTL.Logging, iaRTL.Logging.Debugger.Windows, iaRTL.Logging.CodeSite, iaVCL.Logging.Memo; {$R *.dfm} procedure TfrmThreadStateTest.FormCreate(Sender:TObject); begin ReportMemoryLeaksOnShutdown := True; fLogDestinationChoices := [TLogOutputChoices.NoLog, TLogOutputChoices.LogToDebugger, TLogOutputChoices.LogToCodeSite]; if not CodeSite.Installed then begin fLogDestinationChoices := fLogDestinationChoices - [TLogOutputChoices.LogToCodeSite]; end; fLogOverride := TLogOutputChoices.NoLog; //override fLogDestinationChoices if set to anything other than Undefined end; procedure TfrmThreadStateTest.FormDestroy(Sender:TObject); var Worker:TSimpleExample; begin fActionLock.Enter; try tmrThreadEvent.Enabled := False; for Worker in fWorkerThreads do begin Worker.Free; end; finally fActionLock.Leave; end; end; procedure TfrmThreadStateTest.FormCloseQuery(Sender:TObject; var CanClose:Boolean); begin tmrThreadEvent.Enabled := False; fClosed := True; end; procedure TfrmThreadStateTest.butStartTimerClick(Sender:TObject); begin fActionLock.Enter; try memLog.Lines.Clear; LogProgress('Start clicked'); if not tmrThreadEvent.Enabled then begin labTimerActiveStatus.Caption := 'Timer Active'; labTimerStarted.Caption := FormatDateTime('mm/dd/yyyy hh:nn:ss', Now); tmrThreadEvent.Enabled := True; end; finally fActionLock.Leave; end; end; procedure TfrmThreadStateTest.butStopTimerClick(Sender:TObject); begin fActionLock.Enter; try LogProgress(Format('Stop clicked [%d]', [GetTickCount])); tmrThreadEvent.Enabled := False; TakeAction(True); labTimerStarted.Caption := labTimerStarted.Caption + ' - ' + FormatDateTime('mm/dd/yyyy hh:nn:ss', Now); labTimerActiveStatus.Caption := 'Timer Not Active'; finally fActionLock.Leave; end; end; procedure TfrmThreadStateTest.LogProgress(const LogEntry:string); begin if memLog.Lines.Count > (MAX_THREADS*3) then begin memLog.Lines.Clear; end; memLog.Lines.Add(LogEntry); memLog.Repaint; end; procedure TfrmThreadStateTest.tmrThreadEventTimer(Sender:TObject); begin if (not fClosed) and fActionLock.TryEnter then begin try tmrThreadEvent.Enabled := False; tmrThreadEvent.Interval := Trunc(Random(50)) + 1; TakeAction; tmrThreadEvent.Enabled := True; finally fActionLock.Leave; end; end; end; // Validate that the methods can be externally called in any order, during any current state of the thread procedure TfrmThreadStateTest.TakeAction(const ForceAllStop:Boolean = False); var ActionToTake:Integer; CurrentWorkerThreadCount:Integer; Worker:TSimpleExample; begin CurrentWorkerThreadCount := Length(fWorkerThreads); if ForceAllStop then begin if CurrentWorkerThreadCount = 0 then Exit; for Worker in fWorkerThreads do begin LogProgress(Format('Stopping %s [%d]', [Worker.ThreadNameForDebugger, GetTickCount])); Worker.Stop; Inc(fCountStop); end; for Worker in fWorkerThreads do begin LogProgress(Format('Freeing %s [%d]', [Worker.ThreadNameForDebugger, GetTickCount])); Worker.Free; Inc(fCountFree); end; fWorkerThreads := nil; labThreadsFreed.Caption := IntToStr(fCountFree); end else begin ActionToTake := Trunc(Random(10)); fSelectedWorker := Trunc(Random(CurrentWorkerThreadCount)); if ((fSelectedWorker < CurrentWorkerThreadCount) and (CurrentWorkerThreadCount > 0)) and ((ActionToTake < 5) or (CurrentWorkerThreadCount > MAX_THREADS)) then begin case ActionToTake of 0: DoFree; 1: DoStart; 2: DoIsActive; 3: DoCanStart; else DoStop; end; end else begin DoCreateThread; end; end; end; procedure TfrmThreadStateTest.DoCreateThread; var WorkerThread:TSimpleExample; Logger:ILogger; LogTo:TLogOutputChoices; SanityCheck:Integer; begin Logger := nil; LogTo := fLogOverride; if (LogTo = TLogOutputChoices.Undefined) and (fLogDestinationChoices <> []) then //randomly select a log output begin SanityCheck := 0; repeat LogTo := TLogOutputChoices(Random(Ord(TLogOutputChoices.LogToMemo)+1)); Inc(SanityCheck); if SanityCheck > 20 then begin LogTo := TLogOutputChoices.NoLog; Break; end; until LogTo in fLogDestinationChoices; end; case LogTo of TLogOutputChoices.LogToDebugger: Logger := TiaWindowsDebugLogging.Create; TLogOutputChoices.LogToCodeSite: Logger := TiaCodeSiteLogger.Create('Viewer'); TLogOutputChoices.LogToMemo: Logger := TiaMemoLogger.Create(memLog); end; if Assigned(Logger) then begin Logger.SetLoggingIsEnabled(True); Logger.SetCurrentLogLevel(TiaLogLevel.Debug); end; WorkerThread := TSimpleExample.Create('Worker' + fCountCreate.ToString, Logger); WorkerThread.PauseBetweenWorkMS := Random(1000); WorkerThread.OnReportProgress := LogProgress; fWorkerThreads := fWorkerThreads + [WorkerThread]; Inc(fCountCreate); labThreadsCreated.Caption := IntToStr(fCountCreate); end; procedure TfrmThreadStateTest.DoFree; var WorkerThread:TSimpleExample; begin WorkerThread := fWorkerThreads[fSelectedWorker]; WorkerThread.Free; Delete(fWorkerThreads, fSelectedWorker, 1); Inc(fCountFree); labThreadsFreed.Caption := IntToStr(fCountFree); end; procedure TfrmThreadStateTest.DoStop; var WorkerThread:TSimpleExample; begin WorkerThread := fWorkerThreads[fSelectedWorker]; WorkerThread.Stop; Inc(fCountStop); labThreadsStopped.Caption := IntToStr(fCountStop); end; procedure TfrmThreadStateTest.DoStart; var WorkerThread:TSimpleExample; begin WorkerThread := fWorkerThreads[fSelectedWorker]; WorkerThread.Start; Inc(fCountStart); labThreadsStarted.Caption := IntToStr(fCountStart); end; procedure TfrmThreadStateTest.DoIsActive; var WorkerThread:TSimpleExample; begin WorkerThread := fWorkerThreads[fSelectedWorker]; WorkerThread.ThreadIsActive; Inc(fCountIsActive); labIsActiveChecks.Caption := IntToStr(fCountIsActive); end; procedure TfrmThreadStateTest.DoCanStart; var WorkerThread:TSimpleExample; begin WorkerThread := fWorkerThreads[fSelectedWorker]; WorkerThread.CanBeStarted; Inc(fCountCanStart); labCanStartChecks.Caption := IntToStr(fCountCanStart); end; initialization fActionLock := TCriticalSection.Create; finalization fActionLock.Free; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [OPERADORA_CARTAO] The MIT License Copyright: Copyright (C) 2014 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 OperadoraCartaoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ContaCaixaVO; type [TEntity] [TTable('OPERADORA_CARTAO')] TOperadoraCartaoVO = class(TVO) private FID: Integer; FID_CONTA_CAIXA: Integer; FBANDEIRA: String; FNOME: String; FTAXA_ADM: Extended; FTAXA_ADM_DEBITO: Extended; FVALOR_ALUGUEL_POS_PIN: Extended; FVENCIMENTO_ALUGUEL: Integer; FFONE1: String; FFONE2: String; FCLASSIFICACAO_CONTABIL_CONTA: String; //Transientes FContaCaixaNome: String; FContaCaixaVO: TContaCaixaVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CONTA_CAIXA', 'Id Conta Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA; [TColumnDisplay('CONTA_CAIXA.NOME', 'Conta Caixa', 150, [ldGrid, ldLookup], ftString, 'ContaCaixaVO.TContaCaixaVO', True)] property ContaCaixaNome: String read FContaCaixaNome write FContaCaixaNome; [TColumn('BANDEIRA', 'Bandeira', 240, [ldGrid, ldLookup, ldCombobox], False)] property Bandeira: String read FBANDEIRA write FBANDEIRA; [TColumn('NOME', 'Nome', 400, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('TAXA_ADM', 'Taxa Adm', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaAdm: Extended read FTAXA_ADM write FTAXA_ADM; [TColumn('TAXA_ADM_DEBITO', 'Taxa Adm Debito', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaAdmDebito: Extended read FTAXA_ADM_DEBITO write FTAXA_ADM_DEBITO; [TColumn('VALOR_ALUGUEL_POS_PIN', 'Valor Aluguel Pos Pin', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorAluguelPosPin: Extended read FVALOR_ALUGUEL_POS_PIN write FVALOR_ALUGUEL_POS_PIN; [TColumn('VENCIMENTO_ALUGUEL', 'Vencimento Aluguel', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property VencimentoAluguel: Integer read FVENCIMENTO_ALUGUEL write FVENCIMENTO_ALUGUEL; [TColumn('FONE1', 'Fone1', 112, [ldGrid, ldLookup, ldCombobox], False)] property Fone1: String read FFONE1 write FFONE1; [TColumn('FONE2', 'Fone2', 112, [ldGrid, ldLookup, ldCombobox], False)] property Fone2: String read FFONE2 write FFONE2; [TColumn('CLASSIFICACAO_CONTABIL_CONTA', 'Classificacao Contabil Conta', 240, [ldGrid, ldLookup, ldCombobox], False)] property ClassificacaoContabilConta: String read FCLASSIFICACAO_CONTABIL_CONTA write FCLASSIFICACAO_CONTABIL_CONTA; //Transientes [TAssociation('ID', 'ID_CONTA_CAIXA')] property ContaCaixaVO: TContaCaixaVO read FContaCaixaVO write FContaCaixaVO; end; implementation constructor TOperadoraCartaoVO.Create; begin inherited; FContaCaixaVO := TContaCaixaVO.Create; end; destructor TOperadoraCartaoVO.Destroy; begin FreeAndNil(FContaCaixaVO); inherited; end; initialization Classes.RegisterClass(TOperadoraCartaoVO); finalization Classes.UnRegisterClass(TOperadoraCartaoVO); end.
unit NiceExceptions; {$DEFINE DEBUG_WRITELN_FAILED_ASSIGNED_ASSERTION} {$DEFINE DEBUG_WRITELN_FAILED_ARGUMENT_ASSIGNED_ASSERTION} interface uses SysUtils, Classes, StrUtils, NiceTypes; type EUnassigned = class(Exception) public constructor Create(const aVariableName: string; const aVariableType: TVariableType = TVariableType.Unknown); private fVariableName: string; fVariableType: TVariableType; public property VariableName: string read fVariableName; property VariableType: TVariableType read fVariableType; end; EFileNotFound = class(Exception); EIndexOutOfBounds = class(Exception); EStackTrace = class(Exception); ECritical = class(Exception); EAccessViolationAddress = class helper for EAccessViolation public function GetAddressAsText: string; end; function GetFullExceptionInfo(const aException: Exception): string; function GetStackTraceText: string; procedure AssertAssigned(const aPointer: pointer; const aVariableName: string; const aVariableType: TVariableType); inline; type TOneMoreAssignedAssertion = object public VariableType: TVariableType; function Assigned(const aPointer: pointer; const aVariableName: string) : TOneMoreAssignedAssertion; inline; end; function AssertsAssigned(const aPointer: pointer; const aVariableName: string; const aVariableType: TVariableType): TOneMoreAssignedAssertion; procedure AssertAssigned(const aCondition: boolean; const aVariableName: string; const aVariableType: TVariableType); inline; procedure AssertIndexInBounds(const aMin, aIndex, aMax: integer; const aMessage: string); inline; procedure AssertFileExists(const aFileName: string); inline; function IsExceptionCritical(const aException: Exception): boolean; inline; implementation constructor EUnassigned.Create(const aVariableName: string; const aVariableType: TVariableType); begin inherited Create(''); fVariableName := aVariableName; fVariableType := aVariableType; Message := VariableName + ' (' + VariableType + ') unassigned.'; end; function EAccessViolationAddress.GetAddressAsText: string; var digits: integer; begin digits := SizeOf(pointer) * 2; if Assigned(ExceptionRecord) then result := '$' + IntToHex(PtrInt(ExceptionRecord^.ExceptionAddress), digits) else result := '$' + DupeString('?', digits); end; function GetFullExceptionInfo(const aException: Exception): string; var FrameNumber, FrameCount: longint; Frames: PPointer; begin result := ''; result := result + 'Exception class: ' + aException.ClassName + sLineBreak; result := result + 'Exception message: "' + aException.Message + '"' + sLineBreak; if aException is EAccessViolation then result := result + 'Access violation address: ' + (aException as EAccessViolation).GetAddressAsText + sLineBreak; if RaiseList = nil then exit; result := result + BackTraceStrFunc(RaiseList^.Addr) + sLineBreak; FrameCount := RaiseList^.Framecount; Frames := RaiseList^.Frames; for FrameNumber := 0 to FrameCount - 1 do result := result + BackTraceStrFunc(Frames[FrameNumber]) + LineEnding; result += '(end of stack trace)'; end; function GetStackTraceText: string; begin result := ''; try raise EStackTrace.Create('Stack Trace'); except on e: Exception do result := GetFullExceptionInfo(e); end; end; procedure AssertAssigned(const aPointer: pointer; const aVariableName: string; const aVariableType: TVariableType); begin AssertAssigned(Assigned(aPointer), aVariableName, aVariableType); end; function TOneMoreAssignedAssertion.Assigned(const aPointer: pointer; const aVariableName: string) : TOneMoreAssignedAssertion; inline; begin AssertAssigned(aPointer, aVariableName, VariableType); end; function AssertsAssigned(const aPointer: pointer; const aVariableName: string; const aVariableType: TVariableType): TOneMoreAssignedAssertion; begin result.VariableType := aVariableType; result.Assigned(aPointer, aVariableName); end; procedure AssertAssigned(const aCondition: boolean; const aVariableName: string; const aVariableType: TVariableType); begin if not aCondition then raise EUnassigned.Create(aVariableName, aVariableType); end; procedure AssertIndexInBounds(const aMin, aIndex, aMax: integer; const aMessage: string); var result: boolean; begin result := (aMin <= aIndex) and (aIndex <= aMax); if not result then raise EIndexOutOfBounds.Create(aMessage + ' (index is ' + IntToStr(aIndex) + ')'); end; procedure AssertFileExists(const aFileName: string); begin if not FileExists(aFileName) then raise EFileNotFound.Create(aFileName); end; function IsExceptionCritical(const aException: Exception): boolean; begin result := aException is EOutOfMemory or aException is EOutOfResources or aException is EStackOverflow; end; end.
unit G2048.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, System.Generics.Collections, Direct2D, D2D1; type TDoublePoint = record X, Y:Double; end; TGameCell = class private FValue:Cardinal; FTextValue:string; FFieldPos:TPoint; FNeedPos:TDoublePoint; FColor:TColor; procedure SetValue(Value:Cardinal); function GetEmpty:Boolean; procedure SetFieldPos(Value:TPoint); public Position:TDoublePoint; function StepPos:Boolean; property Value:Cardinal read FValue write SetValue; property Text:string read FTextValue; property Empty:Boolean read GetEmpty; property FieldPos:TPoint read FFieldPos write SetFieldPos; property Color:TColor read FColor; constructor Create(FPos:TPoint); end; const FieldWidth = 4; FieldHeight = 4; CellWidth = 64; CellPlace = 5; StepSize = 5; type TGameField = array[1..FieldWidth, 1..FieldHeight] of Cardinal; TGraphicCells = TList<TGameCell>; TDirection = (tdLeft, tdUp, tdRight, tdDown); TFormMain = class(TForm) TimerRedraw: TTimer; procedure TimerRedrawTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private FD2Canvas:TDirect2DCanvas; FDrawRect:TRect; FStepping:Boolean; FBitmap:TBitmap; FGameField:TGameField; FCells:TGraphicCells; procedure Step; function FindCell(X, Y:Word):Integer; public procedure NewCell; procedure PlayerStep(Direction:TDirection); procedure Paint; override; procedure Redraw; constructor Create(AOwner: TComponent); override; end; const colorEmpty = $00B4C0CD; colorField = $00A0ADBB; var FormMain: TFormMain; FDrawing:Boolean; implementation uses Math, Main.CommonFunc; {$R *.dfm} constructor TFormMain.Create(AOwner: TComponent); var x, y:Integer; begin inherited; FDrawRect:=Rect(0, 0, ClientWidth, ClientHeight); FBitmap:=TBitmap.Create; FBitmap.PixelFormat:=pf24bit; FBitmap.Width:=ClientWidth; FBitmap.Height:=ClientHeight; FBitmap.Canvas.Pen.Color:=colorField; FBitmap.Canvas.Brush.Color:=colorField; FBitmap.Canvas.FillRect(FDrawRect); FCells:=TGraphicCells.Create; for x:= 1 to FieldWidth do for y:= 1 to FieldHeight do FGameField[x, y]:=0; end; function TFormMain.FindCell(X, Y: Word): Integer; var i:Integer; begin Result:=-1; if FCells.Count > 0 then for i:= 0 to FCells.Count - 1 do if FCells[i].FieldPos = Point(X, Y) then Exit(i); end; procedure TFormMain.FormCreate(Sender: TObject); begin Randomize; Redraw; NewCell; end; procedure TFormMain.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_UP:PlayerStep(tdUp); VK_DOWN:PlayerStep(tdDown); VK_LEFT:PlayerStep(tdLeft); VK_RIGHT:PlayerStep(tdRight); end; end; procedure TFormMain.NewCell; var X, Y, Empty:Cardinal; Cell:TGameCell; begin Empty:=0; for X:= 1 to FieldWidth do for Y:= 1 to FieldHeight do if FGameField[X, Y] = 0 then Inc(Empty); if Empty >= 2 then begin for Empty:= 1 to 2 do begin repeat X:=RandomRange(1, FieldWidth+1); Y:=RandomRange(1, FieldWidth+1); until FGameField[X, Y] = 0; FGameField[X, Y]:=2; Cell:=TGameCell.Create(Point(X, Y)); Cell.Value:=FGameField[X, Y]; FCells.Add(Cell); //Cell.Free; end; end; end; procedure TFormMain.Paint; begin inherited; Canvas.Draw(0, 0, FBitmap); end; procedure TFormMain.PlayerStep(Direction: TDirection); var X, Y, NX, NY:Cardinal; Active:Boolean; procedure SetCellValue(X, Y:Word; Value:Cardinal); var fCell:Integer; begin fCell:=FindCell(X, Y); if fCell < 0 then Exit; FCells[fCell].Value:=Value; end; procedure SetCellPos(X, Y:Word; NewPos:TPoint); var fCell:Integer; begin fCell:=FindCell(X, Y); if fCell < 0 then Exit; FCells[fCell].FieldPos:=NewPos; end; procedure DeleteCell(X, Y:Word); var fCell:Integer; begin fCell:=FindCell(X, Y); if fCell < 0 then Exit; FCells.Delete(fCell); end; begin Active:=True; while Active do begin Active:=False; for Y:= 1 to FieldHeight do for X:= 1 to FieldWidth do begin case Direction of tdLeft: if X < 2 then Continue; tdUp: if Y < 2 then Continue; tdRight: if X > FieldWidth-1 then Continue; tdDown: if Y > FieldHeight-1 then Continue; end; if FGameField[X, Y] = 0 then Continue; case Direction of tdLeft: begin NX:=X-1; NY:=Y; end; tdRight: begin NX:=X+1; NY:=Y; end; tdUp: begin NX:=X; NY:=Y-1; end; tdDown: begin NX:=X; NY:=Y+1; end; end; if FGameField[NX, NY] = FGameField[X, Y] then begin FGameField[NX, NY]:=FGameField[NX, NY] * 2; FGameField[X, Y]:=0; DeleteCell(NX, NY); SetCellValue(X, Y, FGameField[NX, NY]); SetCellPos(X, Y, Point(NX, NY)); Active:=True; Continue; end; if FGameField[NX, NY] = 0 then begin FGameField[NX, NY]:=FGameField[X, Y]; FGameField[X, Y]:=0; SetCellPos(X, Y, Point(NX, NY)); Active:=True; Continue; end; end; end; Step; NewCell; end; procedure TFormMain.Redraw; var X, Y:Cardinal; FPos:TDoublePoint; CellRect, TextR:TRect; Str:string; begin FD2Canvas:=TDirect2DCanvas.Create(FBitmap.Canvas, FDrawRect); with FD2Canvas do begin RenderTarget.BeginDraw; Pen.Color:=colorField; Brush.Color:=colorField; FillRect(FDrawRect); for X:= 1 to FieldWidth do for Y:= 1 to FieldHeight do begin FPos.X:=((X - 1) * CellWidth) + (X * CellPlace); FPos.Y:=((Y - 1) * CellWidth) + (Y * CellPlace); CellRect:=Rect(Round(FPos.X), Round(FPos.Y), Round(FPos.X + CellWidth), Round(FPos.Y + CellWidth)); Pen.Color:=colorEmpty; Brush.Color:=colorEmpty; RoundRect(CellRect, 2, 2); end; if FCells.Count > 0 then for X:= 0 to FCells.Count - 1 do begin FPos:=FCells[X].Position; Pen.Color:=FCells[X].Color; Brush.Color:=FCells[X].Color; CellRect:=Rect(Round(FPos.X), Round(FPos.Y), Round(FPos.X + CellWidth), Round(FPos.Y + CellWidth)); RoundRect(CellRect, 2, 2); Font.Size:=18; Font.Name:='Comic Sans MS'; Font.Style:=[fsBold]; Font.Color:=$00F7FAF9; Str:=FCells[X].Text; TextRect(CellRect, Str, [tfCenter, tfVerticalCenter, tfSingleLine]); end; RenderTarget.EndDraw; end; FD2Canvas.Free; Repaint; end; procedure TFormMain.Step; var X, Y:Cardinal; DoStep:Boolean; begin if FStepping then Exit; if FCells.Count <= 0 then Exit; FStepping:=True; DoStep:=True; while DoStep do begin DoStep:=False; for X:= 0 to FCells.Count - 1 do begin if FCells[X].StepPos then DoStep:=True; end; Redraw; Sleep(5); end; FStepping:=False; end; procedure TFormMain.TimerRedrawTimer(Sender: TObject); begin Redraw; end; { TGameCell } constructor TGameCell.Create(FPos: TPoint); begin FieldPos:=FPos; Position:=FNeedPos; Value:=0; end; function TGameCell.GetEmpty:Boolean; begin Result:=FValue = 0; end; procedure TGameCell.SetFieldPos(Value: TPoint); begin FFieldPos:=Value; FNeedPos.X:=((FFieldPos.X - 1) * CellWidth) + (FFieldPos.X * CellPlace); FNeedPos.Y:=((FFieldPos.Y - 1) * CellWidth) + (FFieldPos.Y * CellPlace); end; procedure TGameCell.SetValue(Value: Cardinal); begin FValue:=Value; if FValue > 0 then begin FTextValue:=IntToStr(FValue); FColor:=$00AB84B7; if FValue <= 8 then FColor:=$0079B1F2 else if FValue <= 32 then FColor:=$005F7CF6 else if FValue <= 128 then FColor:=$0073CEED else if FValue <= 1024 then FColor:=$003E3CFF; FColor:=ColorDarker(FColor, FValue div 4);//FValue * 100; end else begin FTextValue:='Пусто'; FColor:=colorEmpty; end; end; function TGameCell.StepPos:Boolean; begin if Abs(FNeedPos.X - Position.X) > StepSize then begin if FNeedPos.X < Position.X then Position.X:=Position.X - StepSize else Position.X:=Position.X + StepSize; end else Position.X:=FNeedPos.X; if Abs(FNeedPos.Y - Position.Y) > StepSize then begin if FNeedPos.Y < Position.Y then Position.Y:=Position.Y - StepSize else Position.Y:=Position.Y + StepSize; end else Position.Y:=FNeedPos.Y; Result:=(Position.X <> FNeedPos.X) or (Position.Y <> FNeedPos.Y); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Menus; type TForm1 = class(TForm) hkVolumeUp: THotKey; hkVolumeDown: THotKey; lblVolumeUp: TLabel; lblVolumeDown: TLabel; trycn1: TTrayIcon; pm1: TPopupMenu; S1: TMenuItem; E1: TMenuItem; hkVolumeMute: THotKey; lblVolumeMute: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure E1Click(Sender: TObject); procedure S1Click(Sender: TObject); procedure trycn1DblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } configUrl: string; atomHandle: ATOM; atomHotkeyVolumeUp: ATOM; atomHotkeyVolumeDown: ATOM; atomHotkeyVolumeMute: ATOM; // atomHotkeyVolumeUp: ATOM; // atomHotkeyVolumeUp: ATOM; // atomHotkeyVolumeUp: ATOM; hotkeyList: TStrings; procedure deleteHotkey(id: ATOM); function registerHotkey(hotkey: THotKey; id: ATOM): Boolean; procedure hotkeyProcess(var msg: TMessage); message WM_HOTKEY; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); begin Key := ShortCut and not(scShift + scCtrl + scAlt); Shift := []; if ShortCut and scShift <> 0 then Include(Shift, ssShift); if ShortCut and scCtrl <> 0 then Include(Shift, ssCtrl); if ShortCut and scAlt <> 0 then Include(Shift, ssAlt); end; function ShiftStateToWord(TShift: TShiftState): Word; begin Result := 0; if ssShift in TShift then Result := MOD_SHIFT; if ssCtrl in TShift then Result := Result or MOD_CONTROL; if ssAlt in TShift then Result := Result or MOD_ALT; end; procedure TForm1.hotkeyProcess(var msg: TMessage); function isHotkey(hotkey: THotKey): Boolean; var T: TShiftState; Key: Word; Shift: Word; begin ShortCutToKey(hotkey.hotkey, Key, T); Shift := ShiftStateToWord(T); Result := (msg.LparamLo = Shift) AND (msg.LParamHi = Key) end; var vk: Byte; begin if isHotkey(hkVolumeUp) then vk := VK_VOLUME_UP // vk := VK_HOME else if isHotkey(hkVolumeDown) then vk := VK_VOLUME_DOWN else if isHotkey(hkVolumeMute) then vk := VK_VOLUME_MUTE; keybd_event(vk, 0, 0, 0); keybd_event(vk, 0, KEYEVENTF_KEYUP, 0);; end; procedure TForm1.deleteHotkey(id: Word); begin UnregisterHotKey(Self.Handle, id); end; function TForm1.registerHotkey(hotkey: THotKey; id: ATOM): Boolean; var T: TShiftState; Key, Shift: Word; begin ShortCutToKey(hotkey.hotkey, Key, T); Shift := ShiftStateToWord(T); Result := Winapi.Windows.registerHotkey(Self.Handle, id, Shift, Key); end; procedure TForm1.E1Click(Sender: TObject); begin Application.Terminate; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); // 提示信息 procedure hotkeyAlreadyRegister(hotkey: THotKey; var status: Boolean); begin if hotkey.hotkey <> 0 then begin status := False; Application.MessageBox(PChar(ShortCutToText(hotkey.hotkey) + '已经被使用,请重新设置'), '提示', MB_OK + MB_ICONINFORMATION); end; end; // 保存按键信息 procedure saveHotkey(hotkey: THotKey); begin hotkeyList.Add(hotkey.Name + '=' + IntToStr(hotkey.hotkey)) end; var okay: Boolean; begin Action := TCloseAction.caNone; // 保存快捷键 // 删除原快捷键 deleteHotkey(atomHotkeyVolumeUp); deleteHotkey(atomHotkeyVolumeDown); deleteHotkey(atomHotkeyVolumeMute); // 注册新快捷键 okay := True; if not registerHotkey(hkVolumeUp, atomHotkeyVolumeUp) then hotkeyAlreadyRegister(hkVolumeUp, okay); if not registerHotkey(hkVolumeDown, atomHotkeyVolumeDown) then hotkeyAlreadyRegister(hkVolumeDown, okay); if not registerHotkey(hkVolumeMute, atomHotkeyVolumeMute) then hotkeyAlreadyRegister(hkVolumeMute, okay); if okay then begin hotkeyList.Clear; saveHotkey(hkVolumeUp); saveHotkey(hkVolumeDown); saveHotkey(hkVolumeMute); hotkeyList.SaveToFile(configUrl); Self.Hide; end; end; procedure TForm1.FormCreate(Sender: TObject); const atomString = 'VolumeChanger'; var index: Integer; i: Integer; controlName: string; baseUrl: string; begin if FindAtom(atomString) = 0 then begin atomHandle := GlobalAddAtom(atomString); atomHotkeyVolumeUp := GlobalAddAtom('hkVolumeUp') - $C000; atomHotkeyVolumeDown := GlobalAddAtom('hkVolumeDown') - $C000; atomHotkeyVolumeMute := GlobalAddAtom('hkVolumeMute') - $C000; baseUrl := GetEnvironmentVariable('localappdata') + '/VolumeChanger'; configUrl := baseUrl + '/config.json'; hotkeyList := TStringList.Create; if FileExists(configUrl) then begin // 加载保存信息 hotkeyList.LoadFromFile(configUrl); for index := 0 to hotkeyList.Count - 1 do begin controlName := hotkeyList.Names[index]; for i := 0 to Self.Componentcount - 1 do // Self.Componentcount就是TForm1的控件数量 begin if Self.Components[i].Name = controlName then begin // ShowMessage(Self.Components[i].Name); (Self.Components[i] as THotKey).hotkey := StrToInt(hotkeyList.Values[controlName]); end; end; end; Application.ShowMainForm := False; Self.Close; end else if not FileExists(baseUrl) then begin CreateDir(baseUrl); end; Exit; end; // 重复运行 Application.Terminate; end; procedure TForm1.FormDestroy(Sender: TObject); begin GlobalDeleteAtom(atomHandle); GlobalDeleteAtom(atomHotkeyVolumeUp); GlobalDeleteAtom(atomHotkeyVolumeDown); GlobalDeleteAtom(atomHotkeyVolumeMute); end; procedure TForm1.S1Click(Sender: TObject); begin Self.Show; end; procedure TForm1.trycn1DblClick(Sender: TObject); begin Self.Show; end; end.
unit WMSRasterProcessorDispatcher; interface uses TeraWMSToolsDefs, TeraWMSTools, GR32, Classes; type TPixelOperation = ( po_ColorToGrayscale, po_AlphaToGrayscale, po_IntensityToAlpha, po_Invert, po_InvertRGB, po_GetRValue, po_GetGValue, po_GetBValue ); TPixelOperationProc = function(Source : TColor32) : TColor32; TRasterProcessor_GetMap = class(TGetMapDispatcher) function GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream; override; end; const PIXELOPERATION_CAPTIONS : array[TPixelOperation] of string = ( 'ColorToGrayscale', 'AlphaToGrayscale', 'IntensityToAlpha', 'Invert', 'InvertRGB', 'RedBand', 'GreenBand', 'BlueBand' ); PIXELOPERATION_ID = 'PIXELOPERATION'; implementation uses ShareTools, Console, jpeg, GR32_Filters, Graphics, SysUtils; function GetRValuePixelProc(SourceColor : TColor32) : TColor32; far; begin Result := Color32(RedComponent(SourceColor), 0, 0); end; function GetGValuePixelProc(SourceColor : TColor32) : TColor32; far; begin Result := Color32(0, GreenComponent(SourceColor), 0); end; function GetBValuePixelProc(SourceColor : TColor32) : TColor32; far; begin Result := Color32(0, 0, BlueComponent(SourceColor)); end; procedure ProcessPixelsInBitmaps(Dst, Src: TBitmap32; PixelProc : TPixelOperationProc); var Col, Row : integer; begin if Assigned(PixelProc) and (Src <> nil) and (Dst <> nil) then begin Dst.Width := Src.Width; Dst.Height := Src.Height; for Row := 0 to Src.Height - 1 do for Col := 0 to Src.Width - 1 do Dst.Pixel[Col, Row] := PixelProc(Src.Pixel[Col, Row]); end; end; function TRasterProcessor_GetMap.GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream; var PixelOperation : TPixelOperation; SourceWMS, s, tmpFileName : string; i : integer; SrcGraphic : TGraphic; MemS : TStream; FileS : TFileStream; SourceBmp : TBitmap32; DestBmp : TBitmap32; bmp : Graphics.TBitmap; FormatStr : string; begin Console.DefConsole.OpenSection('TRasterProcessor_GetMap'); Result := nil; PixelOperation := TPixelOperation(SafeStrToStringIndex(RequestInfo.QueryFields.Values[PIXELOPERATION_ID], PIXELOPERATION_CAPTIONS)); SourceWMS := RequestInfo.QueryFields.Values[SOURCEWMS_ID]; // Request.Query vyvola chybu, protoze jsou v nem ulozeny $3A hodnoty RequestInfo.QueryFields.Delete(RequestInfo.QueryFields.IndexOfName(SOURCEWMS_ID)); s := SourceWMS; for i := 0 to RequestInfo.QueryFields.Count - 1 do s := AddTokenToURLQuery(RequestInfo.QueryFields[i], s); Console.DisplayDebugMsg('Requesting = ' + s); tmpFileName := DownloadURLToFile(s); if tmpFileName <> '' then begin Console.DisplayDebugMsg('Loading file ' + tmpFileName); try FileS := TFileStream.Create(tmpFileName, fmOpenRead); FormatStr := qStr(RequestInfo.QueryFields, FORMAT_ID, 'image/jpeg'); SrcGraphic := WMSStreamtoGraphic(FileS, FormatStr); finally FileS.Free; DeleteFile(tmpFileName); end; SourceBmp := TBitmap32.Create; DestBmp := TBitmap32.Create; SourceBmp.Assign(SrcGraphic); SrcGraphic.Free; case PixelOperation of po_AlphaToGrayscale:AlphaToGrayscale(DestBmp, SourceBmp); po_IntensityToAlpha:IntensityToAlpha(DestBmp, SourceBmp); po_Invert: Invert(DestBmp, SourceBmp); po_InvertRGB: InvertRGB(DestBmp, SourceBmp); po_GetRValue: ProcessPixelsInBitmaps(DestBmp, SourceBmp, GetRValuePixelProc); po_GetGValue: ProcessPixelsInBitmaps(DestBmp, SourceBmp, GetGValuePixelProc); po_GetBValue: ProcessPixelsInBitmaps(DestBmp, SourceBmp, GetBValuePixelProc); else // ro_ColorToGrayscale ColorToGrayscale(DestBmp, SourceBmp, false); end; SourceBmp.Free; bmp := BuildResponseBitmap(RequestInfo); try bmp.TransparentColor := clBlack; bmp.Assign(DestBmp); DestBmp.Free; finally MemS := BMPtoWMSStream(bmp, FormatStr); bmp.Free; end; MemS.Position := 0; Result := MemS; RequestInfo.Handled :=true; end; Console.DefConsole.CloseSection('End of TRasterProcessor_GetMap'); end; var i : TPixelOperation; s : string; initialization with WMSDispatchers.Add do begin ParamNames := SOURCEWMS_ID + PARAMNAMES_DELIMETER + PIXELOPERATION_ID + PARAMNAMES_DELIMETER; PathInfo := '/WMS/PixelProcessor'; Caption := 'Pixel processor'; s := ''; for i := Low(i) to High(i) do begin if s <> '' then s := s + ','; s := s + PIXELOPERATION_CAPTIONS[i]; end; s := s + '<input></input>'; Description := 'Procesor rastrý:' + PIXELOPERATION_ID + '=' + s; //DescriptionFileName := 'PixelProcessor.htm'; GetCapabilitiesDispatcher := TWMSGetCapabilitiesModifier.Create; TWMSGetCapabilitiesModifier(GetCapabilitiesDispatcher).CapabilitiesProcessor := CapabilitiesProcessor_RemoveUnknownFormats; GetMapDispatcher := TRasterProcessor_GetMap.Create; end; end.
unit DispatcherFactory; {$mode objfpc}{$H+} interface uses Classes, DispatcherModbusItf, EssoClientDispatcherItf, LoggerItf; type { TTrasmitterDispFactory } TTrasmitterDispFactory = class public class function GetEssoDispatcherNew : IESSOClientDisp; class function GetModbusDispatcher : IMBDispatcherItf; class procedure SetLoggerItf(LogItf : IDLogger); class procedure DestroyAllDispatchers; end; implementation uses sysutils, DispatcherModbusClasses, EssoClientDispNewTypes; { TTrasmitterDispFactory } var EssoDispatcherNew : TESSOClientDisp; ModbusDispatcher : TDispatcherModbusMaster; LoggerItfVar : IDLogger; class function TTrasmitterDispFactory.GetEssoDispatcherNew: IESSOClientDisp; begin Result := nil; if not Assigned(EssoDispatcherNew) then begin EssoDispatcherNew := TESSOClientDisp.Create(nil); EssoDispatcherNew.Logger := LoggerItfVar; end; Result := EssoDispatcherNew as IESSOClientDisp; end; class function TTrasmitterDispFactory.GetModbusDispatcher: IMBDispatcherItf; begin Result := nil; if not Assigned(ModbusDispatcher) then begin ModbusDispatcher := TDispatcherModbusMaster.Create(nil); ModbusDispatcher.Logger := LoggerItfVar; end; Result := ModbusDispatcher as IMBDispatcherItf; end; class procedure TTrasmitterDispFactory.SetLoggerItf(LogItf: IDLogger); begin if Assigned(EssoDispatcherNew) then EssoDispatcherNew.Logger := LogItf; if Assigned(ModbusDispatcher) then ModbusDispatcher.Logger := LogItf; LoggerItfVar := LogItf; end; class procedure TTrasmitterDispFactory.DestroyAllDispatchers; begin if Assigned(EssoDispatcherNew) then begin FreeAndNil(EssoDispatcherNew); end; if Assigned(ModbusDispatcher) then begin FreeAndNil(ModbusDispatcher); end; LoggerItfVar := nil; end; initialization EssoDispatcherNew := nil; ModbusDispatcher := nil; LoggerItfVar := nil; finalization TTrasmitterDispFactory.DestroyAllDispatchers; end.
unit uRay; interface uses uVect; type Ray = record origin, direction: Vect; class function Create: Ray; overload; static; class function Create(o,d: Vect): Ray; overload; static; end; implementation { Ray } class function Ray.Create: Ray; begin Result.origin := Vect.Create(0,0,0); Result.direction := Vect.Create(1,0,0); end; class function Ray.Create(o, d: Vect): Ray; begin Result.origin := o; Result.direction := d; end; end.
unit fTLangTool; // TFormTLangTool interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Forms, FMX.Dialogs, FMX.TabControl, System.Actions, FMX.ActnList, FMX.Objects, FMX.StdCtrls, System.Rtti, FMX.Grid.Style, FMX.Grid, Fmx.Platform, FMX.Styles, FMX.ScrollBox, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit; type TFormTLangTool = class(TForm) ActionList1: TActionList; PreviousTabAction1: TPreviousTabAction; TitleAction: TControlAction; NextTabAction1: TNextTabAction; TopToolBar: TToolBar; btnBack: TSpeedButton; ToolBarLabel: TLabel; btnNext: TSpeedButton; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; BottomToolBar: TToolBar; layoutTopLangPg1: TLayout; TransGrid: TStringGrid; StringColumn1: TStringColumn; StringColumn2: TStringColumn; StringColumn3: TStringColumn; StringColumn4: TStringColumn; StringColumn5: TStringColumn; StringColumn6: TStringColumn; StringColumn7: TStringColumn; btnLoadLngFile: TButton; Lang1: TLang; btnPasteLanguage: TButton; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; btnSaveFileAs: TButton; btnClearAll: TButton; StringColumn8: TStringColumn; StringColumn9: TStringColumn; StringColumn10: TStringColumn; StringColumn11: TStringColumn; StringColumn12: TStringColumn; StringColumn13: TStringColumn; StringColumn14: TStringColumn; StringColumn15: TStringColumn; btnAddLanguage: TButton; btnCopyTextsToClipboard: TButton; rectAboutLangTool: TRectangle; labVersion: TLabel; Label1: TLabel; linkGit: TLabel; Label2: TLabel; Label3: TLabel; btnDelLanguage: TButton; labHeaderLangTool: TLabel; btnTestTrans: TButton; btnOk: TButton; btnCancel: TButton; btnOpenOldEditor: TButton; edTranslationTest: TEdit; procedure FormCreate(Sender: TObject); procedure TitleActionUpdate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure btnLoadLngFileClick(Sender: TObject); procedure btnSaveFileAsClick(Sender: TObject); procedure btnClearAllClick(Sender: TObject); procedure btnAddLanguageClick(Sender: TObject); procedure btnCopyTextsToClipboardClick(Sender: TObject); procedure btnPasteLanguageClick(Sender: TObject); procedure btnDelLanguageClick(Sender: TObject); procedure btnTestTransClick(Sender: TObject); procedure btnOpenOldEditorClick(Sender: TObject); private procedure ClearLang1; procedure ClearGrid; procedure DoClearAll; procedure DoAddLanguage(const aLang: String); procedure DoDeleteColumn; procedure LoadNativeLanguage; public procedure populateGridWithLanguages; procedure copyGridToLang1; end; var FormTLangTool: TFormTLangTool; implementation uses // DesignEditors, // DesignIntf, // LangToolEditor, // PrevEditorClass omNativeLanguage; // {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.iPhone4in.fmx IOS} function TryGetClipboardService(out _clp: IFMXClipboardService): boolean; begin Result := TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService); if Result then _clp := IFMXClipboardService(TPlatformServices.Current.GetPlatformService(IFMXClipboardService)); end; procedure StringToClipboard(const _s: string); var clp: IFMXClipboardService; begin if TryGetClipboardService(clp) then clp.SetClipboard(_s); end; procedure StringFromClipboard(out _s: string); var clp: IFMXClipboardService; Value: TValue; s: string; begin if TryGetClipboardService(clp) then begin Value := clp.GetClipboard; if not Value.TryAsType(_s) then _s := ''; end; end; { TFormTLangTool } procedure TFormTLangTool.FormCreate(Sender: TObject); var aLang:String; begin { This defines the default active tab at runtime } TabControl1.First(TTabTransition.None); LoadNativeLanguage; end; procedure TFormTLangTool.LoadNativeLanguage; var aLang:String; begin // This app is not localized at this time, but this is how you get the // navive language and localize your form aLang := Copy(NativeLanguage,1,2); // like 'en' or 'pt' get native language ( drop coutry part ) if (CompareText( aLang,'en')<>0) then // en is default begin LoadLangFromStrings( Lang1.LangStr[aLang] ); // load language from resources, if available // LocalizeDialogButtons; end; end; procedure TFormTLangTool.TitleActionUpdate(Sender: TObject); begin if Sender is TCustomAction then begin if TabControl1.ActiveTab <> nil then TCustomAction(Sender).Text := TabControl1.ActiveTab.Text else TCustomAction(Sender).Text := ''; end; end; procedure TFormTLangTool.populateGridWithLanguages; var len: Cardinal; i,j: Integer; r,c:integer; S,aTrans,sLang,aOrig:String; begin // Sep := #9; //csv w/ tab ClearGrid; len := Lang1.Resources.Count; // number of languages S := 'en'; // Original language = 'en' c:=0; r:=0; // col row TransGrid.Columns[0].Header := S; // 1st col= Original texts for j := 0 to Lang1.Original.Count-1 do TransGrid.Cells[0,j] := Lang1.Original.Strings[j]; for i:=0 to len-1 do //for each lang, build column begin c := i+1; sLang := Lang1.Resources[i]; // sLang tipo 'pt' // TransGrid.Cells[c,0] := sLang; // header da lingua TransGrid.Columns[c].Header := sLang; // // LoadLangFromStrings( Lang1.LangStr[sLang]); // load language strings if available for j:=0 to Lang1.Original.Count-1 do begin aOrig := Lang1.Original.Strings[j]; aTrans := Translate(aOrig); if (aTrans=aOrig) then aTrans:=''; TransGrid.Cells[c,j] := aTrans; end; end; end; procedure TFormTLangTool.btnAddLanguageClick(Sender: TObject); begin InputBox('New Lang','Enter language code (2 chars):','', procedure(const AResult: TModalResult; const AValue: string) begin if (AResult=mrOK) then DoAddLanguage(AValue); end ); end; procedure TFormTLangTool.DoAddLanguage(const aLang:String); var c:integer; aCol:TColumn; begin for c:=1 to TransGrid.ColumnCount-1 do begin aCol := TransGrid.Columns[c]; if aCol.Header='' then begin aCol.Header := aLang; exit; end; end; end; procedure TFormTLangTool.btnClearAllClick(Sender: TObject); begin MessageDlg( 'Clear all?', System.UITypes.TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, procedure(const AResult: TModalResult) //non modal msg box for Android begin case AResult of mrYes: DoClearAll; // pressed yes, delete it mrNo: ; end; end ); end; procedure TFormTLangTool.btnCopyTextsToClipboardClick(Sender: TObject); var S,aText:String; r:integer; const crlf=#13#10; begin S:=''; for r :=0 to TransGrid.RowCount-1 do begin aText := TransGrid.Cells[0,r]; // col 0 has the originals if (aText<>'') then S := S+aText+crlf; end; StringToClipboard(S); end; procedure TFormTLangTool.btnDelLanguageClick(Sender: TObject); var c:integer; aCol:TColumn; begin c := TransGrid.ColumnIndex; if (c>0) then begin aCol := TransGrid.Columns[c]; MessageDlg( 'Delete column '+aCol.Header+'?', System.UITypes.TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, procedure(const AResult: TModalResult) //non modal msg box for Android begin case AResult of mrYes: DoDeleteColumn; // pressed yes, delete it mrNo: ; end; end ); end; end; procedure TFormTLangTool.DoDeleteColumn; var c:integer; aCol:TColumn; begin c := TransGrid.ColumnIndex; aCol := TransGrid.Columns[c]; aCol.DisposeOf; end; procedure TFormTLangTool.DoClearAll; // clear grid and Lang1 var c:integer; aCol:TColumn; begin for c:=1 to TransGrid.ColumnCount-1 do //clear grid headers begin aCol := TransGrid.Columns[c]; aCol.Header := ''; end; ClearGrid; // clear grid cells ClearLang1; // end; procedure TFormTLangTool.btnLoadLngFileClick(Sender: TObject); var fn,s:String; begin if OpenDialog1.Execute then begin fn := OpenDialog1.FileName; Lang1.LoadFromFile(fn); populateGridWithLanguages; // Lang1 --> Grid s := 'Loaded '+IntToStr(Lang1.Original.Count)+' texts '+IntToStr(Lang1.Resources.Count)+' languages'; labHeaderLangTool.Text := s; end; end; procedure TFormTLangTool.btnPasteLanguageClick(Sender: TObject); var S,aText:String; r,c,arow,i:integer; SL:TStringList; const crlf=#13#10; begin StringFromClipboard(S); SL := TStringList.Create; SL.Text := S; c := TransGrid.ColumnIndex; arow := TransGrid.Selected; if (SL.Count>0) then begin for i := 0 to SL.Count-1 do begin S := SL.Strings[i]; TransGrid.Cells[c,arow+i] := S; end; end; SL.Free; end; procedure TFormTLangTool.ClearLang1; begin Lang1.Lang := 'en'; //original Lang1.Original.Clear; // TODO: dispose Resources? Lang1.Resources.Clear; end; procedure TFormTLangTool.ClearGrid; var c, r: Integer; begin for c := 0 to Pred(TransGrid.ColumnCount) do for r := 0 to Pred(TransGrid.RowCount) do TransGrid.Cells[c, r] := ''; end; procedure TFormTLangTool.copyGridToLang1; //tricky var c,r:integer; aCol:TColumn; aText,aTrans,aLang,S:String; aStrings:TStrings; begin ClearLang1; c:=0; //Originals aCol := TransGrid.Columns[0]; for r :=0 to TransGrid.RowCount-1 do begin aText := TransGrid.Cells[c,r]; if (aText<>'') then Lang1.Original.Add(aText); // populate Originals end; for c:=1 to TransGrid.ColumnCount-1 do begin aCol := TransGrid.Columns[c]; aLang := aCol.Header; if (aLang<>'') then begin Lang1.AddLang(aLang); // this create a stringlist for each lang aStrings := Lang1.LangStr[aLang]; for r:=0 to TransGrid.RowCount-1 do //for each text.. begin aText := TransGrid.Cells[0,r]; if Trim(aText)='' then continue; //ignore empty original texts aTrans := TransGrid.Cells[c,r]; //get translation if (aTrans<>'') then //has tranlation for this text? begin S := aText+'='+aTrans; // add name=value line aStrings.Add(S); end; end; end; end; end; procedure TFormTLangTool.btnSaveFileAsClick(Sender: TObject); var fn:String; begin // if (OpenDialog1.Filename<>'') then SaveDialog1.Filename := OpenDialog1.Filename; if SaveDialog1.Execute then begin fn := SaveDialog1.Filename; copyGridToLang1; Lang1.SaveToFile(fn); end; end; procedure TFormTLangTool.btnOpenOldEditorClick(Sender: TObject); // var s:string; aOldEditor:TComponentEditor; begin // if Assigned(PrevEditorClass) then // begin // s := 'PrevEditorClass ok:'; // aOldEditor := TComponentEditor(PrevEditorClass.Create(Lang1,{ADesigner:}nil )); // if Assigned(aOldEditor) then aOldEditor.Edit; // end // else s := 'PrevEditorClass nil'; // labHeaderLangTool.Text := s; end; procedure TFormTLangTool.btnTestTransClick(Sender: TObject); var s:String; begin LoadNativeLanguage; s := Translate(edTranslationTest.Text ); //test 'Yes' labHeaderLangTool.Text := s; end; procedure TFormTLangTool.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (Key = vkHardwareBack) and (TabControl1.TabIndex <> 0) then begin TabControl1.First; Key := 0; end; end; end.
unit uDecoupled; interface type IReader = interface function ReadAll: TArray<Byte>; end; IWriter = interface procedure WriteAll(aBytes: TArray<Byte>); end; TCompressionService = class private function DoCompression(aByteArray: TArray<Byte>): TArray<Byte>; public procedure Compress(aReader: IReader; aWriter: IWriter); end; implementation { TCompressionService } procedure TCompressionService.Compress(aReader: IReader; aWriter: IWriter); var LContent: TArray<Byte>; LCompressedContent: TArray<Byte>; begin // Read Content LContent := aReader.ReadAll; // Compress LCompressedContent := DoCompression(LContent); // WriteContent aWriter.WriteAll(LCompressedContent); end; function TCompressionService.DoCompression(aByteArray: TArray<Byte>): TArray<Byte>; begin // Compression Algorithm would go here..... Result := aByteArray; end; end.
unit RestServer; interface uses Vcl.Forms, HttpServerCommand, IdHTTPServer, IdContext, IdHeaderList, IdCustomHTTPServer, classes, IdUri, System.SysUtils; type TRestServer = Class strict private FOwner: TComponent; FCommand: THttpServerCommand; FHttpServer : TIdHTTPServer; FOnLogMessage: TOnLogMessage; private procedure OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); //procedure OnCommandOther(ACommand, AData, AVersion, Thread); procedure CreatePostStream(AContext: TIdContext; AHeaders: TIdHeaderList; var VPostStream: TStream); procedure LogMessage(const msg: String); public constructor Create(AOwner: TComponent); procedure Start(port: word); property OnLogMessage: TOnLogMessage read FOnLogMessage write FOnLogMessage; end; implementation uses Commands.GetWindowHandle, Commands.DeleteSession, Commands.PostElementElements, Commands.PostExecute, Commands.GetElementValue, Commands.PostClear, Commands.GetText, Commands.ClickElement, Commands.GetRect, Commands.PostElements, Commands.PostElement, Commands.CreateSession, Commands.GetEnabled, Commands.PostValue, System.JSON.Types, System.JSON.Writers, System.JSON.Builders, Commands; { TRestServer } constructor TRestServer.Create(AOwner: TComponent); begin inherited Create; FOwner := AOwner; FCommand:= THttpServerCommand.Create(AOwner); FCommand.Commands.Register(TGetElementValueCommand); FCommand.Commands.Register(TGetEnabledCommand); FCommand.Commands.Register(TGetRectCommand); FCommand.Commands.Register(TGetTextCommand); // FCommand.Commands.Register(TGetElementCommand); //FCommand.Commands.Register(TGetScreenshotCommand); FCommand.Commands.Register(TGetWindowhandleCommand); FCommand.Commands.Register(TGetWindowCommand); FCommand.Commands.Register(TGetTitleCommand); FCommand.Commands.Register(TGetSessionCommand); FCommand.Commands.Register(TGetSessionsCommand); FCommand.Commands.Register(TStatusCommand); FCommand.Commands.Register(TPostValueCommand); FCommand.Commands.Register(TPostClearCommand); FCommand.Commands.Register(TClickElementCommand); FCommand.Commands.Register(TPostElementElementsCommand); // Avoiding mismatch with pattern above FCommand.Commands.Register(TPostElementsCommand); FCommand.Commands.Register(TPostElementCommand); FCommand.Commands.Register(TPostExecuteCommand); FCommand.Commands.Register(TPostImplicitWaitCommand); FCommand.Commands.Register(TSessionTimeoutsCommand); FCommand.Commands.Register(TCreateSessionCommand); FCommand.Commands.Register(TDeleteSessionCommand); FCommand.OnLogMessage := FOnLogMessage; FHttpServer := TIdHTTPServer.Create(AOwner); end; procedure TRestServer.CreatePostStream(AContext: TIdContext; AHeaders: TIdHeaderList; var VPostStream: TStream); begin VPostStream := TStringStream.Create; end; procedure TRestServer.LogMessage(const msg: String); begin if assigned(FOnLogMessage) then OnLogMessage(msg); end; procedure TRestServer.OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var cmd: String; begin cmd := ARequestInfo.Command; LogMessage('==================================================='); LogMessage(ARequestInfo.Command + ' ' + ARequestInfo.uri + ' ' + ARequestInfo.Version); LogMessage('Accept-Encoding: ' + ARequestInfo.AcceptEncoding); LogMessage('Connection: ' + ARequestInfo.Connection); LogMessage('Content-Length: ' + Inttostr(ARequestInfo.ContentLength)); LogMessage('Content-Type: ' + ARequestInfo.ContentType); LogMessage('Host: ' + ARequestInfo.Host); LogMessage(ARequestInfo.UserAgent); LogMessage(ARequestInfo.Params.CommaText); FCommand.CommandGet(AContext, ARequestInfo, AResponseInfo); LogMessage(''); LogMessage('Response: ' + IntToStr(AResponseInfo.ResponseNo)); // LogMessage('Content-Length:' + Inttostr(AResponseInfo.ContentLength)); LogMessage('Content-Type: ' + AResponseInfo.ContentType); LogMessage(AResponseInfo.ContentText); end; procedure TRestServer.Start(port: word); begin FHttpServer.DefaultPort := port; FHttpServer.OnCommandGet := OnCommandGet; FHttpServer.OnCommandOther := OnCommandGet; FHttpServer.OnCreatePostStream := CreatePostStream; FHttpServer.Active := True; end; end.
unit StreamingTestTypes; interface uses JSONSerialize; {$RTTI EXPLICIT METHODS(DefaultMethodRttiVisibility) FIELDS(DefaultFieldRttiVisibility) PROPERTIES(DefaultPropertyRttiVisibility)} type TSubObject = class private FSubProperty1: string; public [JSONPath('JSONSubField1')] SubField1: Integer; [JSONPath('JSONSubProperty1')] property SubProperty1: string read FSubProperty1 write FSubProperty1; end; IStreamingIntf = interface function GetSubObject: TSubObject; property SubObject1: TSubObject read GetSubObject; end; TDynStrings = array of string; TStreamingType = class(TInterfacedObject, IStreamingIntf) private FSubObject1: TSubObject; FStrings: TDynStrings; function GetSubObject: TSubObject; public constructor Create; destructor Destroy; override; procedure AddString(const Value: string); public [JSONPath('JSONField1')] Field1: string; [JSONPath('JSONSubObject1')] property SubObject1: TSubObject read GetSubObject; [JSONPath('JSONArrayProperty')] property Strings: TDynStrings read FStrings write FStrings; end; TIntPair = array[0..1] of Integer; TStreamingRecord = record public [JSONPath('JSON_A')] A: string; [JSONPath('JSON_B')] B: TIntPair; end; implementation { TStreamingType } procedure TStreamingType.AddString(const Value: string); var curSize: Integer; begin curSize := Length(FStrings); SetLength(FStrings, curSize + 1); FStrings[curSize] := Value; end; constructor TStreamingType.Create; begin inherited; FSubObject1 := TSubObject.Create; end; destructor TStreamingType.Destroy; begin FSubObject1.Free; inherited; end; function TStreamingType.GetSubObject: TSubObject; begin Result := FSubObject1; end; end.
unit uConsultaMetaAssessoria; interface uses REST.Types, Data.Bind.Components, Data.Bind.ObjectScope, REST.Client, System.SysUtils, REST.Json, System.Json.Readers, uProduto, System.Json.Types, System.Classes; type IConsulta = Interface(IInterface) ['{0E911E20-D972-4862-B15E-CB362C023A89}'] function BaseURL(const Value: string): IConsulta; overload; function BaseURL: string; overload; function Token(const Value: string): IConsulta; overload; function Token: string; overload; function Ambiente(const Value: string): IConsulta; overload; function Ambiente: string; overload; function CNPJ(const Value: string): IConsulta; overload; function CNPJ: string; overload; function Usuario(const Value: string): IConsulta; overload; function Usuario: string; overload; function EAN(const Value: string): IConsulta; overload; function EAN: string; overload; function Consultar: TProduto; function ConsultarStatus: Boolean; procedure ProcessProdutoRead(Produtos: TProduto; jtr: TJsonReader); End; TConsulta = class(TInterfacedObject, IConsulta) strict private FBaseURL: string; FToken: string; FAmbiente: string; FCNPJ: string; FUsuario: string; FEAN: string; private procedure CreateParam(const RESTRequest: TRESTRequest; const ParamName, ParamValue: string); public class function New: IConsulta; function BaseURL(const Value: string): IConsulta; overload; function BaseURL: string; overload; function Token(const Value: string): IConsulta; overload; function Token: string; overload; function Ambiente(const Value: string): IConsulta; overload; function Ambiente: string; overload; function CNPJ(const Value: string): IConsulta; overload; function CNPJ: string; overload; function Usuario(const Value: string): IConsulta; overload; function Usuario: string; overload; function EAN(const Value: string): IConsulta; overload; function EAN: string; overload; function Consultar: TProduto; function ConsultarStatus: Boolean; procedure ProcessProdutoRead(Produtos: TProduto; jtr: TJsonReader); End; implementation { TConsulta } var eProduto: TProduto; function TConsulta.Ambiente(const Value: string): IConsulta; begin Result := Self; FAmbiente := Value; end; function TConsulta.Ambiente: string; begin Result := FAmbiente; end; function TConsulta.BaseURL(const Value: string): IConsulta; begin Result := Self; FBaseURL := Value; end; function TConsulta.BaseURL: string; begin Result := FBaseURL; end; function TConsulta.CNPJ: string; begin Result := FCNPJ; end; procedure TConsulta.CreateParam(const RESTRequest: TRESTRequest; const ParamName, ParamValue: string); begin with RESTRequest.Params.AddItem do begin Name := ParamName; Value := ParamValue; Kind := TRESTRequestParameterKind.pkGETorPOST; end; end; function TConsulta.EAN: string; begin Result := FEAN; end; class function TConsulta.New: IConsulta; begin eProduto := TProduto.Create; Result := Self.Create; end; procedure TConsulta.ProcessProdutoRead(Produtos: TProduto; jtr: TJsonReader); begin try while jtr.Read do begin if jtr.TokenType = TjsonToken.PropertyName then begin if jtr.Value.ToString = 'Codigo' then begin jtr.Read; eProduto.Codigo := jtr.Value.AsInteger; end; if jtr.Value.ToString = 'EAN' then begin jtr.Read; eProduto.EAN := jtr.Value.AsString; end; if jtr.Value.ToString = 'produtoDescricao' then begin jtr.Read; eProduto.Descricao := jtr.Value.AsString; end; if jtr.Value.ToString = 'embalagemUnitariaUnidadeSigla' then begin jtr.Read; eProduto.UnidadeMedidaSigla := jtr.Value.AsString; end; if jtr.Value.ToString = 'tributarioNcm' then begin jtr.Read; eProduto.NCM := jtr.Value.AsString; end; if jtr.Value.ToString = 'tributarioCest' then begin jtr.Read; eProduto.CEST := jtr.Value.AsString; end; if jtr.Value.ToString = 'produtoDiasValidade' then begin jtr.Read; eProduto.DiasValidade := jtr.Value.AsString; end; if jtr.Value.ToString = 'embalagemUnitariaPesoBruto' then begin jtr.Read; eProduto.PesoBruto := jtr.Value.AsString; end; if jtr.Value.ToString = 'embalagemUnitariaPesoLiquido' then begin jtr.Read; eProduto.PesoLiquido := jtr.Value.AsString; end; if jtr.Value.ToString = 'TribRegraCodPerfilOrigem' then begin jtr.Read; eProduto.Origem := jtr.Value.AsInteger; end; if jtr.Value.ToString = 'tribRegraCfop' then begin jtr.Read; eProduto.Cfop := jtr.Value.AsString; end; if jtr.Value.ToString = 'tribIcmsCst' then begin jtr.Read; eProduto.CSTICMS := jtr.Value.AsString; end; if jtr.Value.ToString = 'tribIcmsAliq' then begin jtr.Read; eProduto.AliqICMS := jtr.Value.AsString; end; if jtr.Value.ToString = 'tribIcmsReducao' then begin jtr.Read; eProduto.RedBaseICMS := jtr.Value.AsString; end; if jtr.Value.ToString = 'tribRegraPisCst' then begin jtr.Read; if copy(eProduto.Cfop, 1, 1) = '5' then eProduto.CSTPIS := jtr.Value.AsString; end; if jtr.Value.ToString = 'fisRegraCofinsCst' then begin jtr.Read; if copy(eProduto.Cfop, 1, 1) = '5' then eProduto.CSTCofins := jtr.Value.AsString; end; if jtr.Value.ToString = 'resultadoConsulta' then begin jtr.Read; eProduto.ResultadoConsulta := jtr.Value.AsString; end; // if jtr.TokenType = TJsonToken.EndObject then // begin // Result := eProduto; // end; end; end; finally end; end; function TConsulta.EAN(const Value: string): IConsulta; begin Result := Self; FEAN := Value; end; function TConsulta.Consultar: TProduto; var RESTClient: TRESTClient; RESTRequest: TRESTRequest; RESTResponse: TRESTResponse; // eProdutos : TProduto; sr: TStringReader; jtr: TJsonTextReader; begin // eProduto := TProduto.Create; RESTClient := TRESTClient.Create(nil); try RESTRequest := TRESTRequest.Create(nil); try RESTResponse := TRESTResponse.Create(nil); try RESTRequest.Client := RESTClient; RESTRequest.Response := RESTResponse; RESTClient.BaseURL := FBaseURL; RESTClient.ContentType := 'application/x-www-form-urlencoded'; RESTRequest.Method := TRESTRequestMethod.rmPOST; RESTRequest.Params.AddHeader('token', FToken); RESTRequest.Params.AddHeader('ambiente', FAmbiente); CreateParam(RESTRequest, 'cnpj', FCNPJ); CreateParam(RESTRequest, 'ean', FEAN); CreateParam(RESTRequest, 'usuario', FUsuario); RESTRequest.Execute; sr := TStringReader.Create(RESTResponse.JSONValue.ToString); try jtr := TJsonTextReader.Create(sr); try while jtr.Read do begin if jtr.TokenType = TjsonToken.StartObject then ProcessProdutoRead(eProduto, jtr); end; finally FreeAndNil(jtr); end; finally FreeAndNil(sr); end; finally FreeAndNil(RESTResponse); end; finally FreeAndNil(RESTRequest); end; finally FreeAndNil(RESTClient); end; Result := eProduto; end; function TConsulta.ConsultarStatus: Boolean; var RESTClient: TRESTClient; RESTRequest: TRESTRequest; RESTResponse: TRESTResponse; begin RESTClient := TRESTClient.Create(nil); try RESTRequest := TRESTRequest.Create(nil); try RESTResponse := TRESTResponse.Create(nil); try RESTRequest.Client := RESTClient; RESTRequest.Response := RESTResponse; RESTClient.BaseURL := FBaseURL; RESTClient.ContentType := 'application/x-www-form-urlencoded'; RESTRequest.Method := TRESTRequestMethod.rmPOST; try RESTRequest.Execute; except Result := False; end; Result := RESTResponse.StatusCode = 200 finally FreeAndNil(RESTResponse); end; finally FreeAndNil(RESTRequest); end; finally FreeAndNil(RESTClient); end; end; function TConsulta.CNPJ(const Value: string): IConsulta; begin Result := Self; FCNPJ := Value; end; function TConsulta.Token: string; begin Result := FToken; end; function TConsulta.Token(const Value: string): IConsulta; begin Result := Self; FToken := Value; end; function TConsulta.Usuario(const Value: string): IConsulta; begin Result := Self; FUsuario := Value; end; function TConsulta.Usuario: string; begin Result := FUsuario; end; end.
unit CommonfrmAbout; // Description: About Dialog // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, OTFEFreeOTFEBase_U, SDUStdCtrls, SDUForms; type TfrmAbout = class(TSDUForm) pbOK: TButton; imgIcon: TImage; lblAppID: TLabel; lblDescription: TLabel; lblTitle: TLabel; lblBeta: TLabel; lblDriverVersion: TLabel; lblAuthor: TLabel; pnlDividerUpper: TPanel; pnlDividerLower: TPanel; Label3: TLabel; SDUURLLabel1: TSDUURLLabel; lblTranslatorCredit: TLabel; procedure FormShow(Sender: TObject); private public FreeOTFEObj: TOTFEFreeOTFEBase; BetaNumber: integer; Description: string; end; implementation {$R *.DFM} uses ShellApi, // Needed for ShellExecute SDUi18n, SDUGeneral, CommonConsts; procedure TfrmAbout.FormShow(Sender: TObject); const CONTROL_MARGIN = 10; var majorVersion : integer; minorVersion : integer; revisionVersion: integer; buildVersion : integer; OTFEVersion: string; descAdjustDown: integer; begin self.Caption := SDUParamSubstitute(_('About %1'), [Application.Title]); lblTitle.caption := Application.Title; lblAppID.left := lblTitle.left + lblTitle.width + CONTROL_MARGIN; lblTranslatorCredit.Visible := FALSE; if ( (SDUGetCurrentLanguageCode() <> '') and not(SDUIsLanguageCodeEnglish(SDUGetCurrentLanguageCode())) ) then begin lblTranslatorCredit.Visible := TRUE; lblTranslatorCredit.Caption := SDUParamSubstitute( _('%1 translation by %2'), [_(CONST_LANGUAGE_ENGLISH), SDUGetTranslatorName()] ); end; imgIcon.Picture.Assign(Application.Icon); SDUGetVersionInfo('', majorVersion, minorVersion, revisionVersion, buildVersion); lblAppID.caption := 'v'+SDUGetVersionInfoString(''); if BetaNumber>-1 then begin lblAppID.caption := lblAppID.caption + ' BETA '+inttostr(BetaNumber); end; lblBeta.visible := (BetaNumber>-1); if FreeOTFEObj.Active then begin OTFEVersion := FreeOTFEObj.VersionStr(); if (OTFEVersion<>'') then begin OTFEVersion := SDUParamSubstitute(_('FreeOTFE driver: %1'), [OTFEVersion]); end; end else begin OTFEVersion := _('The main FreeOTFE driver is either not installed, or not started'); end; lblDescription.caption := Description; // Some translated languages may increase the number of lines the // description takes up. Here we increase the height of the dialog to // compensate, and nudge the controls below it down descAdjustDown := ( lblDescription.Top + lblDescription.Height + CONTROL_MARGIN ) - pnlDividerUpper.Top; self.height := self.height + descAdjustDown; pnlDividerUpper.Top := pnlDividerUpper.Top + descAdjustDown; SDUURLLabel1.Top := SDUURLLabel1.Top + descAdjustDown; pnlDividerLower.Top := pnlDividerLower.Top + descAdjustDown; lblDriverVersion.Top := lblDriverVersion.Top + descAdjustDown; pbOK.Top := pbOK.Top + descAdjustDown; SDUCenterControl(lblDescription, ccHorizontal); lblDriverVersion.caption := OTFEVersion; SDUCenterControl(lblDriverVersion, ccHorizontal); pnlDividerUpper.Caption := ''; pnlDividerLower.Caption := ''; end; END.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [FIN_FECHAMENTO_CAIXA_BANCO] 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 FinFechamentoCaixaBancoService; interface uses FinFechamentoCaixaBanco, BancoContaCaixa, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TFinFechamentoCaixaBancoService = class(TServiceBase) private class procedure AnexarObjetosVinculados(AListaFinFechamentoCaixaBanco: TObjectList<TFinFechamentoCaixaBanco>); overload; class procedure AnexarObjetosVinculados(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco); overload; public class function ConsultarLista: TObjectList<TFinFechamentoCaixaBanco>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TFinFechamentoCaixaBanco>; class function ConsultarObjeto(AId: Integer): TFinFechamentoCaixaBanco; class procedure Inserir(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco); class function Alterar(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco): Integer; class function Excluir(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco): Integer; end; var sql: string; implementation { TFinFechamentoCaixaBancoService } class procedure TFinFechamentoCaixaBancoService.AnexarObjetosVinculados(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco); begin // BancoContaCaixa sql := 'SELECT * FROM BANCO_CONTA_CAIXA WHERE ID = ' + AFinFechamentoCaixaBanco.IdBancoContaCaixa.ToString; AFinFechamentoCaixaBanco.BancoContaCaixa := GetQuery(sql).AsObject<TBancoContaCaixa>; end; class procedure TFinFechamentoCaixaBancoService.AnexarObjetosVinculados(AListaFinFechamentoCaixaBanco: TObjectList<TFinFechamentoCaixaBanco>); var FinFechamentoCaixaBanco: TFinFechamentoCaixaBanco; begin for FinFechamentoCaixaBanco in AListaFinFechamentoCaixaBanco do begin AnexarObjetosVinculados(FinFechamentoCaixaBanco); end; end; class function TFinFechamentoCaixaBancoService.ConsultarLista: TObjectList<TFinFechamentoCaixaBanco>; begin sql := 'SELECT * FROM FIN_FECHAMENTO_CAIXA_BANCO ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TFinFechamentoCaixaBanco>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TFinFechamentoCaixaBancoService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TFinFechamentoCaixaBanco>; begin sql := 'SELECT * FROM FIN_FECHAMENTO_CAIXA_BANCO where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TFinFechamentoCaixaBanco>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TFinFechamentoCaixaBancoService.ConsultarObjeto(AId: Integer): TFinFechamentoCaixaBanco; begin sql := 'SELECT * FROM FIN_FECHAMENTO_CAIXA_BANCO WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TFinFechamentoCaixaBanco>; AnexarObjetosVinculados(Result); end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TFinFechamentoCaixaBancoService.Inserir(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco); begin AFinFechamentoCaixaBanco.ValidarInsercao; AFinFechamentoCaixaBanco.Id := InserirBase(AFinFechamentoCaixaBanco, 'FIN_FECHAMENTO_CAIXA_BANCO'); end; class function TFinFechamentoCaixaBancoService.Alterar(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco): Integer; begin AFinFechamentoCaixaBanco.ValidarAlteracao; Result := AlterarBase(AFinFechamentoCaixaBanco, 'FIN_FECHAMENTO_CAIXA_BANCO'); end; class function TFinFechamentoCaixaBancoService.Excluir(AFinFechamentoCaixaBanco: TFinFechamentoCaixaBanco): Integer; begin AFinFechamentoCaixaBanco.ValidarExclusao; Result := ExcluirBase(AFinFechamentoCaixaBanco.Id, 'FIN_FECHAMENTO_CAIXA_BANCO'); end; end.