text
stringlengths
14
6.51M
unit uUtils; interface type TCharSet = set of Char; function ValidateObj(Obj: TObject): Pointer; function IsPathRelative(APath: string): boolean; function AddPathDelim(APath: string): string; function ObjectToVariant(const AObject: TObject): Variant; function WordPosition(const N: Integer; const S: string; const WordDelims: TCharSet): Integer; function ExtractWord(N: Integer; const S: string; const WordDelims: TCharSet): string; implementation uses System.SysUtils; function WordPosition(const N: Integer; const S: string; const WordDelims: TCharSet): Integer; var Count, I: Integer; begin Count := 0; I := 1; Result := 0; while (I <= Length(S)) and (Count <> N) do begin { skip over delimiters } while (I <= Length(S)) and (S[I] in WordDelims) do Inc(I); { if we"re not beyond end of S, we"re at the start of a word } if I <= Length(S) then Inc(Count); { if not finished, find the end of the current word } if Count <> N then while (I <= Length(S)) and not (S[I] in WordDelims) do Inc(I) else Result := I; end; end; function ExtractWord(N: Integer; const S: string; const WordDelims: TCharSet): string; var I: Integer; Len: Integer; begin Len := 0; I := WordPosition(N, S, WordDelims); if I <> 0 then { find the end of the current word } while (I <= Length(S)) and not(S[I] in WordDelims) do begin { add the I"th character to result } Inc(Len); SetLength(Result, Len); Result[Len] := S[I]; Inc(I); end; SetLength(Result, Len); end; function ObjectToVariant(const AObject: TObject): Variant; begin Result := IntToStr(Integer(Pointer(AObject))); end; function ValidateObj(Obj: TObject): Pointer; begin Result := Obj; if Assigned(Result) then try if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then Result := nil; except Result := nil; end; end; function IsPathRelative(APath: string): boolean; begin result := true; if Length(APath) > 0 then begin if IsPathDelimiter(APath, 1) then begin result := false; exit; end; if ExtractFileDrive(APath) <> '' then begin result := false; exit; end; end; end; function AddPathDelim(APath: string): string; begin result := IncludeTrailingBackslash(APath); end; end.
unit glr_render2d; {$i defines.inc} interface uses glr_render, glr_scene, glr_math, glr_utils; type { TglrSprite } TglrSprite = class (TglrNode) protected fRot, fWidth, fHeight: Single; fPP: TglrVec2f; fTextureRegion: PglrTextureRegion; procedure SetRot(const aRot: Single); virtual; procedure SetWidth(const aWidth: Single); virtual; procedure SetHeight(const aHeight: Single); virtual; procedure SetPP(const aPP: TglrVec2f); virtual; public Vertices: array[0..3] of TglrVertexP3T2C4; constructor Create(); override; overload; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); virtual; overload; destructor Destroy(); override; property Rotation: Single read fRot write SetRot; property Width: Single read fWidth write SetWidth; property Height: Single read fHeight write SetHeight; property PivotPoint: TglrVec2f read fPP write SetPP; procedure SetDefaultVertices(); virtual;//Sets vertices due to width, height, pivot point and rotation procedure SetDefaultTexCoords(); //Sets default texture coords procedure SetFlippedTexCoords(); procedure SetVerticesColor(aColor: TglrVec4f); virtual; procedure SetVerticesAlpha(aAlpha: Single); virtual; procedure SetSize(aWidth, aHeight: Single); overload; procedure SetSize(aSize: TglrVec2f); overload; procedure SetTextureRegion(aRegion: PglrTextureRegion; aAdjustSpriteSize: Boolean = True); virtual; function GetTextureRegion(): PglrTextureRegion; procedure RenderSelf(); override; end; TglrSpriteList = TglrObjectList<TglrSprite>; { TglrText } TglrTextHorAlign = (haLeft, haCenter, haRight); TglrText = class (TglrNode) protected fHorAlign: TglrTextHorAlign; fTextWidth: Single; fTextWidthChanged: Boolean; procedure SetHorAlign(aValue: TglrTextHorAlign); procedure SetTextWidth(aValue: Single); public Text: WideString; LetterSpacing, LineSpacing: Single; Color: TglrVec4f; Scale: Single; PivotPoint: TglrVec2f; ShadowEnabled: Boolean; ShadowOffset: TglrVec2f; ShadowColor: TglrVec4f; constructor Create(const aText: WideString = ''); virtual; reintroduce; destructor Destroy(); override; property TextWidth: Single read fTextWidth write SetTextWidth; property HorAlign: TglrTextHorAlign read fHorAlign write SetHorAlign; procedure RenderSelf(); override; end; { TglrFont } TglrFont = class protected type TglrCharData = record ID: WideChar; py: Word; w, h: Word; tx, ty, tw, th: Single; end; PglrCharData = ^TglrCharData; var Material: TglrMaterial; Texture: TglrTexture; Table: array [WideChar] of PglrCharData; CharData: array of TglrCharData; function GetCharQuad(aChar: WideChar; aScale: Single): TglrQuadP3T2C4; public MaxCharHeight: Word; constructor Create(); virtual; overload; constructor Create(aStream: TglrStream; aFreeStreamOnFinish: Boolean = True); virtual; overload; constructor Create(aStream: TglrStream; aShader: TglrShaderProgram; aFreeStreamOnFinish: Boolean = True); virtual; overload; destructor Destroy(); override; end; { TglrSpriteBatch } TglrSpriteBatch = class protected fVData: array[0..65535] of TglrVertexP3T2C4; fIData: array[0..65535] of Word; fCount: Word; fVB: TglrVertexBuffer; fIB: TglrIndexBuffer; public constructor Create(); virtual; destructor Destroy(); override; procedure Start(); procedure Draw(aSprite: TglrSprite); overload; procedure Draw(aSprites: array of TglrSprite); overload; procedure Draw(aSprites: TglrSpriteList); overload; procedure Finish(); end; { TglrFontBatch } TglrFontBatch = class protected fVData: array[0..65535] of TglrVertexP3T2C4; fIData: array[0..65535] of Word; fCount: Word; fVB: TglrVertexBuffer; fIB: TglrIndexBuffer; fFont: TglrFont; function GetTextOrigin(aText: TglrText): TglrVec2f; procedure WordWrapText(aText: TglrText); procedure DrawShadow(aText: TglrText); public constructor Create(aFont: TglrFont); virtual; destructor Destroy(); override; procedure Start(); procedure Draw(aText: TglrText); procedure Finish(); end; implementation uses glr_core, glr_filesystem, glr_resload; const SpriteIndices: array[0..5] of Word = (0, 1, 2, 2, 3, 0); { TglrSprite } procedure TglrSprite.SetRot(const aRot: Single); begin if (not Equalf(aRot, fRot)) then begin Matrix.Identity(); Matrix.Rotate(aRot * deg2rad, Vec3f(0, 0, 1)); fRot := aRot; if fRot > 360 then fRot -= 360 else if fRot < -360 then fRot += 360; end; end; procedure TglrSprite.SetWidth(const aWidth: Single); begin if (not Equalf(aWidth, fWidth)) then begin fWidth := aWidth; SetDefaultVertices(); end; end; procedure TglrSprite.SetHeight(const aHeight: Single); begin if (not Equalf(aHeight, fHeight)) then begin fHeight := aHeight; SetDefaultVertices(); end; end; procedure TglrSprite.SetPP(const aPP: TglrVec2f); begin if (aPP <> fPP) then begin fPP := aPP; SetDefaultVertices(); end; end; constructor TglrSprite.Create; begin Create(1, 1, Vec2f(0.5, 0.5)); end; constructor TglrSprite.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin inherited Create(); fWidth := aWidth; fHeight := aHeight; fPP := aPivotPoint; SetDefaultVertices(); SetDefaultTexCoords(); SetVerticesColor(Vec4f(1, 1, 1, 1)); fTextureRegion := nil; end; destructor TglrSprite.Destroy; begin inherited Destroy; end; procedure TglrSprite.SetDefaultVertices; begin Vertices[0].vec := Vec3f((Vec2f(1, 1) - fPP) * Vec2f(fWidth, fHeight), 0); Vertices[1].vec := Vec3f((Vec2f(1, 0) - fPP) * Vec2f(fWidth, fHeight), 0); Vertices[2].vec := Vec3f((fPP.NegateVector) * Vec2f(fWidth, fHeight), 0); Vertices[3].vec := Vec3f((Vec2f(0, 1) - fPP) * Vec2f(fWidth, fHeight), 0); end; procedure TglrSprite.SetDefaultTexCoords; begin Vertices[0].tex := Vec2f(1, 1); Vertices[1].tex := Vec2f(1, 0); Vertices[2].tex := Vec2f(0, 0); Vertices[3].tex := Vec2f(0, 1); end; procedure TglrSprite.SetFlippedTexCoords; begin Vertices[0].tex := Vec2f(1, 0); Vertices[1].tex := Vec2f(1, 1); Vertices[2].tex := Vec2f(0, 1); Vertices[3].tex := Vec2f(0, 0); end; procedure TglrSprite.SetVerticesColor(aColor: TglrVec4f); var i: Integer; begin for i := 0 to 3 do Vertices[i].col := aColor; end; procedure TglrSprite.SetVerticesAlpha(aAlpha: Single); var i: Integer; begin for i := 0 to 3 do Vertices[i].col.w := aAlpha; end; procedure TglrSprite.SetSize(aWidth, aHeight: Single); begin fWidth := aWidth; fHeight := aHeight; SetDefaultVertices(); end; procedure TglrSprite.SetSize(aSize: TglrVec2f); begin SetSize(aSize.x, aSize.y); end; procedure TglrSprite.SetTextureRegion(aRegion: PglrTextureRegion; aAdjustSpriteSize: Boolean); begin with aRegion^ do if not Rotated then begin Vertices[0].tex := Vec2f(tx + tw, ty + th); Vertices[1].tex := Vec2f(tx + tw, ty); Vertices[2].tex := Vec2f(tx, ty); Vertices[3].tex := Vec2f(tx, ty + th); if aAdjustSpriteSize then begin Width := tw * Texture.Width; Height := th * Texture.Height; end; end else begin Vertices[0].tex := Vec2f(tx, ty + th); Vertices[1].tex := Vec2f(tx + tw, ty + th); Vertices[2].tex := Vec2f(tx + tw, ty); Vertices[3].tex := Vec2f(tx, ty); if aAdjustSpriteSize then begin Width := th * Texture.Height; Height := tw * Texture.Width; end; end; fTextureRegion := aRegion; end; function TglrSprite.GetTextureRegion: PglrTextureRegion; begin Result := fTextureRegion; end; procedure TglrSprite.RenderSelf; begin end; { TglrText } procedure TglrText.SetHorAlign(aValue: TglrTextHorAlign); begin if fHorAlign = aValue then Exit(); fHorAlign := aValue; end; procedure TglrText.SetTextWidth(aValue: Single); begin if fTextWidth = aValue then Exit(); fTextWidth := aValue; fTextWidthChanged := True; //Log.Write(lCritical, 'Text.SetTextWidth is not implemented'); end; constructor TglrText.Create(const aText: WideString); begin inherited Create(); Text := aText; LineSpacing := 2.0; LetterSpacing := 0.0; Color := Vec4f(1, 1, 1, 1); Scale := 1.0; ShadowEnabled := False; ShadowOffset.Reset(); ShadowColor := Color4f(0, 0, 0, 0.5); PivotPoint.Reset(); fHorAlign := haLeft; fTextWidth := -1; fTextWidthChanged := False; end; destructor TglrText.Destroy; begin inherited Destroy; end; procedure TglrText.RenderSelf; begin end; { TglrFont } function TglrFont.GetCharQuad(aChar: WideChar; aScale: Single): TglrQuadP3T2C4; begin FillChar(Result[0], SizeOf(TglrVertexP3T2C4) * 4, 0); if Table[aChar] = nil then Exit(); with Table[aChar]^ do begin Result[0].vec := Vec3f(w, py + h, 0) * aScale; Result[1].vec := Vec3f(w, py, 0) * aScale; Result[2].vec := Vec3f(0, py, 0) * aScale; Result[3].vec := Vec3f(0, py + h, 0) * aScale; Result[0].tex := Vec2f(tx + tw, ty + th); Result[1].tex := Vec2f(tx + tw, ty); Result[2].tex := Vec2f(tx, ty); Result[3].tex := Vec2f(tx, ty + th); end; end; constructor TglrFont.Create; begin inherited Create(); if not Default.Inited then Log.Write(lCritical, 'Font: Can not create default font - default assets are disabled'); Create(FileSystem.ReadResource('default assets/default.fnt')); end; constructor TglrFont.Create(aStream: TglrStream; aFreeStreamOnFinish: Boolean); var shader: TglrShaderProgram; begin if Default.Inited then shader := Default.SpriteShader else shader := nil; Create(aStream, shader, aFreeStreamOnFinish); end; constructor TglrFont.Create(aStream: TglrStream; aShader: TglrShaderProgram; aFreeStreamOnFinish: Boolean); function CreateTexture(Stream: TglrStream): TglrTexture; var Header : record Width : Word; Height : Word; Size : LongWord; end; packedData, unpackedData: PByte; i: Integer; begin Stream.Read(Header, SizeOf(Header)); unpackedData := GetMem(Header.Width * Header.Height * 4); FillChar(unpackedData^, Header.Width * Header.Height * 4, 255); packedData := GetMem(Header.Size); Stream.Read(packedData^, Header.Size); for i := 0 to Header.Width * Header.Height - 1 do (unpackedData + (i * 4 + 3))^ := (packedData + i)^; Result := TglrTexture.Create(unpackedData, Header.Width, Header.Height, tfRGBA8); FreeMem(packedData); FreeMem(unpackedData); end; var data: Pointer; charCount, i: LongWord; begin inherited Create(); Material := TglrMaterial.Create(aShader); Texture := CreateTexture(aStream); Material.AddTexture(Texture, 'uDiffuse'); data := LoadFontData(aStream, charCount); SetLength(Self.CharData, charCount); Move(data^, CharData[0], charCount * SizeOf(TglrCharData)); FreeMem(data); MaxCharHeight := 0; for i := 0 to charCount - 1 do begin Table[CharData[i].ID] := @CharData[i]; if CharData[i].h > MaxCharHeight then MaxCharHeight := CharData[i].h; end; if aFreeStreamOnFinish then aStream.Free(); end; destructor TglrFont.Destroy; begin Material.Free(); Texture.Free(); SetLength(CharData, 0); inherited Destroy; end; { TglrSpriteBatch } constructor TglrSpriteBatch.Create; begin inherited Create; fVB := TglrVertexBuffer.Create(nil, 65536, vfPos3Tex2Col4, uStreamDraw); fIB := TglrIndexBuffer.Create(nil, 65536, ifShort); end; destructor TglrSpriteBatch.Destroy; begin fVB.Free(); fIB.Free(); inherited Destroy; end; procedure TglrSpriteBatch.Start; begin fCount := 0; end; procedure TglrSpriteBatch.Draw(aSprite: TglrSprite); var i: Integer; begin if (aSprite.Visible) then begin for i := 0 to 3 do begin fVData[fCount * 4 + i] := aSprite.Vertices[i]; fVData[fCount * 4 + i].vec := aSprite.AbsoluteMatrix * fVData[fCount * 4 + i].vec; end; for i := 0 to 5 do fIData[fCount * 6 + i] := SpriteIndices[i] + fCount * 4; fCount += 1; end; end; procedure TglrSpriteBatch.Draw(aSprites: array of TglrSprite); var i: Integer; begin for i := 0 to Length(aSprites) - 1 do Draw(aSprites[i]); end; procedure TglrSpriteBatch.Draw(aSprites: TglrSpriteList); var i: Integer; begin for i := 0 to aSprites.Count - 1 do Draw(aSprites[i]); end; procedure TglrSpriteBatch.Finish; begin if fCount = 0 then Exit(); fVB.Update(@fVData[0], 0, fCount * 4); fIB.Update(@fIData[0], 0, fCount * 6); Render.Params.ModelViewProj := Render.Params.ViewProj; Render.DrawTriangles(fVB, fIB, 0, fCount * 6); // Nvidia threading optimization (TO) fails when you use // SpriteBatch several times per one frame, like // Start; Draw(); ... Finish(); // Start; Draw(); ... Finish(); // Nvidia with TO enabled will draw only last batch. // This is shit. // Note: suddenly removing of BindBuffer(0) after update helped... // I will save it here for next generations... end; { TglrFontBatch } function TglrFontBatch.GetTextOrigin(aText: TglrText): TglrVec2f; var i: Integer; maxWidth: Single; textSize: TglrVec2f; begin maxWidth := 0; textSize.Reset(); for i := 1 to Length(aText.Text) do if fFont.Table[aText.Text[i]] <> nil then with fFont.Table[aText.Text[i]]^ do begin // Setup text height on first visible character if (textSize.y < 1) and (h > 0) then textSize.y := fFont.MaxCharHeight + aText.LineSpacing; if ID = #10 then begin textSize.y += fFont.MaxCharHeight + aText.LineSpacing; if maxWidth > textSize.x then textSize.x := maxWidth; maxWidth := 0; continue; end; maxWidth += w + aText.LetterSpacing; end; textSize.x := Max(textSize.x, maxWidth); textSize := textSize * aText.Scale; Result.Reset(); Result := (-1 * textSize) * aText.PivotPoint; end; procedure TglrFontBatch.WordWrapText(aText: TglrText); var lastSpace: Integer; width: Single; i: Integer; begin lastSpace := 0; width := 0; i := 1; while (i <= Length(aText.Text)) do begin if fFont.Table[aText.Text[i]] = nil then continue; if (aText.Text[i] = #10) then aText.Text[i] := ' '; if (aText.Text[i] = ' ') then lastSpace := i; width += fFont.Table[aText.Text[i]].w * aText.Scale + aText.LetterSpacing; if (width > aText.TextWidth) and (lastSpace > 0) then begin aText.Text[lastSpace] := #10; i := lastSpace + 1; width := 0; lastSpace := 0; end else i += 1; end; end; procedure TglrFontBatch.DrawShadow(aText: TglrText); var initialPos: TglrVec3f; initialColor: TglrVec4f; begin initialPos := aText.Position; initialColor := aText.Color; aText.Position += Vec3f(aText.ShadowOffset, -1); aText.Color := aText.ShadowColor; aText.ShadowEnabled := False; // We don't need to go deeper :) Draw(aText); aText.Position := initialPos; aText.Color := initialColor; aText.ShadowEnabled := True; end; constructor TglrFontBatch.Create(aFont: TglrFont); begin inherited Create; if (aFont = nil) then Log.Write(lCritical, 'FontBatch: Null pointer provided, Font object expected'); fFont := aFont; fVB := TglrVertexBuffer.Create(nil, 65536, vfPos3Tex2Col4, uStreamDraw); fIB := TglrIndexBuffer.Create(nil, 65536, ifShort); end; destructor TglrFontBatch.Destroy; begin fVB.Free(); fIB.Free(); inherited Destroy; end; procedure TglrFontBatch.Start; begin fCount := 0; end; procedure TglrFontBatch.Draw(aText: TglrText); var origin, start: TglrVec2f; quad: TglrQuadP3T2C4; j, k: Integer; begin if (not aText.Visible) or (aText.Text = '') then Exit(); // Make a word wrap if (aText.TextWidth > 0) and (aText.fTextWidthChanged) then begin WordWrapText(aText); aText.fTextWidthChanged := False; end; if (aText.ShadowEnabled) then DrawShadow(aText); origin := GetTextOrigin(aText); start := origin; for j := 1 to Length(aText.Text) do begin if (aText.Text[j] = #10) then begin start.x := origin.x; start.y += (aText.LineSpacing + fFont.MaxCharHeight) * aText.Scale; continue; end; if fFont.Table[aText.Text[j]] = nil then continue; quad := fFont.GetCharQuad(aText.Text[j], aText.Scale); //Do not need it anymore - included in AbsoluteMatrix computing //child.Matrix.Pos := child.Position; for k := 0 to 3 do begin fVData[fCount * 4 + k] := quad[k]; fVData[fCount * 4 + k].vec += Vec3f(start, 0); fVData[fCount * 4 + k].vec := aText.AbsoluteMatrix * fVData[fCount * 4 + k].vec; fVData[fCount * 4 + k].col := aText.Color; end; for k := 0 to 5 do fIData[fCount * 6 + k] := SpriteIndices[k] + fCount * 4; start.x += quad[0].vec.x + aText.LetterSpacing; fCount += 1; end; end; procedure TglrFontBatch.Finish; begin if fCount = 0 then Exit(); fVB.Update(@fVData[0], 0, fCount * 4); fIB.Update(@fIData[0], 0, fCount * 6); Render.Params.ModelViewProj := Render.Params.ViewProj; fFont.Material.Bind(); Render.DrawTriangles(fVB, fIB, 0, 6 * fCount); end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMenuButton; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Windows, Messages, SysUtils, Classes, Controls, StdCtrls, Menus, Graphics; {$ELSE} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.Menus, Vcl.Graphics; {$ENDIF} type TclMenuButtonState = (stateNormal, statePushed, stateMenuDrop); TclMenuButton = class(TButton) private FArrowRect: TRect; FButtonRect: TRect; FMenu: TPopupMenu; FButtonState: TclMenuButtonState; FPrevButtonState: TclMenuButtonState; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure WMCancelMode(var Message: TWMCancelMode); message WM_CANCELMODE; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure WMKeyUp(var Message: TWMKeyUp); message WM_KEYUP; procedure WMKillFocus(var Message: TWMSetFocus); message WM_KILLFOCUS; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure CMChildKey(var Message: TCMChildKey); message CM_CHILDKEY; procedure SetButtonState(const Value: TclMenuButtonState); function ProcessMouseDown(Message: TWMMouse): Boolean; procedure DrawFocus(DC: HDC; rt: TRect); procedure DrawButtonText(DC: HDC; rt: TRect); procedure ShowMenu(); protected procedure CreateParams(var Params: TCreateParams); override; procedure SetButtonStyle(ADefault: Boolean); override; property ButtonState: TclMenuButtonState read FButtonState write SetButtonState; public constructor Create(AOwner: TComponent); override; function AddMenuItem(const ACaption: string; AClickEvent: TNotifyEvent): TMenuItem; published property PopupMenu: TPopupMenu read FMenu; end; implementation { TclMenuButton } constructor TclMenuButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FMenu := TPopupMenu.Create(Self); FButtonState := stateNormal; end; procedure TclMenuButton.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.style := (Params.style or BS_OWNERDRAW) and not BS_PUSHBUTTON; end; procedure TclMenuButton.SetButtonState(const Value: TclMenuButtonState); begin if(FButtonState <> Value) then begin FButtonState := Value; Invalidate(); end; end; procedure TclMenuButton.SetButtonStyle(ADefault: Boolean); begin end; procedure TclMenuButton.WMCancelMode(var Message: TWMCancelMode); begin if(GetCapture() = Self.Handle) then if csLButtonDown in ControlState then Perform(WM_LBUTTONUP, 0, Integer($FFFFFFFF)); inherited; end; procedure TclMenuButton.ShowMenu(); var p: TPoint; msg: TMsg; begin ButtonState := stateMenuDrop; p.X := Self.Left; p.Y := Self.Top + Self.Height; p := Parent.ClientToScreen(p); FMenu.Popup(p.X, p.Y); while(PeekMessage(msg, Self.Handle, WM_LBUTTONDOWN, WM_LBUTTONDBLCLK, PM_REMOVE)) do begin {Nothing} end; ButtonState := stateNormal; end; function TclMenuButton.ProcessMouseDown(Message: TWMMouse): Boolean; begin if(PtInRect(FArrowRect, Point(Message.XPos, Message.YPos))) then begin ShowMenu(); Result := True; end else begin SetCapture(Self.Handle); ButtonState := statePushed; FPrevButtonState := ButtonState; Result := False; end; end; procedure TclMenuButton.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin if(not ProcessMouseDown(Message)) then begin inherited; end; end; procedure TclMenuButton.WMLButtonDown(var Message: TWMLButtonDown); begin if(not ProcessMouseDown(Message)) then begin inherited; end; end; procedure TclMenuButton.WMLButtonUp(var Message: TWMLButtonUp); begin inherited; ButtonState := stateNormal; ReleaseCapture(); end; procedure TclMenuButton.WMMouseMove(var Message: TWMMouseMove); begin if(csLButtonDown in ControlState) and (GetCapture() = Self.Handle) then begin if(not PtInRect(ClientRect, Point(Message.XPos, Message.YPos))) then begin ButtonState := stateNormal; end else begin ButtonState := FPrevButtonState; end; end else inherited; end; procedure TclMenuButton.DrawFocus(DC: HDC; rt: TRect); var PrevBkColor, PrevTextColor: TColorRef; begin InflateRect(rt, -4, -4); PrevBkColor := SetBkColor(DC, clBlack); PrevTextColor := SetTextColor(DC, clWhite); DrawFocusRect(DC, rt); SetBkColor(DC, PrevBkColor); SetTextColor(DC, PrevTextColor); end; procedure TclMenuButton.DrawButtonText(DC: HDC; rt: TRect); var oldFont: HGDIOBJ; begin oldFont := SelectObject(DC, Font.Handle); SetBkMode(DC, TRANSPARENT); // SetTextColor(DC, Font.Color); OffsetRect(rt, 0, -1); if(ButtonState = statePushed) then begin OffsetRect(rt, 1, 1); end; DrawText(DC, PChar(Caption), -1, rt, DT_VCENTER or DT_CENTER or DT_SINGLELINE); SelectObject(DC, oldFont); end; procedure TclMenuButton.WMPaint(var Message: TWMPaint); const drawFlags: array[0..1, TclMenuButtonState] of Integer = ((DFCS_BUTTONPUSH, DFCS_BUTTONPUSH or DFCS_PUSHED, DFCS_BUTTONPUSH), (DFCS_SCROLLDOWN, DFCS_SCROLLDOWN or DFCS_PUSHED, DFCS_SCROLLDOWN or DFCS_PUSHED)); var rt: TRect; ps: PAINTSTRUCT; DC: HDC; begin DC := Message.DC; if (Message.DC = 0) then DC := BeginPaint(Handle, ps); try rt := FButtonRect; DrawFrameControl(DC, rt, DFC_BUTTON, drawFlags[0, FButtonState]); DrawButtonText(DC, rt); if(Focused and (ButtonState <> stateMenuDrop)) then begin DrawFocus(DC, rt); end; rt := FArrowRect; if(ButtonState = stateNormal) then begin rt.Top := rt.Top - 1; end; DrawFrameControl(DC, rt, DFC_SCROLL, drawFlags[1, FButtonState]); finally if (Message.DC = 0) then EndPaint(Handle, ps); end; end; procedure TclMenuButton.WMSize(var Message: TWMSize); begin inherited; FArrowRect.Left := Self.ClientWidth - GetSystemMetrics(SM_CXVSCROLL); FArrowRect.Top := 0; FArrowRect.Right := Self.ClientWidth; FArrowRect.Bottom := Self.ClientHeight; SubtractRect(FButtonRect, ClientRect, FArrowRect); end; procedure TclMenuButton.WMKeyDown(var Message: TWMKeyDown); begin case Message.CharCode of VK_SPACE: ButtonState := statePushed; end; inherited; end; procedure TclMenuButton.WMKeyUp(var Message: TWMKeyUp); begin ButtonState := stateNormal; inherited; end; procedure TclMenuButton.WMKillFocus(var Message: TWMSetFocus); begin if(ButtonState <> stateNormal) then begin ButtonState := stateNormal; end else begin Invalidate(); end; end; procedure TclMenuButton.WMSetFocus(var Message: TWMSetFocus); begin Invalidate(); end; procedure TclMenuButton.CMChildKey(var Message: TCMChildKey); begin if(Message.CharCode = VK_DOWN) and ((GetKeyState(VK_CONTROL) and $80000000) <> 0) then begin Message.Result := 1; ShowMenu(); end; end; function TclMenuButton.AddMenuItem(const ACaption: string; AClickEvent: TNotifyEvent): TMenuItem; begin Result := TMenuItem.Create(Self); PopupMenu.Items.Add(Result); Result.Caption := ACaption; Result.OnClick := AClickEvent; end; end.
unit Redactions_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Крылов М.А. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Document/Forms/Redactions_Form.pas" // Начат: 2003/06/20 06:51:14 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMFinalForm::Class>> F1 Работа с документом и списком документов::Document::View::Document::Document::Redactions // // Редакции // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Common_FormDefinitions_Controls, PrimRedactionsOptions_Form {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts {$If defined(Nemesis)} , nscTreeView {$IfEnd} //Nemesis , Classes {a}, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a}, vcmInterfaces {a}, vcmEntityForm {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TRedactionsForm = {final form} class(TvcmEntityFormRef, RedactionsFormDef) {* Редакции } Entities : TvcmEntities; end;//TRedactionsForm {$IfEnd} //not Admin AND not Monitorings implementation {$R *.DFM} {$If not defined(Admin) AND not defined(Monitorings)} uses SysUtils {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type Tkw_Form_Redactions = class(TtfwControlString) {* Слово словаря для идентификатора формы Redactions ---- *Пример использования*: [code] 'aControl' форма::Redactions TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_Redactions // start class Tkw_Form_Redactions {$If not defined(NoScripts)} function Tkw_Form_Redactions.GetString: AnsiString; {-} begin Result := 'RedactionsForm'; end;//Tkw_Form_Redactions.GetString {$IfEnd} //not NoScripts type Tkw_Redactions_RedactionTree_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола RedactionTree формы Redactions } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_Redactions_RedactionTree_ControlInstance // start class Tkw_Redactions_RedactionTree_ControlInstance {$If not defined(NoScripts)} procedure Tkw_Redactions_RedactionTree_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TRedactionsForm).RedactionTree); end;//Tkw_Redactions_RedactionTree_ControlInstance.DoDoIt {$IfEnd} //not NoScripts {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация фабрики формы Redactions fm_RedactionsForm.SetFactory(TRedactionsForm.Make); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Form_Redactions Tkw_Form_Redactions.Register('форма::Redactions', TRedactionsForm); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Redactions_RedactionTree_ControlInstance TtfwScriptEngine.GlobalAddWord('.TRedactionsForm.RedactionTree', Tkw_Redactions_RedactionTree_ControlInstance); {$IfEnd} //not Admin AND not Monitorings end.
unit FmTreeSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, VirtualTrees; type TFmVirtualTreeSearch = class(TForm) edtQuery: TLabeledEdit; lbNodes: TListBox; lblFindedNodes: TLabel; btnSearch: TButton; cbSelectFinded: TCheckBox; procedure btnSearchClick(Sender: TObject); procedure lbNodesDblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FTree: TVirtualStringTree; public procedure Search(Query: string); property Tree: TVirtualStringTree read FTree write FTree; end; var FmVirtualTreeSearch: TFmVirtualTreeSearch; implementation {$R *.dfm} { TFmVirtualTreeSearch } procedure TFmVirtualTreeSearch.btnSearchClick(Sender: TObject); begin Search(edtQuery.Text); end; procedure TFmVirtualTreeSearch.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFmVirtualTreeSearch.lbNodesDblClick(Sender: TObject); var Data: PVirtualNode; begin if lbNodes.ItemIndex <> -1 then begin Data := PVirtualNode(lbNodes.Items.Objects[lbNodes.ItemIndex]); FTree.Selected[Data] := True; FTree.Expanded[Data] := True; FTree.FocusedNode := Data; Close; end; end; procedure TFmVirtualTreeSearch.Search(Query: string); var Node: PVirtualNode; Finded: Boolean; begin if Query.IsEmpty or Trim(Query).IsEmpty or not Assigned (FTRee) then Exit; Finded := False; lbNodes.Clear; FTree.ClearSelection; for Node in FTree.Nodes do begin if ( Pos(AnsiUpperCase(Query), AnsiUpperCase(FTree.Text[Node, 0])) <> 0 ) or (Pos(AnsiUpperCase(Query), AnsiUpperCase(FTree.Text[Node, 1])) <> 0) then begin if cbSelectFinded.Checked then FTree.Selected[Node] := True; lbNodes.Items.AddObject('@'+IntToStr(Integer(Node))+': '+ FTree.Text[Node, 0] + ' ' + FTree.Text[Node, 1], TObject(Node)); Finded := True; end; end; if not Finded then ShowMessage('Не найдено'); end; end.
unit vcmToolbarMenuRes; // Модуль: "w:\common\components\gui\Garant\VCM\implementation\vcmToolbarMenuRes.pas" // Стереотип: "UtilityPack" // Элемент модели: "vcmToolbarMenuRes" MUID: (4B9777000394) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM)} uses l3IntfUses , l3StringIDEx , afwInterfaces , l3Interfaces ; const {* Локализуемые строки vcmIconSize } str_vcmgsAutomatic: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgsAutomatic'; rValue : 'Автоматически'); {* 'Автоматически' } str_vcmgs16x16: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs16x16'; rValue : 'Маленькие'); {* 'Маленькие' } str_vcmgs24x24: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs24x24'; rValue : 'Средние'); {* 'Средние' } str_vcmgs32x32: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs32x32'; rValue : 'Большие'); {* 'Большие' } type TvcmGlyphSize = ( vcm_gsAutomatic , vcm_gs16x16 , vcm_gs24x24 , vcm_gs32x32 );//TvcmGlyphSize vcmIconSizeMapHelper = {final} class {* Утилитный класс для преобразования значений vcmIconSizeMap } public class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): TvcmGlyphSize; {* Преобразование строкового значения к порядковому } end;//vcmIconSizeMapHelper const {* Карта преобразования локализованных строк vcmIconSize } vcmIconSizeMap: array [TvcmGlyphSize] of Pl3StringIDEx = ( @str_vcmgsAutomatic , @str_vcmgs16x16 , @str_vcmgs24x24 , @str_vcmgs32x32 ); {$IfEnd} // NOT Defined(NoVCM) implementation {$If NOT Defined(NoVCM)} uses l3ImplUses , l3MessageID , l3String , SysUtils //#UC START# *4B9777000394impl_uses* //#UC END# *4B9777000394impl_uses* ; class procedure vcmIconSizeMapHelper.FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } var l_Index: TvcmGlyphSize; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(vcmIconSizeMap[l_Index].AsCStr); end;//vcmIconSizeMapHelper.FillStrings class function vcmIconSizeMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): TvcmGlyphSize; {* Преобразование строкового значения к порядковому } var l_Index: TvcmGlyphSize; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, vcmIconSizeMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "vcmIconSizeMap"', [l3Str(aDisplayName)]); end;//vcmIconSizeMapHelper.DisplayNameToValue initialization str_vcmgsAutomatic.Init; {* Инициализация str_vcmgsAutomatic } str_vcmgs16x16.Init; {* Инициализация str_vcmgs16x16 } str_vcmgs24x24.Init; {* Инициализация str_vcmgs24x24 } str_vcmgs32x32.Init; {* Инициализация str_vcmgs32x32 } {$IfEnd} // NOT Defined(NoVCM) end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIX9Curve; {$I ..\Include\CryptoLib.inc} interface uses ClpIECInterface, ClpCryptoLibTypes, ClpIProxiedInterface; type IX9Curve = interface(IAsn1Encodable) ['{BD78E2A1-C079-461C-8962-C4834DFA1478}'] function GetCurve: IECCurve; function GetSeed(): TCryptoLibByteArray; property curve: IECCurve read GetCurve; end; implementation end.
unit calc; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AppEvnts, Unit2, Unit3, Unit4, Unit1; type TForm1 = class(TForm) Label1: TLabel; LabelUserName: TLabel; ApplicationEvents1: TApplicationEvents; procedure FormCreate(Sender: TObject); procedure CreateCalcForm(Sender: TObject); procedure CreateIMCCalcForm(Sender: TObject); procedure ShowLogForm(Sender: TObject); procedure ApplicationEvents1Exception(Sender: TObject; E: Exception); procedure ApplicationEvents1ActionExecute(Action: TBasicAction; var Handled: Boolean); procedure ApplicationEvents1ActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure ApplicationEvents1Activate(Sender: TObject); procedure ApplicationEvents1Deactivate(Sender: TObject); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } username: string; syslog: string; VAR_GLOBAL: TGlobalVar; end; var Form1: TForm1; syslog_list: TStringList; implementation {$R *.dfm} // Open query box to get user name function getUserNameBox() : string; var name: string; begin // Keep asking the user for their name repeat if not InputQuery('Test program', 'Please type your name', name) then ShowMessage('User cancelled the dialog'); until name <> ''; Result := name; end; // Create Calc Form procedure TForm1.CreateCalcForm(Sender: TObject); begin Application.CreateForm(TForm2, Form2); try VAR_GLOBAL.addLog('Open calc form'); Form2.VAR_GLOBAL := Self.VAR_GLOBAL; Form2.ShowModal(); finally Form2.Release; Form2 := nil; end; end; // Create IMC Calc Form procedure TForm1.CreateIMCCalcForm(Sender: TObject); begin Application.CreateForm(TForm3, Form3); try VAR_GLOBAL.addLog('Open IMC calc form'); Form3.VAR_GLOBAL := Self.VAR_GLOBAL; Form3.ShowModal(); finally Form3.Release; Form3 := nil; end; end; // Show Log Form procedure TForm1.ShowLogForm(Sender: TObject); begin Application.CreateForm(TForm4, Form4); try VAR_GLOBAL.addLog('Open log form'); Form4.VAR_GLOBAL := Self.VAR_GLOBAL; Form4.ShowModal(); finally Form4.Release; Form4 := nil; end; end; // Main form create procedure TForm1.FormCreate(Sender: TObject); var btn: TButton; result: integer; begin // New global variables VAR_GLOBAL := TGlobalVar.Create; // Get user name username := getUserNameBox(); VAR_GLOBAL.setUserName(username); VAR_GLOBAL.addLog('Usuário '+username+' acessou o sistema'); // Show their name Self.LabelUserName.Caption := 'Hello '+VAR_GLOBAL.getUserName+'!'; // Create calc button btn := TButton.Create(Self); btn.Parent := Self; btn.top := 10; btn.Left := 10; btn.Width := 273; btn.Height := 35; btn.Caption := 'Calculadora'; btn.OnClick := Form1.CreateCalcForm; // Create IMC Button btn := TButton.Create(Self); btn.Parent := Self; btn.top := btn.Height + 25; btn.Left := 10; btn.Width := 273; btn.Height := 35; btn.Caption := 'Calculadora IMC'; btn.OnClick := Form1.CreateIMCCalcForm; // Create Log Button btn := TButton.Create(Self); btn.Parent := Self; btn.top := btn.Height + 65; btn.Left := 10; btn.Width := 273; btn.Height := 35; btn.Caption := 'Show system log'; btn.OnClick := Form1.ShowLogForm; end; procedure TForm1.ApplicationEvents1Exception(Sender: TObject; E: Exception); begin ShowMessage('erro!'); end; procedure TForm1.ApplicationEvents1ActionExecute(Action: TBasicAction; var Handled: Boolean); begin //ShowMessage('ActionExe'); end; procedure TForm1.ApplicationEvents1ActionUpdate(Action: TBasicAction; var Handled: Boolean); begin //ShowMessage('ActUpdate'); end; procedure TForm1.ApplicationEvents1Activate(Sender: TObject); var index: integer; begin index:=0; //ShowMessage('On Active'); syslog := syslog+'On Active'+#13; end; procedure TForm1.ApplicationEvents1Deactivate(Sender: TObject); begin //ShowMessage('On Desa'); end; procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin //ShowMessage('on message'); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin VAR_GLOBAL.closeSystemLog; end; end.
unit m_dbgrid; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, DBGrids; type { TMariaeDBGrid } TMariaeDBGrid = class(TDBGrid) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public constructor Create(MOwner: TComponent); override; procedure EditingDone; override; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_dbgrid_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeDBGrid]); end; { TMariaeDBGrid } procedure TMariaeDBGrid.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; constructor TMariaeDBGrid.Create(MOwner: TComponent); begin inherited Create(MOwner); Self.FixedCols := 0; Self.ReadOnly := True; Self.Options := [dgTitles,dgIndicator,dgColumnResize,dgColumnMove,dgColLines,dgRowLines,dgAlwaysShowSelection,dgCancelOnExit,dgDblClickAutoSize,dgDisableDelete,dgDisableInsert,dgMultiselect,dgPersistentMultiSelect,dgRowSelect]; end; procedure TMariaeDBGrid.EditingDone; begin inherited EditingDone; Self.SetChanged(True); end; procedure TMariaeDBGrid.ResetChanged; begin Self.SetChanged(False); end; end.
unit pgResultSet; // Модуль: "w:\common\components\rtl\Garant\PG\pgResultSet.pas" // Стереотип: "SimpleClass" // Элемент модели: "TpgResultSet" MUID: (560B961401E4) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , l3ProtoObject , daInterfaces , LibPQ , daSelectFieldList , daFieldList , pgInterfaces , pgConnection , daParamList ; type TpgResultSet = class(Tl3ProtoObject, IdaResultSet, IdaResultBuffer) private f_Result: PPGresult; f_CurrentPos: LongInt; f_EOF: Boolean; f_FieldsDescription: TdaSelectFieldList; f_Fields: TdaFieldList; f_DataConverter: IpgDataConverter; protected procedure Next; function EOF: Boolean; function IsEmpty: Boolean; function Get_Field(const anAlias: AnsiString): IdaField; procedure RegisterField(const aField: IdaField); procedure UnregisterField(const aField: IdaField); function FieldBufferPtr(FieldIndex: Integer): Pointer; function CalcRecordCount: Integer; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aConnection: TpgConnection; const aDataConverter: IpgDataConverter; const aQueryName: AnsiString; aParams: TdaParamList; aSelectFields: TdaSelectFieldList; Unidirectional: Boolean); reintroduce; class function Make(aConnection: TpgConnection; const aDataConverter: IpgDataConverter; const aQueryName: AnsiString; aParams: TdaParamList; aSelectFields: TdaSelectFieldList; Unidirectional: Boolean): IdaResultSet; reintroduce; end;//TpgResultSet {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses , SysUtils , pgField , l3Types //#UC START# *560B961401E4impl_uses* //#UC END# *560B961401E4impl_uses* ; constructor TpgResultSet.Create(aConnection: TpgConnection; const aDataConverter: IpgDataConverter; const aQueryName: AnsiString; aParams: TdaParamList; aSelectFields: TdaSelectFieldList; Unidirectional: Boolean); //#UC START# *560B99890062_560B961401E4_var* var l_ParamsValue: array of AnsiString; l_ParamsValuePtr: TPQparamValues; l_IDX: Integer; //#UC END# *560B99890062_560B961401E4_var* begin //#UC START# *560B99890062_560B961401E4_impl* inherited Create; f_DataConverter := aDataConverter; f_Fields := TdaFieldList.Make; aSelectFields.SetRefTo(f_FieldsDescription); SetLength(l_ParamsValue, aParams.Count); SetLength(l_ParamsValuePtr, aParams.Count); for l_IDX := 0 to aParams.Count - 1 do begin l_ParamsValue[l_IDX] := aParams[l_IDX].AsString; l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]); end; f_Result := PQexecPrepared(aConnection.Handle, PAnsiChar(aQueryName), aParams.Count, l_ParamsValuePtr, nil, 0, 0); if not (PQresultStatus(f_Result) in [PGRES_EMPTY_QUERY, PGRES_COMMAND_OK, PGRES_TUPLES_OK]) then raise EpgError.Create(PQresultErrorMessage(f_Result)); if not IsEmpty then begin f_CurrentPos := 0; f_EOF := False; end else begin f_CurrentPos := -1; f_EOF := True; end; //#UC END# *560B99890062_560B961401E4_impl* end;//TpgResultSet.Create class function TpgResultSet.Make(aConnection: TpgConnection; const aDataConverter: IpgDataConverter; const aQueryName: AnsiString; aParams: TdaParamList; aSelectFields: TdaSelectFieldList; Unidirectional: Boolean): IdaResultSet; var l_Inst : TpgResultSet; begin l_Inst := Create(aConnection, aDataConverter, aQueryName, aParams, aSelectFields, Unidirectional); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TpgResultSet.Make procedure TpgResultSet.Next; //#UC START# *5549C44C037A_560B961401E4_var* //#UC END# *5549C44C037A_560B961401E4_var* begin //#UC START# *5549C44C037A_560B961401E4_impl* Inc(f_CurrentPos); if f_CurrentPos >= PQntuples(f_Result) then begin f_CurrentPos := PQntuples(f_Result) - 1; f_EOF := True; end else f_EOF := False; //#UC END# *5549C44C037A_560B961401E4_impl* end;//TpgResultSet.Next function TpgResultSet.EOF: Boolean; //#UC START# *5549C45A025C_560B961401E4_var* //#UC END# *5549C45A025C_560B961401E4_var* begin //#UC START# *5549C45A025C_560B961401E4_impl* Result := f_EOF; //#UC END# *5549C45A025C_560B961401E4_impl* end;//TpgResultSet.EOF function TpgResultSet.IsEmpty: Boolean; //#UC START# *558BF63203D7_560B961401E4_var* //#UC END# *558BF63203D7_560B961401E4_var* begin //#UC START# *558BF63203D7_560B961401E4_impl* Result := (PQresultStatus(f_Result) = PGRES_EMPTY_QUERY) or (PQntuples(f_Result) = 0); //#UC END# *558BF63203D7_560B961401E4_impl* end;//TpgResultSet.IsEmpty function TpgResultSet.Get_Field(const anAlias: AnsiString): IdaField; //#UC START# *5590FD57027D_560B961401E4get_var* var l_IDX: Integer; //#UC END# *5590FD57027D_560B961401E4get_var* begin //#UC START# *5590FD57027D_560B961401E4get_impl* if f_Fields.FindData(anAlias, l_IDX, l3_siUnsorted) then Result := f_Fields[l_IDX] else if f_FieldsDescription.FindData(anAlias, l_IDX) then Result := TpgField.Make(Self, f_DataConverter, f_FieldsDescription[l_IDX], l_IDX) else Result := nil; //#UC END# *5590FD57027D_560B961401E4get_impl* end;//TpgResultSet.Get_Field procedure TpgResultSet.RegisterField(const aField: IdaField); //#UC START# *55A63E22019B_560B961401E4_var* var l_Dummy: Integer; //#UC END# *55A63E22019B_560B961401E4_var* begin //#UC START# *55A63E22019B_560B961401E4_impl* Assert(f_Fields.FindData(aField, l_Dummy) = False); f_Fields.Add(aField); //#UC END# *55A63E22019B_560B961401E4_impl* end;//TpgResultSet.RegisterField procedure TpgResultSet.UnregisterField(const aField: IdaField); //#UC START# *55A63E3D0122_560B961401E4_var* //#UC END# *55A63E3D0122_560B961401E4_var* begin //#UC START# *55A63E3D0122_560B961401E4_impl* f_Fields.Remove(aField); //#UC END# *55A63E3D0122_560B961401E4_impl* end;//TpgResultSet.UnregisterField function TpgResultSet.FieldBufferPtr(FieldIndex: Integer): Pointer; //#UC START# *55C8996702B1_560B961401E4_var* //#UC END# *55C8996702B1_560B961401E4_var* begin //#UC START# *55C8996702B1_560B961401E4_impl* Result := PQgetvalue(f_Result, f_CurrentPos, FieldIndex); //#UC END# *55C8996702B1_560B961401E4_impl* end;//TpgResultSet.FieldBufferPtr function TpgResultSet.CalcRecordCount: Integer; //#UC START# *576278A800EA_560B961401E4_var* //#UC END# *576278A800EA_560B961401E4_var* begin //#UC START# *576278A800EA_560B961401E4_impl* Result := PQntuples(f_Result); //#UC END# *576278A800EA_560B961401E4_impl* end;//TpgResultSet.CalcRecordCount procedure TpgResultSet.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_560B961401E4_var* //#UC END# *479731C50290_560B961401E4_var* begin //#UC START# *479731C50290_560B961401E4_impl* FreeAndNil(f_Fields); PQclear(f_Result); f_DataConverter := nil; FreeAndNil(f_FieldsDescription); inherited; //#UC END# *479731C50290_560B961401E4_impl* end;//TpgResultSet.Cleanup {$IfEnd} // Defined(UsePostgres) end.
unit bprSync; interface {$ifndef FPC} uses Windows; {$else} {$mode delphi}{$h+} {$endif} type TBugReportCriticalSection = class(TObject) public constructor Create; virtual; abstract; procedure Lock; virtual; abstract; procedure Unlock; virtual; abstract; end; TBugReportCriticalSectionClass = class of TBugReportCriticalSection; procedure RegisterCSClass(AClass: TBugReportCriticalSectionClass); function CreateCS: TBugReportCriticalSection; //todo: //function GetCurrentThread: TThreadID; implementation var CSClass: TBugReportCriticalSectionClass = nil; type { TDefaultCriticalSection } TDefaultCriticalSection = class(TBugReportCriticalSection) private fcs : TRTLCriticalSection; public constructor Create; override; destructor Destroy; override; procedure Lock; override; procedure Unlock; override; end; {$ifndef FPC} procedure InitCriticalSection(var fcs: TRTLCriticalSection); begin InitializeCriticalSection(fcs); end; procedure DoneCriticalSection(var fcs: TRTLCriticalSection); begin DeleteCriticalsection(fcs); end; {$endif} { TDefaultCriticalSection } constructor TDefaultCriticalSection.Create; begin InitCriticalSection(fcs); end; destructor TDefaultCriticalSection.Destroy; begin DoneCriticalsection(fcs); end; procedure TDefaultCriticalSection.Lock; begin EnterCriticalsection(fcs); end; procedure TDefaultCriticalSection.Unlock; begin LeaveCriticalsection(fcs); end; procedure RegisterCSClass(AClass: TBugReportCriticalSectionClass); begin if Assigned(AClass) then CSClass:=AClass else CSClass:=TDefaultCriticalSection; end; function CreateCS: TBugReportCriticalSection; begin Result:=CSClass.Create; end; initialization CSClass := TDefaultCriticalSection; end.
unit Keras.PreProcessing; interface uses System.SysUtils, System.Generics.Collections, PythonEngine, Keras,Models,Python.Utils, Keras.Layers; type TSequenceUtil = class(TBase) public caller : TPythonObject; constructor Create; function PadSequences(sequences : TNDarray ; maxlen : PInteger = nil; dtype : string = 'int32'; padding : string = 'pre'; truncating: string = 'pre'; value : Double= 0): TNDArray; function SkipGrams(sequence : TNDarray; vocabulary_size : Integer; window_size : Integer= 4; negative_samples: Double= 1.0; shuffle : Boolean= true; categorical : Boolean= false; sampling_table : TNDArray= nil; seed : PInteger= nil): TNDArray; function MakeSamplingTable(size: Integer; sampling_factor : Double= 1e-05) : TNDArray; end; implementation uses System.Rtti; { TSequenceUtil } constructor TSequenceUtil.Create; begin inherited create; caller := GetKerasClassIstance('preprocessing.sequence'); end; function TSequenceUtil.MakeSamplingTable(size: Integer; sampling_factor: Double): TNDArray; begin Parameters.Clear; Parameters.Add( TPair<String,TValue>.Create('size',size) ); Parameters.Add( TPair<String,TValue>.Create('sampling_factor',sampling_factor) ); Result := TNDArray.Create( InvokeStaticMethod(caller,'make_sampling_table',Parameters) ) end; function TSequenceUtil.PadSequences(sequences: TNDarray; maxlen: PInteger; dtype, padding, truncating: string; value: Double): TNDArray; begin Parameters.Clear; Parameters.Add( TPair<String,TValue>.Create('sequences',sequences) ); if maxlen <> nil then Parameters.Add( TPair<String,TValue>.Create('maxlen',maxlen^)) else Parameters.Add( TPair<String,TValue>.Create('maxlen', TPythonObject.None )); Parameters.Add( TPair<String,TValue>.Create('dtype',dtype) ); Parameters.Add( TPair<String,TValue>.Create('padding',padding) ); Parameters.Add( TPair<String,TValue>.Create('truncating',truncating) ); Parameters.Add( TPair<String,TValue>.Create('value',value) ); Result := TNDArray.Create( InvokeStaticMethod(caller,'pad_sequences',Parameters) ) end; function TSequenceUtil.SkipGrams(sequence: TNDarray; vocabulary_size, window_size: Integer; negative_samples: Double; shuffle, categorical: Boolean; sampling_table: TNDArray; seed: PInteger): TNDArray; begin Parameters.Clear; Parameters.Add( TPair<String,TValue>.Create('sequences',sequence) ); Parameters.Add( TPair<String,TValue>.Create('vocabulary_size',vocabulary_size) ); Parameters.Add( TPair<String,TValue>.Create('window_size',window_size) ); Parameters.Add( TPair<String,TValue>.Create('negative_samples',negative_samples) ); Parameters.Add( TPair<String,TValue>.Create('shuffle',shuffle) ); Parameters.Add( TPair<String,TValue>.Create('categorical',categorical) ); if sampling_table <> nil then Parameters.Add( TPair<String,TValue>.Create('sampling_table',sampling_table)) else Parameters.Add( TPair<String,TValue>.Create('sampling_table', TPythonObject.None )); if sampling_table <> nil then Parameters.Add( TPair<String,TValue>.Create('seed',seed^)) else Parameters.Add( TPair<String,TValue>.Create('seed', TPythonObject.None )); Result := TNDArray.Create( InvokeStaticMethod(caller,'skipgrams',Parameters) ) end; end.
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. } {$INCLUDE flcTCPTest.inc} {$IFDEF TCPCLIENT_TEST_TLS} {$DEFINE TCPCLIENT_TEST_TLS_WEB} {$ENDIF} unit flcTCPTest_ClientTLS; interface { } { Test } { } {$IFDEF TCPCLIENT_TEST_TLS} procedure Test; {$ENDIF} implementation {$IFDEF TCPCLIENT_TEST_TLS} uses SysUtils, flcTLSTransportTypes, flcTLSTransportConnection, flcTLSTransportClient, flcTCPConnection, flcTCPClient, flcTCPTest_Client; {$ENDIF} { } { Test } { } {$IFDEF TCPCLIENT_TEST_TLS} {$ASSERTIONS ON} {$IFDEF TCPCLIENT_TEST_TLS_WEB} const TLSWebTestHost = 'www.rfc.org'; // DHE_RSA_WITH_AES_256_CBC_SHA procedure Test_Client_TLS_Web( const TLSOptions: TTCPClientTLSOptions = []; const TLSClientOptions: TTCPClientTLSClientOptions = DefaultTLSClientOptions; const TLSVersionOptions: TTCPClientTLSVersionOptions = DefaultTLSClientVersionOptions; const TLSKeyExchangeOptions: TTCPClientTLSKeyExchangeOptions = DefaultTLSClientKeyExchangeOptions; const TLSCipherOptions: TTCPClientTLSCipherOptions = DefaultTLSClientCipherOptions; const TLSHashOptions: TTCPClientTLSHashOptions = DefaultTLSClientHashOptions ); var C : TF5TCPClient; I, L : Integer; S : RawByteString; A : TTCPClientTestObj; begin A := TTCPClientTestObj.Create; C := TF5TCPClient.Create(nil); try // init C.OnLog := A.ClientLog; C.TLSEnabled := True; C.TLSOptions := TLSOptions; C.TLSClientOptions := TLSClientOptions; C.TLSVersionOptions := TLSVersionOptions; C.TLSKeyExchangeOptions := TLSKeyExchangeOptions; C.TLSCipherOptions := TLSCipherOptions; C.TLSHashOptions := TLSHashOptions; C.LocalHost := '0.0.0.0'; C.Host := TLSWebTestHost; C.Port := '443'; // start C.Active := True; Assert(C.Active); // wait connect I := 0; repeat Sleep(1); Inc(I); until ( (C.State in [csReady, csClosed]) and (C.TLSClient.ConnectionState in [tlscoApplicationData, tlscoErrorBadProtocol, tlscoCancelled, tlscoClosed]) and (C.Connection.State = cnsConnected) ) or (I = 5000); Assert(C.State = csReady); Assert(C.Connection.State = cnsConnected); Assert(C.TLSClient.ConnectionState = tlscoApplicationData); // send S := 'GET / HTTP/1.1'#13#10 + 'Host: ' + TLSWebTestHost + #13#10 + 'Date: 11 Oct 2011 12:34:56 GMT'#13#10 + #13#10; C.Connection.Write(S[1], Length(S)); C.BlockingConnection.WaitForTransmitFin(5000); // read C.BlockingConnection.WaitForReceiveData(1, 5000); L := C.Connection.ReadBufferUsed; Assert(L > 0); SetLength(S, L); Assert(C.Connection.Read(S[1], L) = L); Assert(Copy(S, 1, 6) = 'HTTP/1'); // close C.BlockingConnection.Shutdown(2000, 2000, 5000); Assert(C.Connection.State = cnsClosed); // stop C.Active := False; Assert(not C.Active); finally C.Finalise; FreeAndNil(C); A.Free; end; end; procedure TestClientTLSWeb; begin //Test_Client_TLS_Web([ctoDisableTLS10, ctoDisableTLS11, ctoDisableTLS12]); // SSL 3 //Test_Client_TLS_Web([ctoDisableSSL3, ctoDisableTLS11, ctoDisableTLS12]); // TLS 1.0 //Test_Client_TLS_Web([ctoDisableSSL3, ctoDisableTLS10, ctoDisableTLS12]); // TLS 1.1 // TLS 1.2 {Test_Client_TLS_Web( DefaultTCPClientTLSOptions, DefaultTLSClientOptions, [tlsvoTLS12], DefaultTLSClientKeyExchangeOptions, DefaultTLSClientCipherOptions, DefaultTLSClientHashOptions);} // TLS 1.2 Test_Client_TLS_Web( DefaultTCPClientTLSOptions, DefaultTLSClientOptions, [tlsvoTLS12], [tlskeoDHE_RSA], DefaultTLSClientCipherOptions, DefaultTLSClientHashOptions); { Test_Client_TLS_Web( DefaultTCPClientTLSOptions, DefaultTLSClientOptions, [tlsvoTLS12], [tlskeoRSA], [tlsco3DES], DefaultTLSClientHashOptions); } //Test_Client_TLS_Web([]); end; {$ENDIF} procedure Test; begin {$IFDEF TCPCLIENT_TEST_TLS_WEB} TestClientTLSWeb; {$ENDIF} end; {$ENDIF} end.
unit UPedidoServiceImpl; interface uses UPedidoServiceIntf, UPizzaTamanhoEnum, UPizzaSaborEnum, UPedidoRepositoryIntf, UPedidoRetornoDTOImpl, UClienteServiceIntf; type TPedidoService = class(TInterfacedObject, IPedidoService) private FPedidoRepository: IPedidoRepository; FClienteService: IClienteService; function calcularValorPedido(const APizzaTamanho: TPizzaTamanhoEnum): Currency; function calcularTempoPreparo(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum): Integer; public function efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum; const ADocumentoCliente: String): TPedidoRetornoDTO; function consultarPedido(const ADocumentoCliente: String): TPedidoRetornoDTO; constructor Create; reintroduce; end; implementation uses UPedidoRepositoryImpl, System.SysUtils, UClienteServiceImpl, FireDAC.Comp.Client, System.TypInfo; { TPedidoService } function TPedidoService.calcularTempoPreparo(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum): Integer; begin Result := 15; case APizzaTamanho of enPequena: Result := 15; enMedia: Result := 20; enGrande: Result := 25; end; if (APizzaSabor = enPortuguesa) then Result := Result + 5; end; function TPedidoService.calcularValorPedido(const APizzaTamanho: TPizzaTamanhoEnum): Currency; begin Result := 20; case APizzaTamanho of enPequena: Result := 20; enMedia: Result := 30; enGrande: Result := 40; end; end; function TPedidoService.consultarPedido( const ADocumentoCliente: String): TPedidoRetornoDTO; var oFDQuery: TFDQuery; tamanho_pizza: TPizzaTamanhoEnum; sabor_pizza: TPizzaSaborEnum; begin try oFDQuery := TFDQuery.Create(nil); FPedidoRepository.consultarPedido(ADocumentoCliente, oFDQuery); if (oFDQuery.IsEmpty) then Result := nil else begin tamanho_pizza := TPizzaTamanhoEnum(GetEnumValue(TypeInfo(TPizzaTamanhoEnum), oFDQuery.FieldByName('tamanho_pizza').AsString)); sabor_pizza := TPizzaSaborEnum(GetEnumValue(TypeInfo(TPizzaSaborEnum), oFDQuery.FieldByName('sabor_pizza').AsString)); Result := TPedidoRetornoDTO.Create(tamanho_pizza ,sabor_pizza ,oFDQuery.FieldByName('vl_pedido').AsCurrency ,oFDQuery.FieldByName('nr_tempopedido').AsInteger); end; finally oFDQuery.Free; end; end; constructor TPedidoService.Create; begin inherited; FPedidoRepository := TPedidoRepository.Create; FClienteService := TClienteService.Create; end; function TPedidoService.efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum; const ADocumentoCliente: String) : TPedidoRetornoDTO; var oValorPedido: Currency; oTempoPreparo: Integer; oCodigoCliente: Integer; begin oValorPedido := calcularValorPedido(APizzaTamanho); oTempoPreparo := calcularTempoPreparo(APizzaTamanho, APizzaSabor); oCodigoCliente := FClienteService.adquirirCodigoCliente(ADocumentoCliente); FPedidoRepository.efetuarPedido(APizzaTamanho, APizzaSabor, oValorPedido, oTempoPreparo, oCodigoCliente); Result := TPedidoRetornoDTO.Create(APizzaTamanho, APizzaSabor, oValorPedido, oTempoPreparo); end; end.
unit ufrmGo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Winapi.ActiveX; type TDropFilesEvent = procedure(Sender: TObject; const FileNames: array of String) of object; TWndProcEvent = procedure(Sender: TObject; var AMsg: TMessage; var AHandled: Boolean) of object; // 兼容Lazarus的 TShowInTaskbar = ( stDefault, // use default rules for showing taskbar item stAlways, // always show taskbar item for the form stNever // never show taskbar item for the form ); TGoForm = class(TForm) private FOnDropFiles: TDropFilesEvent; FOnStyleChanged: TNotifyEvent; FOnWndProc: TWndProcEvent; FAllowDropFiles: Boolean; FShowInTaskBar: TShowInTaskbar; procedure SetAllowDropFiles(const Value: Boolean); procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; procedure CMStyleChanged(var Msg: TMessage); message CM_STYLECHANGED; function GetAllowDropFiles: Boolean; procedure SetShowInTaskBar(const Value: TShowInTaskbar); procedure UpdateShowInTaskBar; protected procedure InitializeNewForm; override; public constructor Create(AOwner: TComponent); override; procedure WndProc(var AMsg: TMessage); override; published property AllowDropFiles: Boolean read GetAllowDropFiles write SetAllowDropFiles; property OnDropFiles: TDropFilesEvent read FOnDropFiles write FOnDropFiles; property OnStyleChanged: TNotifyEvent read FOnStyleChanged write FOnStyleChanged; property OnWndProc: TWndProcEvent read FOnWndProc write FOnWndProc; property ShowInTaskBar: TShowInTaskbar read FShowInTaskBar write SetShowInTaskBar default stDefault; end; procedure LockInitScale; procedure UnLockInitScale; procedure SetInitScale(AValue: Boolean); implementation //{$R *.dfm} uses uComponents, Winapi.ShellAPI; var uLockObj: TObject; uInitScale: Boolean; procedure LockInitScale; begin System.TMonitor.Enter(uLockObj); end; procedure UnLockInitScale; begin System.TMonitor.Exit(uLockObj); end; procedure SetInitScale(AValue: Boolean); begin uInitScale := AValue; end; procedure Form_ScaleForPPI(AObj: TGoForm; ANewPPI: Integer); stdcall; begin AObj.ScaleForPPI(ANewPPI); end; procedure Form_ScaleControlsForDpi(AObj: TGoForm; ANewPPI: Integer); stdcall; begin AObj.ScaleControlsForDpi(ANewPPI); end; { TGoForm } procedure TGoForm.CMStyleChanged(var Msg: TMessage); begin inherited; // 修复样式造成的问题,如果设置了允许拖放,但实际窗口风格中已经不存在了,则 // 重新设置。 if FAllowDropFiles and not AllowDropFiles then AllowDropFiles := True; if Assigned(FOnStyleChanged) then FOnStyleChanged(Self); end; constructor TGoForm.Create(AOwner: TComponent); var LPPI: Integer; begin try // 这里需要屏蔽对资源查找的错误 inherited Create(AOwner); except end; if OldCreateOrder then DoCreate; // Create(AOwner, 0); if uInitScale and GetGlobalFormScaled then begin LPPI := Screen.PixelsPerInch; ClientWidth := MulDiv(ClientWidth, LPPI, 96); ClientHeight := MulDiv(ClientHeight, LPPI, 96); ScaleForPPI(LPPI); end; ControlStyle := ControlStyle + [csPaintBlackOpaqueOnGlass]; FShowInTaskBar := stDefault; end; function TGoForm.GetAllowDropFiles: Boolean; begin Result := (GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_ACCEPTFILES) <> 0; end; procedure TGoForm.InitializeNewForm; begin inherited InitializeNewForm; Self.ClientHeight := 321; Self.ClientWidth := 678; if GetGlobalFormScaled then Self.PixelsPerInch := 96 else Self.PixelsPerInch := Screen.PixelsPerInch; Scaled := False; end; procedure TGoForm.SetAllowDropFiles(const Value: Boolean); begin FAllowDropFiles := Value; if AllowDropFiles <> Value then DragAcceptFiles(Handle, Value); end; procedure TGoForm.SetShowInTaskBar(const Value: TShowInTaskbar); begin if FShowInTaskBar <> Value then begin FShowInTaskBar := Value; UpdateShowInTaskBar; end; end; procedure TGoForm.UpdateShowInTaskBar; function IsSetVal: Boolean; begin Result := (GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_ACCEPTFILES) <> 0; end; begin if (Assigned(Application) and (Application.MainForm = Self)) or (not HandleAllocated) or Assigned(Parent) or (FormStyle = fsMDIChild){ or not Showing} then Exit; if FShowInTaskBar = stAlways then begin if not IsSetVal then SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end else begin if IsSetVal then SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) and not WS_EX_APPWINDOW); end; end; procedure TGoForm.WMDropFiles(var Msg: TWMDropFiles); var LCount, I: Cardinal; LFileName: array[0..MAX_PATH-1] of Char; LFileNames: array of string; begin inherited; if Assigned(FOnDropFiles) then begin LCount := DragQueryFile(Msg.Drop, INFINITE, nil, 0); if LCount > 0 then begin SetLength(LFileNames, LCount); for I := 0 to LCount - 1 do begin FillChar(LFileName, SizeOf(LFileName), #0); DragQueryFile(Msg.Drop, I, LFileName, SizeOf(LFileName)); LFileNames[I] := string(LFileName); end; FOnDropFiles(Self, LFileNames); end; end; end; procedure TGoForm.WndProc(var AMsg: TMessage); var LHandled: Boolean; begin LHandled := True; if Assigned(FOnWndProc) then FOnWndProc(Self, AMsg, LHandled); if LHandled then inherited; end; exports Form_ScaleForPPI, Form_ScaleControlsForDpi; initialization uLockObj := TObject.Create; CoInitialize(nil); finalization CoUninitialize; uLockObj.Free; end.
unit UserParameterProviderUnit; interface uses SysUtils, UserParametersUnit; type IUserParameterProvider = interface ['{7B95CC9E-20C4-446E-BCC8-544D45AAA155}'] function GetParameters(Email: String): TUserParameters; end; TUserParameterProvider = class(TInterfacedObject, IUserParameterProvider) public function GetParameters(Email: String): TUserParameters; end; implementation uses EnumsUnit; function TUserParameterProvider.GetParameters(Email: String): TUserParameters; begin Randomize; Result := TUserParameters.Create; Result.HideRoutedAddresses := False; Result.PhoneNumber := '571-259-5939'; Result.Zip := '22102'; Result.Email := Email; Result.HideVisitedAddresses := False; Result.ReadonlyUser := False; Result.MemberType := TMemberType.mtSubAccountDispatcher; Result.DateOfBirth := '2010'; Result.FirstName := 'Clay'; Result.LastName := 'Abraham'; Result.Password := '123456'; Result.HideNonFutureRoutes := False; Result.ShowAllVehicles := False; Result.ShowAllDrivers := False; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { *********************************************************** } unit tfNumerics; {$I TFL.inc} {$IFDEF TFL_LIMB32} {$DEFINE LIMB32} {$ENDIF} interface uses SysUtils, tfLimbs, tfTypes, {$IFDEF TFL_DLL} tfImport {$ELSE} tfNumbers, tfMontMath {$ENDIF}; type BigCardinal = record private FNumber: IBigNumber; public procedure Free; function ToString: string; function ToHexString(Digits: Integer = 0; const Prefix: string = ''; TwoCompl: Boolean = False): string; function ToBytes: TBytes; class function TryParse(const S: string; var R: BigCardinal): Boolean; static; class function Parse(const S: string): BigCardinal; static; function GetSign: Integer; property Sign: Integer read GetSign; function GetHashCode: Integer; property HashCode: Integer read GetHashCode; class function Compare(const A, B: BigCardinal): Integer; overload; static; class function Compare(const A: BigCardinal; const B: TLimb): Integer; overload; static; class function Compare(const A: BigCardinal; const B: TIntLimb): Integer; overload; static; class function Compare(const A: BigCardinal; const B: TDLimb): Integer; overload; static; class function Compare(const A: BigCardinal; const B: TDIntLimb): Integer; overload; static; class function Equals(const A, B: BigCardinal): Boolean; overload; static; // class function Equals(const A: BigCardinal; const B: TLimb): Boolean; overload; static; // class function Equals(const A: BigCardinal; const B: TIntLimb): Boolean; overload; static; // class function Equals(const A: BigCardinal; const B: TDblLimb): Boolean; overload; static; // class function Equals(const A: BigCardinal; const B: TDblIntLimb): Boolean; overload; static; class function Pow(const Base: BigCardinal; Value: Cardinal): BigCardinal; overload; static; class function Sqr(const A: BigCardinal): BigCardinal; static; class function Sqrt(const A: BigCardinal): BigCardinal; overload; static; class function GCD(const A, B: BigCardinal): BigCardinal; overload; static; class function LCM(const A, B: BigCardinal): BigCardinal; overload; static; class function ModPow(const BaseValue, ExpValue, Modulo: BigCardinal): BigCardinal; static; class function ModInverse(const A, Modulo: BigCardinal): BigCardinal; overload; static; class function DivRem(const Dividend, Divisor: BigCardinal; var Remainder: BigCardinal): BigCardinal; overload; static; class function DivRem(const Dividend: BigCardinal; Divisor: TLimb; var Remainder: TLimb): BigCardinal; overload; static; class function DivRem(const Dividend: TLimb; Divisor: BigCardinal; var Remainder: TLimb): TLimb; overload; static; function CompareTo(const B: BigCardinal): Integer; overload; function CompareTo(const B: TLimb): Integer; overload; function CompareTo(const B: TIntLimb): Integer; overload; function CompareTo(const B: TDLimb): Integer; overload; function CompareTo(const B: TDIntLimb): Integer; overload; function EqualsTo(const B: BigCardinal): Boolean; overload; // function EqualsTo(const B: TLimb): Boolean; overload; // function EqualsTo(const B: TIntLimb): Boolean; overload; // function EqualsTo(const B: TDblLimb): Boolean; overload; // function EqualsTo(const B: TDblIntLimb): Boolean; overload; class operator Explicit(const Value: BigCardinal): TLimb; class operator Explicit(const Value: BigCardinal): TIntLimb; class operator Explicit(const Value: BigCardinal): TDLimb; class operator Explicit(const Value: BigCardinal): TDIntLimb; class operator Implicit(const Value: TLimb): BigCardinal; class operator Implicit(const Value: TDLimb): BigCardinal; class operator Explicit(const Value: TIntLimb): BigCardinal; class operator Explicit(const Value: TDIntLimb): BigCardinal; class operator Explicit(const Value: TBytes): BigCardinal; class operator Explicit(const Value: string): BigCardinal; class operator Equal(const A, B: BigCardinal): Boolean; class operator NotEqual(const A, B: BigCardinal): Boolean; class operator GreaterThan(const A, B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A, B: BigCardinal): Boolean; class operator LessThan(const A, B: BigCardinal): Boolean; class operator LessThanOrEqual(const A, B: BigCardinal): Boolean; class operator Add(const A, B: BigCardinal): BigCardinal; class operator Subtract(const A, B: BigCardinal): BigCardinal; class operator Multiply(const A, B: BigCardinal): BigCardinal; class operator IntDivide(const A, B: BigCardinal): BigCardinal; class operator Modulus(const A, B: BigCardinal): BigCardinal; class operator LeftShift(const A: BigCardinal; Shift: Cardinal): BigCardinal; class operator RightShift(const A: BigCardinal; Shift: Cardinal): BigCardinal; class operator BitwiseAnd(const A, B: BigCardinal): BigCardinal; class operator BitwiseOr(const A, B: BigCardinal): BigCardinal; class operator Equal(const A: BigCardinal; const B: TLimb): Boolean; class operator Equal(const A: TLimb; const B: BigCardinal): Boolean; class operator Equal(const A: BigCardinal; const B: TIntLimb): Boolean; class operator Equal(const A: TIntLimb; const B: BigCardinal): Boolean; class operator NotEqual(const A: BigCardinal; const B: TLimb): Boolean; class operator NotEqual(const A: TLimb; const B: BigCardinal): Boolean; class operator NotEqual(const A: BigCardinal; const B: TIntLimb): Boolean; class operator NotEqual(const A: TIntLimb; const B: BigCardinal): Boolean; class operator GreaterThan(const A: BigCardinal; const B: TLimb): Boolean; class operator GreaterThan(const A: TLimb; const B: BigCardinal): Boolean; class operator GreaterThan(const A: BigCardinal; const B: TIntLimb): Boolean; class operator GreaterThan(const A: TIntLimb; const B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A: BigCardinal; const B: TLimb): Boolean; class operator GreaterThanOrEqual(const A: TLimb; const B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A: BigCardinal; const B: TIntLimb): Boolean; class operator GreaterThanOrEqual(const A: TIntLimb; const B: BigCardinal): Boolean; class operator LessThan(const A: BigCardinal; const B: TLimb): Boolean; class operator LessThan(const A: TLimb; const B: BigCardinal): Boolean; class operator LessThan(const A: BigCardinal; const B: TIntLimb): Boolean; class operator LessThan(const A: TIntLimb; const B: BigCardinal): Boolean; class operator LessThanOrEqual(const A: BigCardinal; const B: TLimb): Boolean; class operator LessThanOrEqual(const A: TLimb; const B: BigCardinal): Boolean; class operator LessThanOrEqual(const A: BigCardinal; const B: TIntLimb): Boolean; class operator LessThanOrEqual(const A: TIntLimb; const B: BigCardinal): Boolean; class operator Equal(const A: BigCardinal; const B: TDLimb): Boolean; class operator Equal(const A: TDLimb; const B: BigCardinal): Boolean; class operator Equal(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator Equal(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator NotEqual(const A: BigCardinal; const B: TDLimb): Boolean; class operator NotEqual(const A: TDLimb; const B: BigCardinal): Boolean; class operator NotEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator NotEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator GreaterThan(const A: BigCardinal; const B: TDLimb): Boolean; class operator GreaterThan(const A: TDLimb; const B: BigCardinal): Boolean; class operator GreaterThan(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator GreaterThan(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A: BigCardinal; const B: TDLimb): Boolean; class operator GreaterThanOrEqual(const A: TDLimb; const B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator GreaterThanOrEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator LessThan(const A: BigCardinal; const B: TDLimb): Boolean; class operator LessThan(const A: TDLimb; const B: BigCardinal): Boolean; class operator LessThan(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator LessThan(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator LessThanOrEqual(const A: BigCardinal; const B: TDLimb): Boolean; class operator LessThanOrEqual(const A: TDLimb; const B: BigCardinal): Boolean; class operator LessThanOrEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; class operator LessThanOrEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; class operator Add(const A: BigCardinal; const B: TLimb): BigCardinal; class operator Add(const A: TLimb; const B: BigCardinal): BigCardinal; class operator Subtract(const A: BigCardinal; const B: TLimb): BigCardinal; class operator Subtract(const A: TLimb; const B: BigCardinal): Cardinal; class operator Multiply(const A: BigCardinal; const B: TLimb): BigCardinal; class operator Multiply(const A: TLimb; const B: BigCardinal): BigCardinal; class operator IntDivide(const A: BigCardinal; const B: TLimb): BigCardinal; class operator IntDivide(const A: TLimb; const B: BigCardinal): TLimb; class operator Modulus(const A: BigCardinal; const B: TLimb): TLimb; class operator Modulus(const A: TLimb; const B: BigCardinal): TLimb; // unary plus class operator Positive(const A: BigCardinal): BigCardinal; class function PowerOfTwo(APower: Cardinal): BigCardinal; static; function IsPowerOfTwo: Boolean; function Next: BigCardinal; function Prev: BigCardinal; end; BigInteger = record private FNumber: IBigNumber; public procedure Free; function ToString: string; function ToHexString(Digits: Integer = 0; const Prefix: string = ''; TwoCompl: Boolean = False): string; function ToBytes: TBytes; class function TryParse(const S: string; var R: BigInteger; TwoCompl: Boolean = False): Boolean; static; class function Parse(const S: string; TwoCompl: Boolean = False): BigInteger; static; function GetSign: Integer; property Sign: Integer read GetSign; function GetHashCode: Integer; property HashCode: Integer read GetHashCode; class function Compare(const A, B: BigInteger): Integer; overload; static; class function Compare(const A: BigInteger; const B: BigCardinal): Integer; overload; static; class function Compare(const A: BigCardinal; const B: BigInteger): Integer; overload; static; class function Compare(const A: BigInteger; const B: TLimb): Integer; overload; static; class function Compare(const A: BigInteger; const B: TIntLimb): Integer; overload; static; class function Compare(const A: BigInteger; const B: TDLimb): Integer; overload; static; class function Compare(const A: BigInteger; const B: TDIntLimb): Integer; overload; static; function CompareTo(const B: BigInteger): Integer; overload; function CompareTo(const B: BigCardinal): Integer; overload; function CompareTo(const B: TLimb): Integer; overload; function CompareTo(const B: TIntLimb): Integer; overload; function CompareTo(const B: TDLimb): Integer; overload; function CompareTo(const B: TDIntLimb): Integer; overload; class function Equals(const A, B: BigInteger): Boolean; overload; static; class function Equals(const A: BigInteger; const B: BigCardinal): Boolean; overload; static; class function Equals(const A: BigCardinal; const B: BigInteger): Boolean; overload; static; function EqualsTo(const B: BigInteger): Boolean; overload; function EqualsTo(const B: BigCardinal): Boolean; overload; class function Abs(const A: BigInteger): BigInteger; static; class function Pow(const Base: BigInteger; Value: Cardinal): BigInteger; overload; static; class function Sqr(const A: BigInteger): BigInteger; static; class function Sqrt(const A: BigInteger): BigInteger; static; class function GCD(const A, B: BigInteger): BigInteger; overload; static; class function EGCD(const A, B: BigInteger; var X, Y: BigInteger): BigInteger; static; class function LCM(const A, B: BigInteger): BigInteger; overload; static; class function ModPow(const BaseValue, ExpValue, Modulo: BigInteger): BigInteger; static; class function ModInverse(const A, Modulo: BigInteger): BigInteger; overload; static; // removed because lead to overload ambiguity with hardcoded constants // class function GCD(const A: BigInteger; const B: BigCardinal): BigInteger; overload; static; // class function GCD(const A: BigCardinal; const B: BigInteger): BigInteger; overload; static; // class function ModInverse(const A: BigInteger; const Modulo: BigCardinal): BigInteger; overload; static; // class function ModInverse(const A: BigCardinal; const Modulo: BigInteger): BigInteger; overload; static; class function DivRem(const Dividend, Divisor: BigInteger; var Remainder: BigInteger): BigInteger; overload; static; class operator Implicit(const Value: BigCardinal): BigInteger; inline; class operator Explicit(const Value: BigInteger): BigCardinal; inline; class operator Explicit(const Value: BigInteger): TLimb; class operator Explicit(const Value: BigInteger): TDLimb; class operator Explicit(const Value: BigInteger): TIntLimb; class operator Explicit(const Value: BigInteger): TDIntLimb; class operator Implicit(const Value: TLimb): BigInteger; class operator Implicit(const Value: TDLimb): BigInteger; class operator Implicit(const Value: TIntLimb): BigInteger; class operator Implicit(const Value: TDIntLimb): BigInteger; class operator Explicit(const Value: TBytes): BigInteger; class operator Explicit(const Value: string): BigInteger; class operator Equal(const A, B: BigInteger): Boolean; class operator Equal(const A: BigInteger; const B: BigCardinal): Boolean; class operator Equal(const A: BigCardinal; const B: BigInteger): Boolean; class operator NotEqual(const A, B: BigInteger): Boolean; class operator NotEqual(const A: BigInteger; const B: BigCardinal): Boolean; class operator NotEqual(const A: BigCardinal; const B: BigInteger): Boolean; class operator GreaterThan(const A, B: BigInteger): Boolean; class operator GreaterThan(const A: BigInteger; const B: BigCardinal): Boolean; class operator GreaterThan(const A: BigCardinal; const B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A, B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; class operator GreaterThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; class operator LessThan(const A, B: BigInteger): Boolean; class operator LessThan(const A: BigInteger; const B: BigCardinal): Boolean; class operator LessThan(const A: BigCardinal; const B: BigInteger): Boolean; class operator LessThanOrEqual(const A, B: BigInteger): Boolean; class operator LessThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; class operator LessThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; class operator Add(const A, B: BigInteger): BigInteger; class operator Subtract(const A, B: BigInteger): BigInteger; class operator Multiply(const A, B: BigInteger): BigInteger; class operator IntDivide(const A, B: BigInteger): BigInteger; class operator Modulus(const A, B: BigInteger): BigInteger; class operator LeftShift(const A: BigInteger; Shift: Cardinal): BigInteger; class operator RightShift(const A: BigInteger; Shift: Cardinal): BigInteger; class operator BitwiseAnd(const A, B: BigInteger): BigInteger; class operator BitwiseOr(const A, B: BigInteger): BigInteger; class operator BitwiseXor(const A, B: BigInteger): BigInteger; class operator Equal(const A: BigInteger; const B: TLimb): Boolean; class operator Equal(const A: TLimb; const B: BigInteger): Boolean; class operator Equal(const A: BigInteger; const B: TIntLimb): Boolean; class operator Equal(const A: TIntLimb; const B: BigInteger): Boolean; class operator NotEqual(const A: BigInteger; const B: TLimb): Boolean; class operator NotEqual(const A: TLimb; const B: BigInteger): Boolean; class operator NotEqual(const A: BigInteger; const B: TIntLimb): Boolean; class operator NotEqual(const A: TIntLimb; const B: BigInteger): Boolean; class operator GreaterThan(const A: BigInteger; const B: TLimb): Boolean; class operator GreaterThan(const A: TLimb; const B: BigInteger): Boolean; class operator GreaterThan(const A: BigInteger; const B: TIntLimb): Boolean; class operator GreaterThan(const A: TIntLimb; const B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A: BigInteger; const B: TLimb): Boolean; class operator GreaterThanOrEqual(const A: TLimb; const B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A: BigInteger; const B: TIntLimb): Boolean; class operator GreaterThanOrEqual(const A: TIntLimb; const B: BigInteger): Boolean; class operator LessThan(const A: BigInteger; const B: TLimb): Boolean; class operator LessThan(const A: TLimb; const B: BigInteger): Boolean; class operator LessThan(const A: BigInteger; const B: TIntLimb): Boolean; class operator LessThan(const A: TIntLimb; const B: BigInteger): Boolean; class operator LessThanOrEqual(const A: BigInteger; const B: TLimb): Boolean; class operator LessThanOrEqual(const A: TLimb; const B: BigInteger): Boolean; class operator LessThanOrEqual(const A: BigInteger; const B: TIntLimb): Boolean; class operator LessThanOrEqual(const A: TIntLimb; const B: BigInteger): Boolean; class operator Equal(const A: BigInteger; const B: TDLimb): Boolean; class operator Equal(const A: TDLimb; const B: BigInteger): Boolean; class operator Equal(const A: BigInteger; const B: TDIntLimb): Boolean; class operator Equal(const A: TDIntLimb; const B: BigInteger): Boolean; class operator NotEqual(const A: BigInteger; const B: TDLimb): Boolean; class operator NotEqual(const A: TDLimb; const B: BigInteger): Boolean; class operator NotEqual(const A: BigInteger; const B: TDIntLimb): Boolean; class operator NotEqual(const A: TDIntLimb; const B: BigInteger): Boolean; class operator GreaterThan(const A: BigInteger; const B: TDLimb): Boolean; class operator GreaterThan(const A: TDLimb; const B: BigInteger): Boolean; class operator GreaterThan(const A: BigInteger; const B: TDIntLimb): Boolean; class operator GreaterThan(const A: TDIntLimb; const B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A: BigInteger; const B: TDLimb): Boolean; class operator GreaterThanOrEqual(const A: TDLimb; const B: BigInteger): Boolean; class operator GreaterThanOrEqual(const A: BigInteger; const B: TDIntLimb): Boolean; class operator GreaterThanOrEqual(const A: TDIntLimb; const B: BigInteger): Boolean; class operator LessThan(const A: BigInteger; const B: TDLimb): Boolean; class operator LessThan(const A: TDLimb; const B: BigInteger): Boolean; class operator LessThan(const A: BigInteger; const B: TDIntLimb): Boolean; class operator LessThan(const A: TDIntLimb; const B: BigInteger): Boolean; class operator LessThanOrEqual(const A: BigInteger; const B: TDLimb): Boolean; class operator LessThanOrEqual(const A: TDLimb; const B: BigInteger): Boolean; class operator LessThanOrEqual(const A: BigInteger; const B: TDIntLimb): Boolean; class operator LessThanOrEqual(const A: TDIntLimb; const B: BigInteger): Boolean; // arithmetic operations on BigInteger & TLimb class operator Add(const A: BigInteger; const B: TLimb): BigInteger; class operator Subtract(const A: BigInteger; const B: TLimb): BigInteger; class operator Multiply(const A: BigInteger; const B: TLimb): BigInteger; class operator IntDivide(const A: BigInteger; const B: TLimb): BigInteger; class operator Modulus(const A: BigInteger; const B: TLimb): BigInteger; class function DivRem(const Dividend: BigInteger; const Divisor: TLimb; var Remainder: BigInteger): BigInteger; overload; static; // arithmetic operations on TLimb & BigInteger class operator Add(const A: TLimb; const B: BigInteger): BigInteger; class operator Subtract(const A: TLimb; const B: BigInteger): BigInteger; class operator Multiply(const A: TLimb; const B: BigInteger): BigInteger; class operator IntDivide(const A: TLimb; const B: BigInteger): BigInteger; class operator Modulus(const A: TLimb; const B: BigInteger): TLimb; class function DivRem(const Dividend: TLimb; const Divisor: BigInteger; var Remainder: TLimb): BigInteger; overload; static; // arithmetic operations on BigInteger & TIntLimb class operator Add(const A: BigInteger; const B: TIntLimb): BigInteger; class operator Subtract(const A: BigInteger; const B: TIntLimb): BigInteger; class operator Multiply(const A: BigInteger; const B: TIntLimb): BigInteger; class operator IntDivide(const A: BigInteger; const B: TIntLimb): BigInteger; class operator Modulus(const A: BigInteger; const B: TIntLimb): TIntLimb; class function DivRem(const Dividend: BigInteger; const Divisor: TIntLimb; var Remainder: TIntLimb): BigInteger; overload; static; // arithmetic operations on TIntLimb & BigInteger class operator Add(const A: TIntLimb; const B: BigInteger): BigInteger; class operator Subtract(const A: TIntLimb; const B: BigInteger): BigInteger; class operator Multiply(const A: TIntLimb; const B: BigInteger): BigInteger; class operator IntDivide(const A: TIntLimb; const B: BigInteger): TIntLimb; class operator Modulus(const A: TIntLimb; const B: BigInteger): TIntLimb; class function DivRem(const Dividend: TIntLimb; const Divisor: BigInteger; var Remainder: TIntLimb): TIntLimb; overload; static; // unary minus/plus class operator Negative(const A: BigInteger): BigInteger; class operator Positive(const A: BigInteger): BigInteger; function Next: BigInteger; function Prev: BigInteger; class function PowerOfTwo(APower: Cardinal): BigInteger; static; function IsPowerOfTwo: Boolean; function IsEven: Boolean; // -- mutating methods will NOT be supported in user classes // procedure SelfAdd(const A: BigInteger); overload; // procedure SelfAdd(const A: TLimb); overload; // procedure SelfAdd(const A: TIntLimb); overload; // procedure SelfSub(const A: BigInteger); overload; // procedure SelfSub(const A: TLimb); overload; // procedure SelfSub(const A: TIntLimb); overload; end; type TMont = record private FInstance: IMont; public class function GetInstance(const Modulus: BigInteger): TMont; static; procedure Free; function IsAssigned: Boolean; procedure Burn; function Reduce(const A: BigInteger): BigInteger; function Convert(const A: BigInteger): BigInteger; function Add(const A, B: BigInteger): BigInteger; function Subtract(const A, B: BigInteger): BigInteger; function Multiply(const A, B: BigInteger): BigInteger; function ModMul(const A, B: BigInteger): BigInteger; function ModPow(const Base, Pow: BigInteger): BigInteger; overload; function ModPow(const Base: BigInteger; Pow: TLimb): BigInteger; overload; function GetRModulus: BigInteger; end; type EBigNumberError = class(Exception) private FCode: TF_RESULT; public constructor Create(ACode: TF_RESULT; const Msg: string = ''); property Code: TF_RESULT read FCode; end; procedure BigNumberError(ACode: TF_RESULT; const Msg: string = ''); implementation { EBigNumberError } constructor EBigNumberError.Create(ACode: TF_RESULT; const Msg: string); begin if Msg = '' then inherited Create(Format('Big Number Error 0x%.8x', [ACode])) else inherited Create(Msg); FCode:= ACode; end; procedure BigNumberError(ACode: TF_RESULT; const Msg: string); begin raise EBigNumberError.Create(ACode, Msg); end; procedure HResCheck(Value: TF_RESULT); inline; begin if Value <> TF_S_OK then BigNumberError(Value); end; {----------------------- Compare Inlines ----------------------} function Compare_BigCard_BigCard(const A, B: BigCardinal): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareNumberU(B.FNumber); {$ELSE} Result:= TBigNumber.CompareNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Compare_BigInt_BigInt(const A, B: BigInteger): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareNumber(B.FNumber); {$ELSE} Result:= TBigNumber.CompareNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Compare_BigInt_BigCard(const A: BigInteger; const B: BigCardinal): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareNumber(B.FNumber); {$ELSE} Result:= TBigNumber.CompareNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Compare_BigCard_BigInt(const A: BigCardinal; const B: BigInteger): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareNumber(B.FNumber); {$ELSE} Result:= TBigNumber.CompareNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Compare_BigCard_Limb(const A: BigCardinal; const B: TLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToLimbU(B); {$ELSE} Result:= TBigNumber.CompareToLimbU(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigCard_IntLimb(const A: BigCardinal; const B: TIntLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToIntLimbU(B); {$ELSE} Result:= TBigNumber.CompareToIntLimbU(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigCard_DblLimb(const A: BigCardinal; const B: TDLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToDblLimbU(B); {$ELSE} Result:= TBigNumber.CompareToDblLimbU(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigCard_DblIntLimb(const A: BigCardinal; const B: TDIntLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToDblIntLimbU(B); {$ELSE} Result:= TBigNumber.CompareToDblIntLimbU(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigInt_Limb(const A: BigInteger; const B: TLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToLimb(B); {$ELSE} Result:= TBigNumber.CompareToLimb(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigInt_IntLimb(const A: BigInteger; const B: TIntLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToIntLimb(B); {$ELSE} Result:= TBigNumber.CompareToIntLimb(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigInt_DblLimb(const A: BigInteger; const B: TDLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToDblLimb(B); {$ELSE} Result:= TBigNumber.CompareToDblLimb(PBigNumber(A.FNumber), B); {$ENDIF} end; function Compare_BigInt_DblIntLimb(const A: BigInteger; const B: TDIntLimb): Integer; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.CompareToDblIntLimb(B); {$ELSE} Result:= TBigNumber.CompareToDblIntLimb(PBigNumber(A.FNumber), B); {$ENDIF} end; {------------------------ Equal Inlines -----------------------} function Equal_BigCard_BigCard(const A, B: BigCardinal): Boolean; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.EqualsNumberU(B.FNumber); {$ELSE} Result:= TBigNumber.EqualNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Equal_BigInt_BigInt(const A, B: BigInteger): Boolean; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.EqualsNumber(B.FNumber); {$ELSE} Result:= TBigNumber.EqualNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Equal_BigInt_BigCard(const A: BigInteger; const B: BigCardinal): Boolean; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.EqualsNumber(B.FNumber); {$ELSE} Result:= TBigNumber.EqualNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Equal_BigCard_BigInt(const A: BigCardinal; const B: BigInteger): Boolean; inline; begin {$IFDEF TFL_INTFCALL} Result:= A.FNumber.EqualsNumber(B.FNumber); {$ELSE} Result:= TBigNumber.EqualNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber)); {$ENDIF} end; function Equal_BigCard_Limb(const A: BigCardinal; const B: TLimb): Boolean; inline; begin Result:= Compare_BigCard_Limb(A, B) = 0; end; function Equal_BigCard_IntLimb(const A: BigCardinal; const B: TIntLimb): Boolean; inline; begin Result:= Compare_BigCard_IntLimb(A, B) = 0; end; function Equal_BigCard_DblLimb(const A: BigCardinal; const B: TDLimb): Boolean; inline; begin Result:= Compare_BigCard_DblLimb(A, B) = 0; end; function Equal_BigCard_DblIntLimb(const A: BigCardinal; const B: TDIntLimb): Boolean; inline; begin Result:= Compare_BigCard_DblIntLimb(A, B) = 0; end; function Equal_BigInt_Limb(const A: BigInteger; const B: TLimb): Boolean; inline; begin Result:= Compare_BigInt_Limb(A, B) = 0; end; function Equal_BigInt_IntLimb(const A: BigInteger; const B: TIntLimb): Boolean; inline; begin Result:= Compare_BigInt_IntLimb(A, B) = 0; end; function Equal_BigInt_DblLimb(const A: BigInteger; const B: TDLimb): Boolean; inline; begin Result:= Compare_BigInt_DblLimb(A, B) = 0; end; function Equal_BigInt_DblIntLimb(const A: BigInteger; const B: TDIntLimb): Boolean; inline; begin Result:= Compare_BigInt_DblIntLimb(A, B) = 0; end; { BigCardinal } function BigCardinal.ToString: string; var BytesUsed: Integer; L: Integer; P, P1: PByte; I: Integer; begin {$IFDEF TFL_INTFCALL} BytesUsed:= FNumber.GetSize; {$ELSE} BytesUsed:= TBigNumber.GetSize(PBigNumber(FNumber)); {$ENDIF} // log(256) approximated from above by 41/17 L:= (BytesUsed * 41) div 17 + 1; GetMem(P, L); try {$IFDEF TFL_INTFCALL} HResCheck(FNumber.ToDec(P, L)); {$ELSE} HResCheck(TBigNumber.ToDec(PBigNumber(FNumber), P, L)); {$ENDIF} Result:= ''; SetLength(Result, L); P1:= P; for I:= 1 to L do begin Result[I]:= Char(P1^); Inc(P1); end; finally FreeMem(P); end; end; function BigCardinal.ToHexString(Digits: Integer; const Prefix: string; TwoCompl: Boolean): string; var L: Integer; P, P1: PByte; HR: TF_RESULT; I: Integer; begin HR:= FNumber.ToHex(nil, L, TwoCompl); if HR = TF_E_INVALIDARG then begin GetMem(P, L); try {$IFDEF TFL_INTFCALL} HResCheck(FNumber.ToHex(P, L, TwoCompl)); {$ELSE} HResCheck(TBigNumber.ToHex(PBigNumber(FNumber), P, L, TwoCompl)); {$ENDIF} if Digits < L then Digits:= L; Inc(Digits, Length(Prefix)); Result:= ''; SetLength(Result, Digits); Move(Pointer(Prefix)^, Pointer(Result)^, Length(Prefix) * SizeOf(Char)); P1:= P; I:= Length(Prefix); while I + L < Digits do begin Inc(I); Result[I]:= '0'; end; while I < Digits do begin Inc(I); Result[I]:= Char(P1^); Inc(P1); end; finally FreeMem(P); end; end else BigNumberError(HR); end; function BigCardinal.ToBytes: TBytes; var HR: TF_RESULT; L: Cardinal; begin L:= 0; HR:= FNumber.ToPByte(nil, L); if (HR = TF_E_INVALIDARG) and (L > 0) then begin Result:= nil; SetLength(Result, L); {$IFDEF TFL_INTFCALL} HR:= FNumber.ToPByte(Pointer(Result), L); {$ELSE} HR:= TBigNumber.ToPByte(PBigNumber(FNumber), Pointer(Result), L); {$ENDIF} end; HResCheck(HR); end; class function BigCardinal.Parse(const S: string): BigCardinal; begin {$IFDEF TFL_DLL} HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(S), Length(S), SizeOf(Char), False, False)); {$ELSE} HResCheck(BigNumberFromPChar(PBigNumber(Result.FNumber), Pointer(S), Length(S), SizeOf(Char), False, False)); {$ENDIF} end; class function BigCardinal.TryParse(const S: string; var R: BigCardinal): Boolean; begin {$IFDEF TFL_DLL} Result:= BigNumberFromPChar(R.FNumber, Pointer(S), Length(S), SizeOf(Char), False, False) = TF_S_OK; {$ELSE} Result:= BigNumberFromPChar(PBigNumber(R.FNumber), Pointer(S), Length(S), SizeOf(Char), False, False) = TF_S_OK; {$ENDIF} end; function BigCardinal.GetHashCode: Integer; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetHashCode; {$ELSE} Result:= TBigNumber.GetHashCode(PBigNumber(FNumber)); {$ENDIF} end; function BigCardinal.GetSign: Integer; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetSign; {$ELSE} Result:= TBigNumber.GetSign(PBigNumber(FNumber)); {$ENDIF} end; function BigCardinal.CompareTo(const B: BigCardinal): Integer; begin Result:= Compare_BigCard_BigCard(Self, B); end; function BigCardinal.EqualsTo(const B: BigCardinal): Boolean; begin Result:= Equal_BigCard_BigCard(Self, B); end; class operator BigCardinal.Equal(const A, B: BigCardinal): Boolean; begin Result:= Equal_BigCard_BigCard(A, B); end; class operator BigCardinal.NotEqual(const A, B: BigCardinal): Boolean; begin Result:= not Equal_BigCard_BigCard(A, B); end; class operator BigCardinal.GreaterThan(const A, B: BigCardinal): Boolean; begin Result:= Compare_BigCard_BigCard(A, B) > 0; end; class operator BigCardinal.GreaterThanOrEqual(const A, B: BigCardinal): Boolean; begin Result:= Compare_BigCard_BigCard(A, B) >= 0; end; class operator BigCardinal.LessThan(const A, B: BigCardinal): Boolean; begin Result:= Compare_BigCard_BigCard(A, B) < 0; end; class operator BigCardinal.LessThanOrEqual(const A, B: BigCardinal): Boolean; begin Result:= Compare_BigCard_BigCard(A, B) <= 0; end; class function BigCardinal.LCM(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.LCM(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.LCM(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.LeftShift(const A: BigCardinal; Shift: Cardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ShlNumber(Shift, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ShlNumber(PBigNumber(A.FNumber), Shift, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.RightShift(const A: BigCardinal; Shift: Cardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ShrNumber(Shift, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ShrNumber(PBigNumber(A.FNumber), Shift, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: string): BigCardinal; begin {$IFDEF TFL_DLL} HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(Value), Length(Value), SizeOf(Char), False, False)); {$ELSE} HResCheck(BigNumberFromPChar(PBigNumber(Result.FNumber), Pointer(Value), Length(Value), SizeOf(Char), False, False)); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: TBytes): BigCardinal; begin HResCheck(BigNumberFromPByte( {$IFDEF TFL_DLL} Result.FNumber, {$ELSE} PBigNumber(Result.FNumber), {$ENDIF} Pointer(Value), Length(Value), False)); end; procedure BigCardinal.Free; begin FNumber:= nil; end; class operator BigCardinal.Explicit(const Value: BigCardinal): TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: BigCardinal): TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToIntLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToIntLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: BigCardinal): TDLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToDblLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToDblLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: BigCardinal): TDIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToDblIntLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToDblIntLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigCardinal.Explicit(const Value: TIntLimb): BigCardinal; begin if Value < 0 then BigNumberError(TF_E_INVALIDARG) else begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromIntLimb(Result.FNumber, TLimb(Value))); {$ELSE} HResCheck(BigNumberFromIntLimb(PBigNumber(Result.FNumber), TLimb(Value))); {$ENDIF} end; end; class operator BigCardinal.Explicit(const Value: TDIntLimb): BigCardinal; begin if Value < 0 then BigNumberError(TF_E_INVALIDARG) else begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromDblIntLimb(Result.FNumber, TDblLimb(Value))); {$ELSE} HResCheck(BigNumberFromDblIntLimb(PBigNumber(Result.FNumber), TDLimb(Value))); {$ENDIF} end; end; class operator BigCardinal.Implicit(const Value: TLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigCardinal.Implicit(const Value: TDLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromDblLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromDblLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigCardinal.BitwiseAnd(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AndNumberU(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AndNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.BitwiseOr(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.OrNumberU(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.OrNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Add(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AddNumberU(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Subtract(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SubNumberU(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Multiply(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.MulNumberU(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.IntDivide(const A, B: BigCardinal): BigCardinal; var Remainder: IBigNumber; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemNumberU(B.FNumber, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber), PBigNumber(Remainder))); {$ENDIF} end; class operator BigCardinal.Modulus(const A, B: BigCardinal): BigCardinal; var Quotient: IBigNumber; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemNumberU(B.FNumber, Quotient, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemNumbersU(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Quotient), PBigNumber(Result.FNumber))); {$ENDIF} end; function BigCardinal.CompareTo(const B: TLimb): Integer; begin Result:= Compare_BigCard_Limb(Self, B); end; function BigCardinal.CompareTo(const B: TIntLimb): Integer; begin Result:= Compare_BigCard_IntLimb(Self, B); end; function BigCardinal.CompareTo(const B: TDLimb): Integer; begin Result:= Compare_BigCard_DblLimb(Self, B); end; function BigCardinal.CompareTo(const B: TDIntLimb): Integer; begin Result:= Compare_BigCard_DblIntLimb(Self, B); end; class operator BigCardinal.Equal(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= Equal_BigCard_Limb(A, B); end; class operator BigCardinal.Equal(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= Equal_BigCard_Limb(B, A); end; class operator BigCardinal.Equal(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= Equal_BigCard_IntLimb(A, B); end; class operator BigCardinal.Equal(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= Equal_BigCard_IntLimb(B, A); end; class operator BigCardinal.NotEqual(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= not Equal_BigCard_Limb(A, B); end; class operator BigCardinal.NotEqual(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= not Equal_BigCard_Limb(B, A); end; class operator BigCardinal.NotEqual(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= not Equal_BigCard_IntLimb(A, B); end; class operator BigCardinal.NotEqual(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= not Equal_BigCard_IntLimb(B, A); end; class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= Compare_BigCard_Limb(A, B) > 0; end; class operator BigCardinal.GreaterThan(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_Limb(B, A) < 0; end; class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= Compare_BigCard_IntLimb(A, B) > 0; end; class operator BigCardinal.GreaterThan(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_IntLimb(B, A) < 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= Compare_BigCard_Limb(A, B) >= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_Limb(B, A) <= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= Compare_BigCard_IntLimb(A, B) >= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_IntLimb(B, A) <= 0; end; class operator BigCardinal.LessThan(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= Compare_BigCard_Limb(A, B) < 0; end; class operator BigCardinal.LessThan(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_Limb(B, A) > 0; end; class operator BigCardinal.LessThan(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= Compare_BigCard_IntLimb(A, B) < 0; end; class operator BigCardinal.LessThan(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_IntLimb(B, A) > 0; end; class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: TLimb): Boolean; begin Result:= Compare_BigCard_Limb(A, B) <= 0; end; class operator BigCardinal.LessThanOrEqual(const A: TLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_Limb(B, A) >= 0; end; class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: TIntLimb): Boolean; begin Result:= Compare_BigCard_IntLimb(A, B) <= 0; end; class operator BigCardinal.LessThanOrEqual(const A: TIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_IntLimb(B, A) >= 0; end; class operator BigCardinal.Equal(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= Equal_BigCard_DblLimb(A, B); end; class operator BigCardinal.Equal(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= Equal_BigCard_DblLimb(B, A); end; class operator BigCardinal.Equal(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= Equal_BigCard_DblIntLimb(A, B); end; class operator BigCardinal.Equal(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= Equal_BigCard_DblIntLimb(B, A); end; class operator BigCardinal.NotEqual(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= not Equal_BigCard_DblLimb(A, B); end; class operator BigCardinal.NotEqual(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= not Equal_BigCard_DblLimb(B, A); end; class operator BigCardinal.NotEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= not Equal_BigCard_DblIntLimb(A, B); end; function BigCardinal.Next: BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(FNumber.NextNumberU(Result.FNumber); {$ELSE} HResCheck(TBigNumber.NextNumberU(PBigNumber(FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.NotEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= not Equal_BigCard_DblIntLimb(B, A); end; class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= Compare_BigCard_DblLimb(A, B) > 0; end; class operator BigCardinal.GreaterThan(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblLimb(B, A) < 0; end; class operator BigCardinal.GreaterThan(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= Compare_BigCard_DblIntLimb(A, B) > 0; end; class operator BigCardinal.GreaterThan(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblIntLimb(B, A) < 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= Compare_BigCard_DblLimb(A, B) >= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblLimb(B, A) <= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= Compare_BigCard_DblIntLimb(A, B) >= 0; end; class operator BigCardinal.GreaterThanOrEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblIntLimb(B, A) <= 0; end; class operator BigCardinal.LessThan(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= Compare_BigCard_DblLimb(A, B) < 0; end; class operator BigCardinal.LessThan(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblLimb(B, A) > 0; end; class operator BigCardinal.LessThan(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= Compare_BigCard_DblIntLimb(A, B) < 0; end; class operator BigCardinal.LessThan(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblIntLimb(B, A) > 0; end; class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: TDLimb): Boolean; begin Result:= Compare_BigCard_DblLimb(A, B) <= 0; end; class operator BigCardinal.LessThanOrEqual(const A: TDLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblLimb(B, A) >= 0; end; class operator BigCardinal.LessThanOrEqual(const A: BigCardinal; const B: TDIntLimb): Boolean; begin Result:= Compare_BigCard_DblIntLimb(A, B) <= 0; end; class operator BigCardinal.LessThanOrEqual(const A: TDIntLimb; const B: BigCardinal): Boolean; begin Result:= Compare_BigCard_DblIntLimb(B, A) >= 0; end; class operator BigCardinal.Add(const A: BigCardinal; const B: TLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AddLimbU(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddLimbU(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Add(const A: TLimb; const B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.AddLimbU(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddLimbU(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Subtract(const A: BigCardinal; const B: TLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SubLimbU(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubLimbU(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Subtract(const A: TLimb; const B: BigCardinal): Cardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.SubLimbU2(A, Result)); {$ELSE} HResCheck(TBigNumber.SubLimbU2(PBigNumber(B.FNumber), A, Result)); {$ENDIF} end; class operator BigCardinal.Multiply(const A: BigCardinal; const B: TLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.MulLimbU(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulLimbU(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Multiply(const A: TLimb; const B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.MulLimbU(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulLimbU(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.IntDivide(const A: BigCardinal; const B: TLimb): BigCardinal; var Remainder: TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemLimbU(B, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; class operator BigCardinal.IntDivide(const A: TLimb; const B: BigCardinal): TLimb; var Remainder: TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemLimbU2(A, Result, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU2(PBigNumber(B.FNumber), A, Result, Remainder)); {$ENDIF} end; class operator BigCardinal.Modulus(const A: BigCardinal; const B: TLimb): TLimb; var Quotient: IBigNumber; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemLimbU(B, Quotient, Result)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU(PBigNumber(A.FNumber), B, PBigNumber(Quotient), Result)); {$ENDIF} end; class operator BigCardinal.Modulus(const A: TLimb; const B: BigCardinal): TLimb; var Quotient: TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemLimbU2(A, Quotient, Result)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU2(PBigNumber(B.FNumber), A, Quotient, Result)); {$ENDIF} end; { BigInteger } function BigInteger.ToString: string; var BytesUsed: Integer; L: Integer; P, P1: PByte; I: Integer; IsMinus: Boolean; begin {$IFDEF TFL_INTFCALL} BytesUsed:= FNumber.GetSize; {$ELSE} BytesUsed:= TBigNumber.GetSize(PBigNumber(FNumber)); // BytesUsed:= PBigNumber(FNumber).FUsed; {$ENDIF} // log(256) approximated from above by 41/17 L:= (BytesUsed * 41) div 17 + 1; GetMem(P, L); try {$IFDEF TFL_INTFCALL} HResCheck(FNumber.ToDec(P, L)); {$ELSE} HResCheck(TBigNumber.ToDec(PBigNumber(FNumber), P, L)); {$ENDIF} IsMinus:= GetSign < 0; if IsMinus then Inc(L); Result:= ''; SetLength(Result, L); I:= 1; if IsMinus then begin Result[1]:= '-'; Inc(I); end; P1:= P; while I <= L do begin Result[I]:= Char(P1^); Inc(P1); Inc(I); end; finally FreeMem(P); end; end; function BigInteger.ToHexString(Digits: Integer; const Prefix: string; TwoCompl: Boolean): string; const ASCII_8 = 56; // Ord('8') var L: Integer; P, P1: PByte; HR: TF_RESULT; Filler: Char; I: Integer; begin {$IFDEF TFL_INTFCALL} HR:= FNumber.ToHex(nil, L, TwoCompl); {$ELSE} HR:= TBigNumber.ToHex(PBigNumber(FNumber), nil, L, TwoCompl); {$ENDIF} if HR = TF_E_INVALIDARG then begin GetMem(P, L); try {$IFDEF TFL_INTFCALL} HResCheck(FNumber.ToHex(P, L, TwoCompl)); {$ELSE} HResCheck(TBigNumber.ToHex(PBigNumber(FNumber), P, L, TwoCompl)); {$ENDIF} if Digits < L then Digits:= L; I:= 1; Result:= ''; if (FNumber.GetSign < 0) and not TwoCompl then begin Inc(I); SetLength(Result, Digits + Length(Prefix) + 1); Result[1]:= '-'; end else SetLength(Result, Digits + Length(Prefix)); Move(Pointer(Prefix)^, Result[I], Length(Prefix) * SizeOf(Char)); Inc(I, Length(Prefix)); if Digits > L then begin if TwoCompl and (P[L] >= ASCII_8) then Filler:= 'F' else Filler:= '0'; while I + L <= Length(Result) do begin Result[I]:= Filler; Inc(I); end; end; P1:= P; while I <= Length(Result) do begin Result[I]:= Char(P1^); Inc(I); Inc(P1); end; finally FreeMem(P); end; end else BigNumberError(HR); end; function BigInteger.ToBytes: TBytes; var HR: TF_RESULT; L: Cardinal; begin Result:= nil; {$IFDEF TFL_INTFCALL} HR:= FNumber.ToPByte(nil, L); {$ELSE} HR:= TBigNumber.ToPByte(PBigNumber(FNumber), nil, L); {$ENDIF} if (HR = TF_E_INVALIDARG) and (L > 0) then begin SetLength(Result, L); HR:= FNumber.ToPByte(Pointer(Result), L); end; HResCheck(HR); end; class function BigInteger.Parse(const S: string; TwoCompl: Boolean): BigInteger; begin {$IFDEF TFL_DLL} HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(S), Length(S), SizeOf(Char), True, TwoCompl)); {$ELSE} HResCheck(BigNumberFromPChar(PBigNumber(Result.FNumber), Pointer(S), Length(S), SizeOf(Char), True, TwoCompl)); {$ENDIF} end; class function BigInteger.TryParse(const S: string; var R: BigInteger; TwoCompl: Boolean): Boolean; begin {$IFDEF TFL_DLL} Result:= BigNumberFromPChar(R.FNumber, Pointer(S), Length(S), SizeOf(Char), True, TwoCompl) = TF_S_OK; {$ELSE} Result:= BigNumberFromPChar(PBigNumber(R.FNumber), Pointer(S), Length(S), SizeOf(Char), True, TwoCompl) = TF_S_OK; {$ENDIF} end; function BigInteger.GetSign: Integer; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetSign; {$ELSE} Result:= TBigNumber.GetSign(PBigNumber(FNumber)); {$ENDIF} end; function BigInteger.GetHashCode: Integer; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetHashCode; {$ELSE} Result:= TBigNumber.GetHashCode(PBigNumber(FNumber)); {$ENDIF} end; function BigInteger.IsEven: Boolean; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetIsEven; {$ELSE} Result:= TBigNumber.GetIsEven(PBigNumber(FNumber)); {$ENDIF} end; function BigInteger.IsPowerOfTwo: Boolean; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetIsPowerOfTwo; {$ELSE} Result:= TBigNumber.GetIsPowerOfTwo(PBigNumber(FNumber)); {$ENDIF} end; class function BigInteger.PowerOfTwo(APower: Cardinal): BigInteger; begin {$IFDEF TFL_DLL} HResCheck(BigNumberPowerOfTwo(Result.FNumber, APower)); {$ELSE} HResCheck(BigNumberPowerOfTwo(PBigNumber(Result.FNumber), APower)); {$ENDIF} end; class function BigCardinal.Compare(const A, B: BigCardinal): Integer; begin Result:= Compare_BigCard_BigCard(A, B); end; class function BigInteger.Compare(const A, B: BigInteger): Integer; begin Result:= Compare_BigInt_BigInt(A, B); end; class function BigInteger.Compare(const A: BigInteger; const B: BigCardinal): Integer; begin Result:= Compare_BigInt_BigCard(A, B); end; class function BigInteger.Compare(const A: BigCardinal; const B: BigInteger): Integer; begin Result:= Compare_BigCard_BigInt(A, B); end; class function BigCardinal.Compare(const A: BigCardinal; const B: TLimb): Integer; begin Result:= Compare_BigCard_Limb(A, B); end; class function BigCardinal.Compare(const A: BigCardinal; const B: TIntLimb): Integer; begin Result:= Compare_BigCard_IntLimb(A, B); end; class function BigCardinal.Compare(const A: BigCardinal; const B: TDLimb): Integer; begin Result:= Compare_BigCard_DblLimb(A, B); end; class function BigCardinal.Compare(const A: BigCardinal; const B: TDIntLimb): Integer; begin Result:= Compare_BigCard_DblIntLimb(A, B); end; class function BigInteger.Compare(const A: BigInteger; const B: TLimb): Integer; begin Result:= Compare_BigInt_Limb(A, B); end; class function BigInteger.Compare(const A: BigInteger; const B: TIntLimb): Integer; begin Result:= Compare_BigInt_IntLimb(A, B); end; class function BigInteger.Compare(const A: BigInteger; const B: TDLimb): Integer; begin Result:= Compare_BigInt_DblLimb(A, B); end; class function BigInteger.Compare(const A: BigInteger; const B: TDIntLimb): Integer; begin Result:= Compare_BigInt_DblIntLimb(A, B); end; function BigInteger.CompareTo(const B: TLimb): Integer; begin Result:= Compare_BigInt_Limb(Self, B); end; function BigInteger.CompareTo(const B: TIntLimb): Integer; begin Result:= Compare_BigInt_IntLimb(Self, B); end; function BigInteger.CompareTo(const B: TDLimb): Integer; begin Result:= Compare_BigInt_DblLimb(Self, B); end; function BigInteger.CompareTo(const B: TDIntLimb): Integer; begin Result:= Compare_BigInt_DblIntLimb(Self, B); end; function BigInteger.CompareTo(const B: BigInteger): Integer; begin Result:= Compare_BigInt_BigInt(Self, B); end; function BigInteger.CompareTo(const B: BigCardinal): Integer; begin Result:= Compare_BigInt_BigCard(Self, B); end; class function BigCardinal.Equals(const A, B: BigCardinal): Boolean; begin Result:= Equal_BigCard_BigCard(A, B); end; class function BigInteger.Equals(const A, B: BigInteger): Boolean; begin Result:= Equal_BigInt_BigInt(A, B); end; class function BigInteger.Equals(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Equal_BigInt_BigCard(A, B); end; class function BigInteger.Equals(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Equal_BigCard_BigInt(A, B); end; function BigInteger.EqualsTo(const B: BigInteger): Boolean; begin Result:= Equal_BigInt_BigInt(Self, B); end; function BigInteger.EqualsTo(const B: BigCardinal): Boolean; begin Result:= Equal_BigInt_BigCard(Self, B); end; class function BigInteger.Abs(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AbsNumber(Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AbsNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.Pow(const Base: BigCardinal; Value: Cardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(Base.FNumber.PowU(Value, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.PowU(PBigNumber(Base.FNumber), Value, PBigNumber(Result.FNumber))); {$ENDIF} end; function BigCardinal.IsPowerOfTwo: Boolean; begin {$IFDEF TFL_INTFCALL} Result:= FNumber.GetIsPowerOfTwo; {$ELSE} Result:= TBigNumber.GetIsPowerOfTwo(PBigNumber(FNumber)); {$ENDIF} end; class function BigCardinal.PowerOfTwo(APower: Cardinal): BigCardinal; begin {$IFDEF TFL_DLL} HResCheck(BigNumberPowerOfTwo(Result.FNumber, APower)); {$ELSE} HResCheck(BigNumberPowerOfTwo(PBigNumber(Result.FNumber), APower)); {$ENDIF} end; function BigCardinal.Prev: BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(FNumber.PrevNumberU(Result.FNumber); {$ELSE} HResCheck(TBigNumber.PrevNumberU(PBigNumber(FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.Pow(const Base: BigInteger; Value: Cardinal): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(Base.FNumber.Pow(Value, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.Pow(PBigNumber(Base.FNumber), Value, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.BitwiseAnd(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AndNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AndNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.BitwiseOr(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.OrNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.OrNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.BitwiseXor(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.XorNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.XorNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; (* conversion to integer types is redesigned class operator BigInteger.Explicit(const Value: BigInteger): TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TDblLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToDblLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToDblLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToIntLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToIntLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TDblIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.ToDblIntLimb(Result)); {$ELSE} HResCheck(TBigNumber.ToDblIntLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; *) class operator BigInteger.Explicit(const Value: BigInteger): TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.GetLimb(Result)); {$ELSE} HResCheck(TBigNumber.GetLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TDLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.GetDblLimb(Result)); {$ELSE} HResCheck(TBigNumber.GetDblLimb(PBigNumber(Value.FNumber), Result)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.GetLimb(TLimb(Result))); {$ELSE} HResCheck(TBigNumber.GetLimb(PBigNumber(Value.FNumber), TLimb(Result))); {$ENDIF} end; class operator BigInteger.Explicit(const Value: BigInteger): TDIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Value.FNumber.GetDblLimb(TDblLimb(Result))); {$ELSE} HResCheck(TBigNumber.GetDblLimb(PBigNumber(Value.FNumber), TDLimb(Result))); {$ENDIF} end; class operator BigInteger.Implicit(const Value: BigCardinal): BigInteger; begin Result.FNumber:= Value.FNumber; end; class operator BigInteger.Explicit(const Value: BigInteger): BigCardinal; begin {$IFDEF TFL_INTFCALL} if (Value.FNumber.GetSign < 0) then {$ELSE} if (PBigNumber(Value.FNumber).FSign < 0) then {$ENDIF} BigNumberError(TF_E_INVALIDARG); Result.FNumber:= Value.FNumber; end; class operator BigInteger.Explicit(const Value: string): BigInteger; begin {$IFDEF TFL_DLL} HResCheck(BigNumberFromPChar(Result.FNumber, Pointer(Value), Length(Value), SizeOf(Char), True, False)); {$ELSE} // HResCheck(TBigNumber.FromString(PBigNumber(Result.FNumber), Value)); HResCheck(BigNumberFromPChar(PBigNumber(Result.FNumber), Pointer(Value), Length(Value), SizeOf(Char), True, False)); {$ENDIF} end; class operator BigInteger.Explicit(const Value: TBytes): BigInteger; begin {$IFDEF TFL_DLL} HResCheck(BigNumberFromPByte(Result.FNumber, {$ELSE} HResCheck(BigNumberFromPByte(PBigNumber(Result.FNumber), {$ENDIF} Pointer(Value), Length(Value), True)); end; class operator BigInteger.Equal(const A, B: BigInteger): Boolean; begin Result:= Equal_BigInt_BigInt(A, B); end; class operator BigInteger.Equal(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Equal_BigInt_BigCard(A, B); end; class operator BigInteger.Equal(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Equal_BigCard_BigInt(A, B); end; class operator BigInteger.NotEqual(const A, B: BigInteger): Boolean; begin Result:= not Equal_BigInt_BigInt(A, B); end; class operator BigInteger.NotEqual(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= not Equal_BigInt_BigCard(A, B); end; class operator BigInteger.NotEqual(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= not Equal_BigCard_BigInt(A, B); end; class operator BigInteger.GreaterThan(const A, B: BigInteger): Boolean; begin Result:= Compare_BigInt_BigInt(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Compare_BigInt_BigCard(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Compare_BigCard_BigInt(A, B) > 0; end; class operator BigInteger.GreaterThanOrEqual(const A, B: BigInteger): Boolean; begin Result:= Compare_BigInt_BigInt(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Compare_BigInt_BigCard(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Compare_BigCard_BigInt(A, B) >= 0; end; class operator BigInteger.LessThan(const A, B: BigInteger): Boolean; begin Result:= Compare_BigInt_BigInt(A, B) < 0; end; class operator BigInteger.LessThan(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Compare_BigInt_BigCard(A, B) < 0; end; class operator BigInteger.LessThan(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Compare_BigCard_BigInt(A, B) < 0; end; class operator BigInteger.LessThanOrEqual(const A, B: BigInteger): Boolean; begin Result:= Compare_BigInt_BigInt(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: BigCardinal): Boolean; begin Result:= Compare_BigInt_BigCard(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: BigCardinal; const B: BigInteger): Boolean; begin Result:= Compare_BigCard_BigInt(A, B) <= 0; end; class operator BigInteger.LeftShift(const A: BigInteger; Shift: Cardinal): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ShlNumber(Shift, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ShlNumber(PBigNumber(A.FNumber), Shift, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.RightShift(const A: BigInteger; Shift: Cardinal): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ShrNumber(Shift, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ShrNumber(PBigNumber(A.FNumber), Shift, PBigNumber(Result.FNumber))); {$ENDIF} end; procedure BigInteger.Free; begin FNumber:= nil; end; class operator BigInteger.Implicit(const Value: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigInteger.Implicit(const Value: TDLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromDblLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromDblLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigInteger.Implicit(const Value: TIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromIntLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromIntLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigInteger.Implicit(const Value: TDIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(BigNumberFromDblIntLimb(Result.FNumber, Value)); {$ELSE} HResCheck(BigNumberFromDblIntLimb(PBigNumber(Result.FNumber), Value)); {$ENDIF} end; class operator BigInteger.Add(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AddNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Subtract(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SubNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Multiply(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.MulNumber(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.IntDivide(const A, B: BigInteger): BigInteger; var Remainder: IBigNumber; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemNumber(B.FNumber, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber), PBigNumber(Remainder))); {$ENDIF} end; class operator BigInteger.Modulus(const A, B: BigInteger): BigInteger; var Quotient: IBigNumber; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemNumber(B.FNumber, Quotient, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemNumbers(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Quotient), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.DivRem(const Dividend, Divisor: BigCardinal; var Remainder: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(Dividend.FNumber.DivRemNumberU(Divisor.FNumber, Result.FNumber, Remainder.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemNumbersU(PBigNumber(Dividend.FNumber), PBigNumber(Divisor.FNumber), PBigNumber(Result.FNumber), PBigNumber(Remainder.FNumber))); {$ENDIF} end; class function BigInteger.DivRem(const Dividend, Divisor: BigInteger; var Remainder: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(Dividend.FNumber.DivRemNumber(Divisor.FNumber, Result.FNumber, Remainder.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemNumbers(PBigNumber(Dividend.FNumber), PBigNumber(Divisor.FNumber), PBigNumber(Result.FNumber), PBigNumber(Remainder.FNumber))); {$ENDIF} end; class function BigCardinal.DivRem(const Dividend: BigCardinal; Divisor: TLimb; var Remainder: TLimb): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(Dividend.FNumber.DivRemLimbU(Divisor, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU(PBigNumber(Dividend.FNumber), Divisor, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; class function BigCardinal.DivRem(const Dividend: TLimb; Divisor: BigCardinal; var Remainder: TLimb): TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Divisor.FNumber.DivRemLimbU2(Dividend, Result, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimbU2(PBigNumber(Divisor.FNumber), Dividend, Result, Remainder)); {$ENDIF} end; class function BigCardinal.Sqr(const A: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SqrNumber(Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SqrNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.Sqrt(const A: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SqrtNumber(Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SqrtNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.Sqr(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SqrNumber(Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SqrNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.Sqrt(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SqrtNumber(Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SqrtNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.GCD(const A, B: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.GCD(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.GCD(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.GCD(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; (* class function BigInteger.GCD(const A: BigInteger; const B: BigCardinal): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.GCD(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.GCD(const A: BigCardinal; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.GCD(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.GCD(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; *) class function BigInteger.LCM(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.LCM(B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.LCM(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.EGCD(const A, B: BigInteger; var X, Y: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.EGCD(B.FNumber, Result.FNumber, X.FNumber, Y.FNumber)); {$ELSE} HResCheck(TBigNumber.EGCD(PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber), PBigNumber(X.FNumber), PBigNumber(Y.FNumber))); {$ENDIF} end; class function BigInteger.ModPow(const BaseValue, ExpValue, Modulo: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(BaseValue.FNumber.ModPow(ExpValue.FNumber, Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModPow(PBigNumber(BaseValue.FNumber), PBigNumber(ExpValue.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.ModPow(const BaseValue, ExpValue, Modulo: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(BaseValue.FNumber.ModPow(ExpValue.FNumber, Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModPow(PBigNumber(BaseValue.FNumber), PBigNumber(ExpValue.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigCardinal.ModInverse(const A, Modulo: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModInverse(PBigNumber(A.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.ModInverse(const A, Modulo: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModInverse(PBigNumber(A.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; (* class function BigInteger.ModInverse(const A: BigInteger; const Modulo: BigCardinal): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModInverse(PBigNumber(A.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.ModInverse(const A: BigCardinal; const Modulo: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.ModInverse(Modulo.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.ModInverse(PBigNumber(A.FNumber), PBigNumber(Modulo.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; *) class operator BigInteger.Equal(const A: BigInteger; const B: TLimb): Boolean; begin Result:= Equal_BigInt_Limb(A, B); end; class operator BigInteger.Equal(const A: TLimb; const B: BigInteger): Boolean; begin Result:= Equal_BigInt_Limb(B, A); end; class operator BigInteger.Equal(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= Equal_BigInt_IntLimb(A, B); end; class operator BigInteger.Equal(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= Equal_BigInt_IntLimb(B, A); end; class operator BigInteger.NotEqual(const A: BigInteger; const B: TLimb): Boolean; begin Result:= not Equal_BigInt_Limb(A, B); end; class operator BigInteger.NotEqual(const A: TLimb; const B: BigInteger): Boolean; begin Result:= not Equal_BigInt_Limb(B, A); end; class operator BigInteger.NotEqual(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= not Equal_BigInt_IntLimb(A, B); end; class operator BigInteger.NotEqual(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= not Equal_BigInt_IntLimb(B, A); end; class operator BigInteger.GreaterThan(const A: BigInteger; const B: TLimb): Boolean; begin Result:= Compare_BigInt_Limb(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: TLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_Limb(B, A) < 0; end; class operator BigInteger.GreaterThan(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= Compare_BigInt_IntLimb(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_IntLimb(B, A) < 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: TLimb): Boolean; begin Result:= Compare_BigInt_Limb(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: TLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_Limb(B, A) <= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= Compare_BigInt_IntLimb(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_IntLimb(B, A) <= 0; end; class operator BigInteger.LessThan(const A: BigInteger; const B: TLimb): Boolean; begin Result:= Compare_BigInt_Limb(A, B) < 0; end; class operator BigInteger.LessThan(const A: TLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_Limb(B, A) > 0; end; class operator BigInteger.LessThan(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= Compare_BigInt_IntLimb(A, B) < 0; end; class operator BigInteger.LessThan(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_IntLimb(B, A) > 0; end; class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: TLimb): Boolean; begin Result:= Compare_BigInt_Limb(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: TLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_Limb(B, A) >= 0; end; class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: TIntLimb): Boolean; begin Result:= Compare_BigInt_IntLimb(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: TIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_IntLimb(B, A) >= 0; end; class operator BigInteger.Equal(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= Equal_BigInt_DblLimb(A, B); end; class operator BigInteger.Equal(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= Equal_BigInt_DblLimb(B, A); end; class operator BigInteger.Equal(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= Equal_BigInt_DblIntLimb(A, B); end; class operator BigInteger.Equal(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= Equal_BigInt_DblIntLimb(B, A); end; class operator BigInteger.NotEqual(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= not Equal_BigInt_DblLimb(A, B); end; class operator BigInteger.NotEqual(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= not Equal_BigInt_DblLimb(B, A); end; class operator BigInteger.NotEqual(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= not Equal_BigInt_DblIntLimb(A, B); end; class operator BigInteger.NotEqual(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= not Equal_BigInt_DblIntLimb(B, A); end; class operator BigInteger.GreaterThan(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= Compare_BigInt_DblLimb(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblLimb(B, A) < 0; end; class operator BigInteger.GreaterThan(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= Compare_BigInt_DblIntLimb(A, B) > 0; end; class operator BigInteger.GreaterThan(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblIntLimb(B, A) < 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= Compare_BigInt_DblLimb(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblLimb(B, A) <= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= Compare_BigInt_DblIntLimb(A, B) >= 0; end; class operator BigInteger.GreaterThanOrEqual(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblIntLimb(B, A) <= 0; end; class operator BigInteger.LessThan(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= Compare_BigInt_DblLimb(A, B) < 0; end; class operator BigInteger.LessThan(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblLimb(B, A) > 0; end; class operator BigInteger.LessThan(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= Compare_BigInt_DblIntLimb(A, B) < 0; end; class operator BigInteger.LessThan(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblIntLimb(B, A) > 0; end; class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: TDLimb): Boolean; begin Result:= Compare_BigInt_DblLimb(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: TDLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblLimb(B, A) >= 0; end; class operator BigInteger.LessThanOrEqual(const A: BigInteger; const B: TDIntLimb): Boolean; begin Result:= Compare_BigInt_DblIntLimb(A, B) <= 0; end; class operator BigInteger.LessThanOrEqual(const A: TDIntLimb; const B: BigInteger): Boolean; begin Result:= Compare_BigInt_DblIntLimb(B, A) >= 0; end; // -- arithmetic operations on BigInteger & TLimb -- class operator BigInteger.Add(const A: BigInteger; const B: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AddLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Subtract(const A: BigInteger; const B: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SubLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Multiply(const A: BigInteger; const B: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.MulLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.IntDivide(const A: BigInteger; const B: TLimb): BigInteger; var Remainder: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemLimb(B, Result.FNumber, Remainder.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber), PBigNumber(Remainder.FNumber))); {$ENDIF} end; class operator BigInteger.Modulus(const A: BigInteger; const B: TLimb): BigInteger; var Quotient: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemLimb(B, Quotient.FNumber, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemLimb(PBigNumber(A.FNumber), B, PBigNumber(Quotient.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class function BigInteger.DivRem(const Dividend: BigInteger; const Divisor: TLimb; var Remainder: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(Dividend.FNumber.DivRemLimb(Divisor, Result.FNumber, Remainder.FNumber)); {$ELSE} HResCheck(TBigNumber.DivRemLimb(PBigNumber(Dividend.FNumber), Divisor, PBigNumber(Result.FNumber), PBigNumber(Remainder.FNumber))); {$ENDIF} end; // -- arithmetic operations on TLimb & BigInteger -- class operator BigInteger.Add(const A: TLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.AddLimb(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddLimb(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Subtract(const A: TLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.SubLimb2(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubLimb2(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Multiply(const A: TLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.MulLimb(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulLimb(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.IntDivide(const A: TLimb; const B: BigInteger): BigInteger; var Remainder: TLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemLimb2(A, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimb2(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; class operator BigInteger.Modulus(const A: TLimb; const B: BigInteger): TLimb; var Quotient: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemLimb2(A, Quotient.FNumber, Result)); {$ELSE} HResCheck(TBigNumber.DivRemLimb2(PBigNumber(B.FNumber), A, PBigNumber(Quotient.FNumber), Result)); {$ENDIF} end; class function BigInteger.DivRem(const Dividend: TLimb; const Divisor: BigInteger; var Remainder: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(Divisor.FNumber.DivRemLimb2(Dividend, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemLimb2(PBigNumber(Divisor.FNumber), Dividend, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; // -- arithmetic operations on BigInteger & TIntLimb -- class operator BigInteger.Add(const A: BigInteger; const B: TIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.AddIntLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddIntLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Subtract(const A: BigInteger; const B: TIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.SubIntLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubIntLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Multiply(const A: BigInteger; const B: TIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.MulIntLimb(B, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulIntLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.IntDivide(const A: BigInteger; const B: TIntLimb): BigInteger; var Remainder: TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemIntLimb(B, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb(PBigNumber(A.FNumber), B, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; class operator BigInteger.Modulus(const A: BigInteger; const B: TIntLimb): TIntLimb; var Quotient: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.FNumber.DivRemIntLimb(B, Quotient.FNumber, Result)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb(PBigNumber(A.FNumber), B, PBigNumber(Quotient.FNumber), Result)); {$ENDIF} end; class function BigInteger.DivRem(const Dividend: BigInteger; const Divisor: TIntLimb; var Remainder: TIntLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(Dividend.FNumber.DivRemIntLimb(Divisor, Result.FNumber, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb(PBigNumber(Dividend.FNumber), Divisor, PBigNumber(Result.FNumber), Remainder)); {$ENDIF} end; // -- arithmetic operations on TIntLimb & BigInteger -- class operator BigInteger.Add(const A: TIntLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.AddIntLimb(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.AddIntLimb(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Subtract(const A: TIntLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.SubIntLimb2(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.SubIntLimb2(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Multiply(const A: TIntLimb; const B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.MulIntLimb(A, Result.FNumber)); {$ELSE} HResCheck(TBigNumber.MulIntLimb(PBigNumber(B.FNumber), A, PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.IntDivide(const A: TIntLimb; const B: BigInteger): TIntLimb; var Remainder: TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemIntLimb2(A, Result, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb2(PBigNumber(B.FNumber), A, Result, Remainder)); {$ENDIF} end; class operator BigInteger.Modulus(const A: TIntLimb; const B: BigInteger): TIntLimb; var Quotient: TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(B.FNumber.DivRemIntLimb2(A, Quotient, Result)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb2(PBigNumber(B.FNumber), A, Quotient, Result)); {$ENDIF} end; class function BigInteger.DivRem(const Dividend: TIntLimb; const Divisor: BigInteger; var Remainder: TIntLimb): TIntLimb; begin {$IFDEF TFL_INTFCALL} HResCheck(Divisor.FNumber.DivRemIntLimb2(Dividend, Result, Remainder)); {$ELSE} HResCheck(TBigNumber.DivRemIntLimb2(PBigNumber(Divisor.FNumber), Dividend, Result, Remainder)); {$ENDIF} end; function BigInteger.Next: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FNumber.NextNumber(Result.FNumber); {$ELSE} HResCheck(TBigNumber.NextNumber(PBigNumber(FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function BigInteger.Prev: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FNumber.PrevNumber(Result.FNumber); {$ELSE} HResCheck(TBigNumber.PrevNumber(PBigNumber(FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Negative(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.NegateNumber(Result.FNumber); {$ELSE} HResCheck(TBigNumber.NegateNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigInteger.Positive(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(A.DuplicateNumber(Result.FNumber); {$ELSE} HResCheck(TBigNumber.DuplicateNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; class operator BigCardinal.Positive(const A: BigCardinal): BigCardinal; begin {$IFDEF TFL_INTFCALL} HResCheck(A.DuplicateNumber(Result.FNumber); {$ELSE} HResCheck(TBigNumber.DuplicateNumber(PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; { TMont } class function TMont.GetInstance(const Modulus: BigInteger): TMont; begin {$IFDEF TFL_DLL} HResCheck(GetMontInstance(Result.FInstance, Modulus.FNumber)); {$ELSE} HResCheck(GetMontInstance(PMontInstance(Result.FInstance), PBigNumber(Modulus.FNumber))); {$ENDIF} end; function TMont.GetRModulus: BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.GetRModulus(Result.FNumber)); {$ELSE} HResCheck(TMontInstance.GetRModulus(PMontInstance(FInstance), PBigNumber(Result.FNumber))); {$ENDIF} end; procedure TMont.Free; begin FInstance:= nil; end; function TMont.IsAssigned: Boolean; begin Result:= FInstance <> nil; end; procedure TMont.Burn; begin {$IFDEF TFL_INTFCALL} FInstance.Burn; {$ELSE} TMontInstance.Burn(PMontInstance(FInstance)); {$ENDIF} end; function TMont.Convert(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.Convert(A.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.Convert(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.Reduce(const A: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.Reduce(A.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.Reduce(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.Add(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.AddNumbers(A.FNumber, B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.AddNumbers(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.Multiply(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.MulNumbers(A.FNumber, B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.MulNumbers(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.Subtract(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.SubNumbers(A.FNumber, B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.SubNumbers(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.ModMul(const A, B: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.ModMulNumbers(A.FNumber, B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.ModMulNumbers(PMontInstance(FInstance), PBigNumber(A.FNumber), PBigNumber(B.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.ModPow(const Base: BigInteger; Pow: TLimb): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.PowLimb(A.FNumber, B, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.ModPowLimb(PMontInstance(FInstance), PBigNumber(Base.FNumber), Pow, PBigNumber(Result.FNumber))); {$ENDIF} end; function TMont.ModPow(const Base, Pow: BigInteger): BigInteger; begin {$IFDEF TFL_INTFCALL} HResCheck(FInstance.PowNumber(A.FNumber, B.FNumber, Result.FNumber)); {$ELSE} HResCheck(TMontInstance.ModPowNumber(PMontInstance(FInstance), PBigNumber(Base.FNumber), PBigNumber(Pow.FNumber), PBigNumber(Result.FNumber))); {$ENDIF} end; end.
unit SelectLenderForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, Grids, AdvGrid, FFSAdvStringGrid, TCWODT, RXCtrls, sBitBtn; //uFreeLocalizer type TfrmSelectLender = class(TForm) grdLender: TFFSAdvStringGrid; btnOk: TsBitBtn; btnCancel: TsBitBtn; procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure grdLenderKeyPress(Sender: TObject; var Key: Char); procedure grdLenderDblClick(Sender: TObject); procedure grdLenderMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdLenderMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private FLendList : TStringList; FColName: integer; FColNumber: integer; FLastLender:string; procedure FillGrid; procedure GotoLastLender; procedure FindFirst(c: char); procedure FindNext(c: char); function GetSelectedLender:string; public { Public declarations } LendList: TStringList; constructor create(AOwner:Tcomponent;ALendList:TStringList;ALastLender:string); reintroduce; destructor destroy;override; property SelectedLender:string read GetSelectedLender; end; var frmSelectLender: TfrmSelectLender; implementation uses ffsutils, datamod, TicklerGlobals ; {$R *.DFM} procedure TfrmSelectLender.FillGrid; var x : integer; sl : TStringList; begin sl := TStringList.create; try {$IFDEF SERVER} sl.Assign(LendList); {$ELSE} daapi.LendGetSelectList(CurrentUser.PLenderGroup, sl); {$ENDIF} grdLender.LoadFromCSVStringList(sl); grdLender.SortColumn := FColName; grdLender.QSort; grdLender.FitLastColumn; finally sl.free; end; end; procedure TfrmSelectLender.btnOkClick(Sender: TObject); begin ModalResult := mrOk; end; constructor TfrmSelectLender.create(AOwner:Tcomponent;ALendList:TStringList;ALastLender:string); var sl : TStringList; x,y : integer; totalWidth : integer; function LendGetLendHeaders: string; begin result := '"LNum",60,"Name",190,"Number",60,2,1'; end; begin inherited create(AOwner); FLendList := TStringList.create; LendList := TStringList.Create; FLendList.Assign(ALendList); FLastLender := ALastLender; sl := TStringlist.create; try sl.commatext := LendGetLendHeaders; y := sl.count - 2; grdLender.ColCount := y div 2; grdLender.columnheaders.clear; totalwidth := 0; x := 0; while x < y do begin grdLender.Columnheaders.add(sl[x]); grdLender.Colwidths[x div 2] := StrToIntDef(sl[x+1],15); inc(totalwidth, grdLender.Colwidths[x div 2]); inc(x,2); end; self.ClientWidth := totalwidth + grdLender.ScrollWidth + 6; if self.ClientWidth < 200 then self.ClientWidth := 200; btnOk.left := (self.clientwidth - 165) div 2; btnCancel.Left := btnOk.Left + 90; FColNumber := StrToIntDef(sl[y],0); FColName := StrToIntDef(sl[y+1],1); finally sl.free; end; end; procedure TfrmSelectLender.FormShow(Sender: TObject); begin FillGrid; GotoLastLender; //FreeLocalizer.Translate(Self); // grdLender.Repaint; end; procedure TfrmSelectLender.GotoLastLender; var x : integer; begin grdLender.Row := 1; for x := 1 to grdLender.rowcount - 1 do begin if grdLender.cells[FColNumber,x] = FLastLender then begin grdLender.Row := x; break; end; end; end; procedure TfrmSelectLender.FindFirst(c:char); var x : integer; begin x := 1; while (x < grdLender.rowcount) do begin if uppercase(copy(grdLender.cells[FColName,x],1,1)) = c then begin grdLender.Row := x; break; end else inc(x); end; end; procedure TfrmSelectLender.FindNext(c:char); var x : integer; f : boolean; begin f := false; x := grdLender.Row+1; while (x < grdLender.rowcount) do begin if uppercase(copy(grdLender.cells[FColName,x],1,1)) = c then begin grdLender.Row := x; f := true; break; end else inc(x); end; if not f then FindFirst(c); end; procedure TfrmSelectLender.grdLenderKeyPress(Sender: TObject; var Key: Char); var x : integer; c : char; begin c := upcase(key); if c in ['A'..'Z'] then begin if c = uppercase(copy(grdLender.cells[FColName,grdLender.Row],1,1)) then FindNext(c) else FindFirst(c); key := #0; end; end; procedure TfrmSelectLender.grdLenderDblClick(Sender: TObject); begin btnOk.Click; end; destructor TfrmSelectLender.destroy; begin FLendList.free; LendList.Free; inherited; end; function TfrmSelectLender.GetSelectedLender: string; begin result := grdLender.cells[FColNumber,grdLender.Row] end; procedure TfrmSelectLender.grdLenderMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdLender.SetFocus; end; procedure TfrmSelectLender.grdLenderMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdLender.SetFocus; end; end.
unit kwClearTemplateStorage; {* Очищает данные для 'Текстового шаблона' } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwClearTemplateStorage.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "ClearTemplateStorage" MUID: (53B647A9029B) // Имя типа: "TkwClearTemplateStorage" {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type TkwClearTemplateStorage = {final} class(TtfwRegisterableWord) {* Очищает данные для 'Текстового шаблона' } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwClearTemplateStorage {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)} uses l3ImplUses , arArchiTestAdapter2 //#UC START# *53B647A9029Bimpl_uses* //#UC END# *53B647A9029Bimpl_uses* ; class function TkwClearTemplateStorage.GetWordNameForRegister: AnsiString; begin Result := 'ClearTemplateStorage'; end;//TkwClearTemplateStorage.GetWordNameForRegister procedure TkwClearTemplateStorage.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_53B647A9029B_var* //#UC END# *4DAEEDE10285_53B647A9029B_var* begin //#UC START# *4DAEEDE10285_53B647A9029B_impl* ArClearTemplateStorage; //#UC END# *4DAEEDE10285_53B647A9029B_impl* end;//TkwClearTemplateStorage.DoDoIt initialization TkwClearTemplateStorage.RegisterInEngine; {* Регистрация ClearTemplateStorage } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts) end.
unit uLicencaController; interface uses System.SysUtils, uDMOrcamento, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFiltroOrcamento, Data.DBXJSON, Data.DBXJSONReflect, uUsuario, uParcelas, uOrcamentoVO, uFormaPagtoVO, uObsevacaoController, uConverter, System.Generics.Collections, uOrcamentoEmailVO, uGenericProperty, uDepartamentoEmailVO, uParametrosController, uFormaPagtoController, uClienteController, uTipoController, uTipoVO, uContatoVO, ULicencaVO, uLicencaItensVO, uFiltroLicenca; type TLicencaController = class public procedure Importar(); function BuscarLicencas(AFiltro: TFiltroLicenca): TObjectList<TLicencaVO>; function BuscarLicencasItens(AFiltro: TFiltroLicenca): TObjectList<TLicencaItensVO>; procedure PermissaoAcessar(AIdUsuario: Integer); function LimparLicencas(): string; end; implementation { TLicencaController } function TLicencaController.BuscarLicencas(AFiltro: TFiltroLicenca): TObjectList<TLicencaVO>; var Negocio: TServerModule2Client; objJSON: TJSONValue; begin objJSON := TConverte.ObjectToJSON<TFiltroLicenca>(AFiltro); dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Result := TConverte.JSONToObject<TListaLicenca>(Negocio.LicencasListarTodos(objJSON)); finally FreeAndNil(Negocio); end; end; function TLicencaController.BuscarLicencasItens(AFiltro: TFiltroLicenca): TObjectList<TLicencaItensVO>; var Negocio: TServerModule2Client; objJSON: TJSONValue; begin Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); objJSON := TConverte.ObjectToJSON<TFiltroLicenca>(AFiltro); try Result := TConverte.JSONToObject<TListaLicencaItens>(Negocio.LicencasListarTodosItens(objJSON)); finally FreeAndNil(Negocio); end; end; procedure TLicencaController.Importar; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.LicencasImportar(); finally FreeAndNil(Negocio); end; end; function TLicencaController.LimparLicencas: string; var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Result := Negocio.LicencasLimpar(); finally FreeAndNil(Negocio); end; end; procedure TLicencaController.PermissaoAcessar(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.LicencaPermissaoAcessar(CLicenca, AIdUsuario); finally FreeAndNil(Negocio); end; end; end.
unit infosistemas.business.address; interface uses System.Classes, System.SysUtils, Rest.Client, System.Json; type TAddressUtils = class(TObject) private const sUrl: string = 'https://viacep.com.br/ws/'; //do not localize! sCepParam: string = '%s/json'; //do not localize! var FCep, FLogradouro, FBairro, FCidade, FUF, FComplemento: string; function IsValidParam(const cep: string): boolean; procedure ClearData; public constructor Create; destructor Destroy; override; function BuscaDadosCep(const cep: string): boolean; property Cep: string read FCep; property Logradouro: string read FLogradouro; property Bairro: string read FBairro; property Cidade: string read FCidade; property UF: string read FUF; property Complemento: string read FComplemento; end; implementation { TAddressUtils } function TAddressUtils.BuscaDadosCep(const cep: string): boolean; var RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; FData: TJSONObject; begin {Busca dados do cep no serviço remoto. Os dados são retornado pelo serviço no padrão JSON.} //Verifica o cep informado. Se o cep não está no formato esperado nem vai //ao serviço remoto. Result := IsValidParam(cep); if Result = False then Exit; RESTClient1 := TRESTClient.Create(nil); RESTRequest1 := TRESTRequest.Create(nil); RESTResponse1 := TRESTResponse.Create(nil); RESTRequest1.Client := RESTClient1; RESTRequest1.Response := RESTResponse1; RESTClient1.BaseURL := sUrl + Format(sCepParam, [cep]); self.ClearData; try RESTRequest1.Execute; FData := RESTResponse1.JSONValue as TJSONObject; //FData.Count = 1 indica que o cep informado não existe no serviço remoto. Result := (Assigned(FData)) and (FData.Count > 1); if Result then begin FCep := cep; FLogradouro := FData.Values['logradouro'].Value; FBairro := FData.Values['bairro'].Value; FCidade := FData.Values['localidade'].Value; FUF := FData.Values['uf'].Value; FComplemento := FData.Values['complemento'].Value; end; finally FreeAndNil(RESTClient1); FreeAndNil(RESTRequest1); FreeAndNil(RESTResponse1); end; end; procedure TAddressUtils.ClearData; begin //Limpa as variáveis internas dos dados do endereço. FCep := ''; FLogradouro := ''; FBairro := ''; FCidade := ''; FUF := ''; FComplemento := ''; end; constructor TAddressUtils.Create; begin inherited Create; end; destructor TAddressUtils.Destroy; begin inherited Destroy; end; function TAddressUtils.IsValidParam(const cep: string): boolean; begin //Valida se o cep é válido ou possui comandos inválidos a serem passados para //o serviço remoto. Aqui a validação é apenas um constraint simples. Result := (Cep.Trim <> '') and (Cep.Trim.Length = 9) and (Cep.Contains('-')); end; end.
unit Eagle.ERP.{ModuleName}.Model.Repository.Impl.{ModelName}Repository; interface uses System.SysUtils, Spring, Spring.Container, Spring.Container.Common, Eagle.ERP.Common.DB.Connection, Eagle.ERP.{ModuleName}.Model.Repository.{ModelName}Repository, Eagle.ERP.{ModuleName}.Model.Entity.{ModelName}, Eagle.ERP.{ModuleName}.Model.Entity.Impl.{ModelName}; type [Interceptor('transactional')] T{ModelName}Repository = class(TInterfacedObject, I{ModelName}Repository) private [Inject] FConnection : IConnection; function GetRecord(const Sql: string): I{ModelName}; public function IsFirst({ModelName}: I{ModelName}): Boolean; function IsLast({ModelName}: I{ModelName}): Boolean; function GetFirst(): I{ModelName}; function GetPrior(Current: I{ModelName}): I{ModelName}; function GetNext(Current: I{ModelName}): I{ModelName}; function GetLast(): I{ModelName}; function Reload(Current: I{ModelName}): I{ModelName}; function Get(const Id: Integer): I{ModelName}; procedure Save({ModelName}: I{ModelName}); procedure Delete({ModelName}: I{ModelName}); end; implementation { T{ModelName}Repository } procedure T{ModelName}Repository.Delete({ModelName}: I{ModelName}); begin FConnection.GetSession.Delete({ModelName} as TInterfacedObject); end; function T{ModelName}Repository.Get(const Id: Integer): I{ModelName}; begin Result := FConnection.GetSession.FindOne<T{ModelName}>(Id); end; function T{ModelName}Repository.GetFirst: I{ModelName}; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S ORDER BY {ModelName}S_ID'; begin Result := GetRecord(SQL_ID); end; function T{ModelName}Repository.GetLast: I{ModelName}; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S ORDER BY {ModelName}S_ID DESC'; begin Result := GetRecord(SQL_ID); end; function T{ModelName}Repository.GetNext(Current: I{ModelName}): I{ModelName}; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S WHERE {ModelName}S_ID > ? ORDER BY {ModelName}S_ID'; begin Result := GetRecord(SQL_ID.Replace('?', string.Parse(Current.Id).QuotedString)); end; function T{ModelName}Repository.GetPrior(Current: I{ModelName}): I{ModelName}; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S WHERE {ModelName}S_ID < ? ORDER BY 1 DESC'; begin Result := GetRecord(SQL_ID.Replace('?', string.Parse(Current.Id).QuotedString)); end; function T{ModelName}Repository.GetRecord(const Sql: string): I{ModelName}; var Id: string; begin Id := FConnection.GetSession.ExecuteScalar<string>(Sql, []); Result := FConnection.GetSession.FindOne<T{ModelName}>(Id); end; function T{ModelName}Repository.IsFirst({ModelName}: I{ModelName}): Boolean; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S WHERE {ModelName}S_ID < ?'; var Sql: string; begin if not Assigned({ModelName}) then Exit(False); Sql := SQL_ID.Replace('?', string.Parse({ModelName}.Id).QuotedString); Result := FConnection.GetSession.ExecuteScalar<string>(Sql, []).Equals('') end; function T{ModelName}Repository.IsLast({ModelName}: I{ModelName}): Boolean; const SQL_ID = 'SELECT FIRST 1 {ModelName}S_ID FROM {ModelName}S WHERE {ModelName}S_ID > ?'; var Sql: string; begin if not Assigned({ModelName}) then Exit(False); Sql := SQL_ID.Replace('?', string.Parse({ModelName}.Id).QuotedString); Result := FConnection.GetSession.ExecuteScalar<string>(Sql, []).Equals('') end; function T{ModelName}Repository.Reload(Current: I{ModelName}): I{ModelName}; begin Result := FConnection.GetSession.FindOne<T{ModelName}>(Current.Id); end; procedure T{ModelName}Repository.Save({ModelName}: I{ModelName}); begin FConnection.GetSession.Save({ModelName} as TInterfacedObject); end; initialization GlobalContainer.RegisterType<T{ModelName}Repository>('{ModelName}Repository').Implements<I{ModelName}Repository>; end.
unit MyLib; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Process; procedure fun_StrToCommandLine (var cmd: string); // Процедура для передачи команды Командной строке Linux в качестве строки implementation {Процедура для передачи команды Командной строке Linux в качестве строки} procedure fun_StrToCommandLine(var cmd: string); var AProcess: TProcess; begin AProcess := TProcess.Create(nil); try AProcess.CommandLine := cmd; AProcess.Options := AProcess.Options; AProcess.Execute; finally AProcess.Free; end; end; end.
unit nsBaseTagNode; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "f1DocumentTagsImplementation" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/f1DocumentTagsImplementation/nsBaseTagNode.pas" // Начат: 19.08.2010 14:33 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::f1DocumentTagsImplementation::DocumentTagNodes::TnsBaseTagNode // // Базовая реализация тега на уровне оболочки // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses k2Interfaces, k2HugeTagObject, nevTools, k2Prim ; type TnsBaseTagNode = {abstract} class(Tk2HugeTagObject) {* Базовая реализация тега на уровне оболочки } protected // overridden protected methods function DeleteChildPrim(anIndex: Integer; const aChild: Ik2Tag; const aContext: Ik2Op): Boolean; override; function AddChild(var aChild: Ik2Tag; const aContext: Ik2Op = nil): Integer; override; procedure InsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op = nil); override; protected // protected methods procedure BaseInsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op); function BaseDeleteChild(anIndex: Integer; const aContext: Ik2Op): Boolean; function Op(aCode: Integer; aNeedUndo: Boolean): Ik2Op; procedure ChildInserted(const aChild: Ik2Tag; const anOp: Ik2Op); virtual; procedure CheckChildDelete(anIndex: Integer; const aChild: Ik2Tag); virtual; procedure DoInsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op); virtual; function DoDeleteChild(anIndex: Integer; const aContext: Ik2Op): Boolean; virtual; end;//TnsBaseTagNode implementation // start class TnsBaseTagNode procedure TnsBaseTagNode.BaseInsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op); //#UC START# *4C6CED6D03CC_467FCA4701F9_var* //#UC END# *4C6CED6D03CC_467FCA4701F9_var* begin //#UC START# *4C6CED6D03CC_467FCA4701F9_impl* inherited InsertChild(anIndex, aChild, aContext); //#UC END# *4C6CED6D03CC_467FCA4701F9_impl* end;//TnsBaseTagNode.BaseInsertChild function TnsBaseTagNode.BaseDeleteChild(anIndex: Integer; const aContext: Ik2Op): Boolean; //#UC START# *4C6CEDA601C5_467FCA4701F9_var* //#UC END# *4C6CEDA601C5_467FCA4701F9_var* begin //#UC START# *4C6CEDA601C5_467FCA4701F9_impl* Result := inherited DeleteChildPrim(anIndex, nil, aContext); //#UC END# *4C6CEDA601C5_467FCA4701F9_impl* end;//TnsBaseTagNode.BaseDeleteChild function TnsBaseTagNode.Op(aCode: Integer; aNeedUndo: Boolean): Ik2Op; //#UC START# *4C6CEDD103A4_467FCA4701F9_var* //#UC END# *4C6CEDD103A4_467FCA4701F9_var* var l_Para : InevPara; l_Cont : InevDocumentContainer; begin //#UC START# *4C6CEDD103A4_467FCA4701F9_impl* if not QT(InevPara, l_Para) then Assert(false); l_Cont := l_Para.DocumentContainer; if (l_Cont = nil) then Result := nil else begin Result := l_Cont.Processor.StartOp(aCode); if (Result <> nil) then Result.SaveUndo := aNeedUndo; end;//l_Cont = nil //#UC END# *4C6CEDD103A4_467FCA4701F9_impl* end;//TnsBaseTagNode.Op procedure TnsBaseTagNode.ChildInserted(const aChild: Ik2Tag; const anOp: Ik2Op); //#UC START# *4C6CECF7035E_467FCA4701F9_var* //#UC END# *4C6CECF7035E_467FCA4701F9_var* begin //#UC START# *4C6CECF7035E_467FCA4701F9_impl* //#UC END# *4C6CECF7035E_467FCA4701F9_impl* end;//TnsBaseTagNode.ChildInserted procedure TnsBaseTagNode.CheckChildDelete(anIndex: Integer; const aChild: Ik2Tag); //#UC START# *4C6CED10018F_467FCA4701F9_var* //#UC END# *4C6CED10018F_467FCA4701F9_var* begin //#UC START# *4C6CED10018F_467FCA4701F9_impl* //#UC END# *4C6CED10018F_467FCA4701F9_impl* end;//TnsBaseTagNode.CheckChildDelete procedure TnsBaseTagNode.DoInsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op); //#UC START# *4C6CED28025A_467FCA4701F9_var* //#UC END# *4C6CED28025A_467FCA4701F9_var* begin //#UC START# *4C6CED28025A_467FCA4701F9_impl* BaseInsertChild(anIndex, aChild, aContext); //#UC END# *4C6CED28025A_467FCA4701F9_impl* end;//TnsBaseTagNode.DoInsertChild function TnsBaseTagNode.DoDeleteChild(anIndex: Integer; const aContext: Ik2Op): Boolean; //#UC START# *4C6CED4C009B_467FCA4701F9_var* //#UC END# *4C6CED4C009B_467FCA4701F9_var* begin //#UC START# *4C6CED4C009B_467FCA4701F9_impl* Result := BaseDeleteChild(anIndex, aContext); //#UC END# *4C6CED4C009B_467FCA4701F9_impl* end;//TnsBaseTagNode.DoDeleteChild function TnsBaseTagNode.DeleteChildPrim(anIndex: Integer; const aChild: Ik2Tag; const aContext: Ik2Op): Boolean; //#UC START# *4C6CE735026E_467FCA4701F9_var* //#UC END# *4C6CE735026E_467FCA4701F9_var* begin //#UC START# *4C6CE735026E_467FCA4701F9_impl* CheckChildDelete(anIndex, aChild); Result := DoDeleteChild(anIndex, aContext); //#UC END# *4C6CE735026E_467FCA4701F9_impl* end;//TnsBaseTagNode.DeleteChildPrim function TnsBaseTagNode.AddChild(var aChild: Ik2Tag; const aContext: Ik2Op = nil): Integer; //#UC START# *4C6CE8F703AD_467FCA4701F9_var* //#UC END# *4C6CE8F703AD_467FCA4701F9_var* begin //#UC START# *4C6CE8F703AD_467FCA4701F9_impl* Result := inherited AddChild(aChild, aContext); ChildInserted(aChild, aContext); //#UC END# *4C6CE8F703AD_467FCA4701F9_impl* end;//TnsBaseTagNode.AddChild procedure TnsBaseTagNode.InsertChild(anIndex: Integer; var aChild: Ik2Tag; const aContext: Ik2Op = nil); //#UC START# *4C6CE91903A5_467FCA4701F9_var* //#UC END# *4C6CE91903A5_467FCA4701F9_var* begin //#UC START# *4C6CE91903A5_467FCA4701F9_impl* DoInsertChild(anIndex, aChild, aContext); ChildInserted(aChild, aContext); //#UC END# *4C6CE91903A5_467FCA4701F9_impl* end;//TnsBaseTagNode.InsertChild end.
program ejercicioPractico1; const Df = 2400; // alumnos type str40 = String[40]; alumno = record apellido : str40; dni : Integer; cantCursadasAprobadas : Integer; cantFinalesAprobados : Integer; notaPromedio : Real; end; procedure leerAlumno(var a:alumno); begin with a do begin write('Ingrese APELLIDO: '); readln(apellido); write('ingrese DNI: '); readln(dni); write('Ingrese cantidad DE CURSADAS APROBADAS: '); readln(cantCursadasAprobadas); write('ingrese cantidad de FINALES APROBADOS: '); readln(cantFinalesAprobados); write('Ingrese NOTA PROMEDIO: '); readln(notaPromedio); end; end; procedure alDia(a:alumno; var aldia: Integer); begin aldia:= (a.cantFinalesAprobados * 100) / cantCursadasAprobadas; end; procedure mejoresPromedios(a:alumno; var max1, max2: Real; var dniMax1, dniMax2: Integer); begin if (a.notaPromedio >= max1) then begin max2:= max1; dniMax2:= dniMax1; max1:= a.notaPromedio; dniMax1:= a.dni; end else if (a.notaPromedio >=max2) then begin max2:= a.notaPromedio; dniMax2:= a.dni; end; end; var a: alumno; max1,max2, sumaPromedio, promedio:Real; dniMax1, dniMax2,contalumnosAlDia, aldia: Integer; begin contalumnosAlDia:= 0; sumaPromedio:= 0; max1:= -1; max2:= -1; dniMax1:= 0; dniMax2:= 0; for i := 1 to Df do begin leerAlumno(a); sumaPromedio:= sumaPromedio + a.notaPromedio; alDia(a, aldia); if (aldia >= 70) then begin contalumnosAlDia := contalumnosAlDia + 1; end; mejoresPromedios(a,max1,max2,dniMax1,dniMax2); end; writeln('La cantidad de alumnos considerado al dia son: ', contalumnosAlDia); writeln('El proemdio general de todo los alumnos es: ', promedio:= sumaPromedio div Df); writeln('Los dos DNI mejroes promedio son: ', dniMax1, ' y ', dniMax2); end.
unit UStore; interface uses Classes, FileScanner, UGitIgnore; type TFileInfoSaver = class(TObject) private FBasePath : string; FScanner : TFileScanner; FIgnoreList : TGitIgnore; FList : TStrings; FTzBias : Integer; procedure FoundHandler(Sender:TObject; const FileInformation:TFileInformation); public DestFile : string; constructor Create(ignorelist:TGitIgnore); destructor Destroy;override; procedure ScanDir(const dir:string); end; implementation uses Windows, SysUtils, ISO8601; { TFileInfoSaver } constructor TFileInfoSaver.Create(ignorelist:TGitIgnore); var tzi : TTimeZoneInformation; begin inherited Create; FIgnoreList := ignorelist; FScanner := TFileScanner.Create; FScanner.OnFound := FoundHandler; FScanner.Recursive := True; FList := TStringlist.Create; GetTimeZoneInformation(tzi); FTzBias := tzi.Bias; end; destructor TFileInfoSaver.Destroy; begin FList.Free; FScanner.Free; inherited; end; procedure TFileInfoSaver.FoundHandler(Sender:TObject; const FileInformation:TFileInformation); var relpath : string; s : string; begin if FileInformation.IsDir then begin if ExtractFileName(ExcludeTrailingBackslash(FileInformation.Path)) = '.git' then begin (Sender as TFileScanner).StopDirectory; Exit; end; relpath := ExtractRelativePath(FBasepath, FileInformation.Path); FList.Add('['+relpath+']'); Exit; end; if FIgnoreList.MatchPattern(FileInformation.Name) then Exit; s := FileInformation.Name+ '|'+ ISO8601DateTimeToStr(FileInformation.LastWrite); FList.Add(s); end; procedure TFileInfoSaver.ScanDir(const dir:string); begin FBasePath := dir; FList.Add('V2.0'); FScanner.ScanDir(dir, True); FList.SaveToFile(DestFile); end; end.
unit SearchVendorsUnit; interface uses SysUtils, Classes, BaseExampleUnit, EnumsUnit; type TSearchVendors = class(TBaseExample) public procedure Execute(Size: TVendorSizeType; IsIntegrated: Boolean; Feature, Country, Search: String; Page, PerPage: Integer); end; implementation uses NullableBasicTypesUnit, VendorUnit; procedure TSearchVendors.Execute(Size: TVendorSizeType; IsIntegrated: Boolean; Feature, Country, Search: String; Page, PerPage: Integer); var ErrorString: String; Vendors: TVendorList; begin Vendors := Route4MeManager.Telematics.Search(Size, IsIntegrated, Feature, Country, Search, Page, PerPage, ErrorString); try WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('SearchVendors successfully'); WriteLn(''); end else WriteLn(Format('SearchVendors error: "%s"', [ErrorString])); finally FreeAndNil(Vendors); end; end; end.
unit pirates_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, sound_engine,oki6295,misc_functions; function iniciar_pirates:boolean; implementation const //Pirates pirates_rom:array[0..1] of tipo_roms=( (n:'r_449b.bin';l:$80000;p:0;crc:$224aeeda),(n:'l_5c1e.bin';l:$80000;p:$1;crc:$46740204)); pirates_gfx:array[0..3] of tipo_roms=( (n:'p4_4d48.bin';l:$80000;p:0;crc:$89fda216),(n:'p2_5d74.bin';l:$80000;p:$80000;crc:$40e069b4), (n:'p1_7b30.bin';l:$80000;p:$100000;crc:$26d78518),(n:'p8_9f4f.bin';l:$80000;p:$180000;crc:$f31696ea)); pirates_sprites:array[0..3] of tipo_roms=( (n:'s1_6e89.bin';l:$80000;p:0;crc:$c78a276f),(n:'s2_6df3.bin';l:$80000;p:$80000;crc:$9f0bad96), (n:'s4_fdcc.bin';l:$80000;p:$100000;crc:$8916ddb5),(n:'s8_4b7c.bin';l:$80000;p:$180000;crc:$1c41bd2c)); pirates_oki:tipo_roms=(n:'s89_49d4.bin';l:$80000;p:0;crc:$63a739ec); //Genix Family genix_rom:array[0..1] of tipo_roms=( (n:'1.15';l:$80000;p:0;crc:$d26abfb0),(n:'2.16';l:$80000;p:$1;crc:$a14a25b4)); genix_gfx:array[0..3] of tipo_roms=( (n:'7.34';l:$40000;p:0;crc:$58da8aac),(n:'9.35';l:$40000;p:$80000;crc:$96bad9a8), (n:'8.48';l:$40000;p:$100000;crc:$0ddc58b6),(n:'10.49';l:$40000;p:$180000;crc:$2be308c5)); genix_sprites:array[0..3] of tipo_roms=( (n:'6.69';l:$40000;p:0;crc:$b8422af7),(n:'5.70';l:$40000;p:$80000;crc:$e46125c5), (n:'4.71';l:$40000;p:$100000;crc:$7a8ed21b),(n:'3.72';l:$40000;p:$180000;crc:$f78bd6ca)); genix_oki:tipo_roms=(n:'0.31';l:$80000;p:0;crc:$80d087bc); var rom:array[0..$7ffff] of word; sound_rom:array[0..1,0..$3ffff] of byte; ram1:array[0..$7ffff] of word; ram2:array[0..$3fff] of word; sprite_ram:array[0..$7ff] of word; scroll_x:word; procedure update_video_pirates; var f,x,y,nchar,color:word; procedure draw_sprites; var f,nchar,color,atrib,sx,sy:word; flip_x,flip_y:boolean; begin for f:=0 to $1fd do begin sy:=sprite_ram[3+(f*4)]; // indeed... if (sy and $8000)<>0 then exit; // end-of-list marker */ sx:=sprite_ram[5+(f*4)]-32; atrib:=sprite_ram[6+(f*4)]; nchar:=atrib shr 2; color:=sprite_ram[4+(f*4)] and $ff; flip_x:=(atrib and 2)<>0; flip_y:=(atrib and 1)<>0; sy:=$f2-sy; put_gfx_sprite(nchar,(color shl 4)+$1800,flip_x,flip_y,1); actualiza_gfx_sprite(sx,sy,4,1); end; end; begin for f:=$0 to $47f do begin x:=f div 32; y:=f mod 32; //txt color:=ram2[$c1+(f*2)] and $1ff; if ((gfx[0].buffer[f]) or (buffer_color[color])) then begin nchar:=ram2[$c0+(f*2)]; put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0); gfx[0].buffer[f]:=false; end; end; for f:=$0 to $7ff do begin x:=f div 32; y:=f mod 32; //bg color:=ram2[$1541+(f*2)] and $1ff; if ((gfx[0].buffer[f+$480]) or (buffer_color[color+$100])) then begin nchar:=ram2[$1540+(f*2)]; put_gfx(x*8,y*8,nchar,(color+$100) shl 4,2,0); gfx[0].buffer[f+$480]:=false; end; //fg color:=ram2[$9c1+(f*2)] and $1ff; if ((gfx[0].buffer[f+$c80]) or (buffer_color[color+$80])) then begin nchar:=ram2[$9c0+(f*2)]; put_gfx_trans(x*8,y*8,nchar,(color+$80) shl 4,3,0); gfx[0].buffer[f+$c80]:=false; end; end; scroll__x(2,4,scroll_x); scroll__x(3,4,scroll_x); draw_sprites; actualiza_trozo(0,0,288,256,1,0,0,288,256,4); actualiza_trozo_final(0,16,288,224,4); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_pirates; begin if event.arcade then begin //input if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $0001); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $0002); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or $0004); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or $0008); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $0010); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $0020); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $0040); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $0080); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $feff) else marcade.in1:=(marcade.in1 or $0100); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fdff) else marcade.in1:=(marcade.in1 or $0200); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fbff) else marcade.in1:=(marcade.in1 or $0400); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $f7ff) else marcade.in1:=(marcade.in1 or $0800); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000); if arcade_input.but3[1] then marcade.in1:=(marcade.in1 and $bfff) else marcade.in1:=(marcade.in1 or $4000); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7fff) else marcade.in1:=(marcade.in1 or $8000); //system if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); end; end; procedure pirates_principal; var frame_m:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; if (f=239) then begin m68000_0.irq[1]:=HOLD_LINE; update_video_pirates; end; end; eventos_pirates; video_sync; end; end; function pirates_getword(direccion:dword):word; begin case direccion of 0..$fffff:pirates_getword:=rom[direccion shr 1]; $100000..$10ffff:pirates_getword:=ram1[(direccion and $ffff) shr 1]; $300000:pirates_getword:=marcade.in1; $400000:pirates_getword:=marcade.in0; $500000..$500fff:pirates_getword:=sprite_ram[(direccion and $fff) shr 1]; $800000..$803fff:pirates_getword:=buffer_paleta[(direccion and $3fff) shr 1]; $900000..$907fff:pirates_getword:=ram2[(direccion and $7fff) shr 1]; $a00000:pirates_getword:=oki_6295_0.read; end; end; procedure pirates_putword(direccion:dword;valor:word); procedure cambiar_color(pos,data:word); var color:tcolor; begin color.r:=pal5bit(data shr 10); color.g:=pal5bit((data shr 5) and $1f); color.b:=pal5bit(data); set_pal_color(color,pos); buffer_color[pos shr 4]:=true; end; begin case direccion of 0..$fffff:; $100000..$10ffff:ram1[(direccion and $ffff) shr 1]:=valor; $500000..$500fff:sprite_ram[(direccion and $fff) shr 1]:=valor; $600000:begin //eeprom missing copymemory(oki_6295_0.get_rom_addr,@sound_rom[(valor and $40) shr 6,0],$40000); end; $700000:scroll_x:=valor and $1ff; $800000..$803fff:if buffer_paleta[(direccion and $3fff) shr 1]<>valor then begin buffer_paleta[(direccion and $3fff) shr 1]:=valor; cambiar_color((direccion and $3fff) shr 1,valor); end; $900000..$907fff:begin ram2[(direccion and $7fff) shr 1]:=valor; case (direccion and $7fff) of $180..$137f:gfx[0].buffer[((direccion and $7fff)-$180) shr 2]:=true; $1380..$2a7f:gfx[0].buffer[$c80+(((direccion and $7fff)-$1380) shr 2)]:=true; $2a80..$4187:gfx[0].buffer[$480+(((direccion and $7fff)-$2a80) shr 2)]:=true; end; end; $a00000:oki_6295_0.write(valor and $ff) end; end; procedure pirates_sound_update; begin oki_6295_0.update; end; function genix_getword(direccion:dword):word; begin case direccion of 0..$fffff:genix_getword:=rom[direccion shr 1]; $100000..$10ffff:case (direccion and $ffff) of $9e98:genix_getword:=4; //proteccion $9e99..$9e9b:genix_getword:=0; //proteccion else genix_getword:=ram1[(direccion and $ffff) shr 1]; end; $300000:genix_getword:=marcade.in1; $400000:genix_getword:=marcade.in0; $500000..$500fff:genix_getword:=sprite_ram[(direccion and $fff) shr 1]; $800000..$803fff:genix_getword:=buffer_paleta[(direccion and $3fff) shr 1]; $900000..$907fff:genix_getword:=ram2[(direccion and $7fff) shr 1]; $a00000:genix_getword:=oki_6295_0.read; end; end; //Main procedure reset_pirates; begin m68000_0.reset; oki_6295_0.reset; reset_audio; marcade.in0:=$9f; marcade.in1:=$ffff; end; function iniciar_pirates:boolean; var ptempw:pword; ptempb,ptempb2:pbyte; procedure decr_and_load_oki; var f,adrr:dword; ptempb3,ptempb4:pbyte; begin ptempb3:=ptempb; for f:=0 to $7ffff do begin adrr:=BITSWAP24(f,23,22,21,20,19,10,16,13,8,4,7,11,14,17,12,6,2,0,5,18,15,3,1,9); ptempb4:=ptempb2; inc(ptempb4,adrr); ptempb4^:=BITSWAP8(ptempb3^,2,3,4,0,7,5,1,6); inc(ptempb3); end; copymemory(@sound_rom[0,0],ptempb2,$40000); ptempb3:=ptempb2; inc(ptempb3,$40000); copymemory(@sound_rom[1,0],ptempb3,$40000); end; procedure decr_and_load_rom; var ptempw2:pword; f,adrl,adrr:dword; vl,vr:byte; begin for f:=0 to $7ffff do begin ptempw2:=ptempw; adrl:=BITSWAP24(f,23,22,21,20,19,18,4,8,3,14,2,15,17,0,9,13,10,5,16,7,12,6,1,11); inc(ptempw2,adrl); vl:=BITSWAP8(ptempw2^ and $ff,4,2,7,1,6,5,0,3); ptempw2:=ptempw; adrr:=BITSWAP24(f,23,22,21,20,19,18,4,10,1,11,12,5,9,17,14,0,13,6,15,8,3,16,7,2); inc(ptempw2,adrr); vr:=BITSWAP8(ptempw2^ shr 8,1,4,7,0,3,5,6,2); rom[f]:=(vr shl 8) or vl; end; end; procedure decr_and_load_gfx; const pt_x:array[0..7] of dword=(7, 6, 5, 4, 3, 2, 1, 0); pt_y:array[0..7] of dword=(8*0, 8*1, 8*2, 8*3, 8*4, 8*5, 8*6, 8*7); var f,adrr:dword; ptempb3,ptempb4:pbyte; begin for f:=0 to $7ffff do begin adrr:=BITSWAP24(f,23,22,21,20,19,18,10,2,5,9,7,13,16,14,11,4,1,6,12,17,3,0,15,8); ptempb3:=ptempb2;inc(ptempb3,adrr); ptempb4:=ptempb;inc(ptempb4,f); ptempb3^:=BITSWAP8(ptempb4^,2,3,4,0,7,5,1,6); ptempb3:=ptempb2;inc(ptempb3,adrr+$80000); ptempb4:=ptempb;inc(ptempb4,f+$80000); ptempb3^:= BITSWAP8(ptempb4^,4,2,7,1,6,5,0,3); ptempb3:=ptempb2;inc(ptempb3,adrr+$100000); ptempb4:=ptempb;inc(ptempb4,f+$100000); ptempb3^:= BITSWAP8(ptempb4^,1,4,7,0,3,5,6,2); ptempb3:=ptempb2;inc(ptempb3,adrr+$180000); ptempb4:=ptempb;inc(ptempb4,f+$180000); ptempb3^:= BITSWAP8(ptempb4^,2,3,4,0,7,5,1,6); end; init_gfx(0,8,8,$10000); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,8*8,$180000*8,$100000*8,$80000*8,0); convert_gfx(0,0,ptempb2,@pt_x[0],@pt_y[0],false,false); end; procedure decr_and_load_sprites; const ps_x:array[0..15] of dword=(7, 6, 5, 4, 3, 2, 1, 0, 15,14,13,12,11,10, 9, 8); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16,10*16,11*16,12*16,13*16,14*16,15*16); var f,adrr:dword; ptempb3,ptempb4:pbyte; begin for f:=0 to $7ffff do begin adrr:=BITSWAP24(f,23,22,21,20,19,18,17,5,12,14,8,3,0,7,9,16,4,2,6,11,13,1,10,15); ptempb3:=ptempb2;inc(ptempb3,adrr); ptempb4:=ptempb;inc(ptempb4,f); ptempb3^:=BITSWAP8(ptempb4^,4,2,7,1,6,5,0,3); ptempb3:=ptempb2;inc(ptempb3,adrr+$80000); ptempb4:=ptempb;inc(ptempb4,f+$80000); ptempb3^:= BITSWAP8(ptempb4^,1,4,7,0,3,5,6,2); ptempb3:=ptempb2;inc(ptempb3,adrr+$100000); ptempb4:=ptempb;inc(ptempb4,f+$100000); ptempb3^:= BITSWAP8(ptempb4^,2,3,4,0,7,5,1,6); ptempb3:=ptempb2;inc(ptempb3,adrr+$180000); ptempb4:=ptempb;inc(ptempb4,f+$180000); ptempb3^:= BITSWAP8(ptempb4^,4,2,7,1,6,5,0,3); end; init_gfx(1,16,16,$4000); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,16*16,$180000*8,$100000*8,$80000*8,0); convert_gfx(1,0,ptempb2,@ps_x[0],@ps_y[0],false,false); end; begin llamadas_maquina.bucle_general:=pirates_principal; llamadas_maquina.reset:=reset_pirates; iniciar_pirates:=false; iniciar_audio(false); //Pantallas screen_init(1,288,256,true); screen_init(2,512,256,true); screen_mod_scroll(2,512,512,511,256,256,255); screen_init(3,512,256,true); screen_mod_scroll(3,512,512,511,256,256,255); screen_init(4,512,256,false,true); iniciar_video(288,224); //Main CPU m68000_0:=cpu_m68000.create(16000000,256); m68000_0.init_sound(pirates_sound_update); //sound oki_6295_0:=snd_okim6295.Create(1333333,OKIM6295_PIN7_LOW); getmem(ptempb,$200000); getmem(ptempb2,$200000); case main_vars.tipo_maquina of 206:begin //Pirates m68000_0.change_ram16_calls(pirates_getword,pirates_putword); //OKI snd if not(roms_load(ptempb,pirates_oki)) then exit; decr_and_load_oki; //cargar roms getmem(ptempw,$100000); if not(roms_load16w(ptempw,pirates_rom)) then exit; decr_and_load_rom; freemem(ptempw); //Protection patch rom[$62c0 shr 1]:=$6006; //cargar gfx if not(roms_load(ptempb,pirates_gfx)) then exit; decr_and_load_gfx; //sprites if not(roms_load(ptempb,pirates_sprites)) then exit; decr_and_load_sprites; end; 207:begin //Genix Family m68000_0.change_ram16_calls(genix_getword,pirates_putword); //OKI snd if not(roms_load(ptempb,genix_oki)) then exit; decr_and_load_oki; //cargar roms getmem(ptempw,$100000); if not(roms_load16w(ptempw,genix_rom)) then exit; decr_and_load_rom; freemem(ptempw); //cargar gfx if not(roms_load(ptempb,genix_gfx)) then exit; decr_and_load_gfx; //sprites if not(roms_load(ptempb,genix_sprites)) then exit; decr_and_load_sprites; end; end; freemem(ptempb); freemem(ptempb2); //final reset_pirates; iniciar_pirates:=true; end; end.
unit fmWorkstations; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ADC.Types; type TForm_Workstations = class(TForm) Label_Hint: TLabel; Label_Choice: TLabel; GroupBox_Workstation: TGroupBox; Label_ComputerName: TLabel; Edit_Workstation: TEdit; Button_Add: TButton; Button_Change: TButton; ListBox_Workstations: TListBox; Button_Delete: TButton; RadioButton_All: TRadioButton; RadioButton_Listed: TRadioButton; Button_Cancel: TButton; Button_OK: TButton; procedure Button_CancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button_ChangeClick(Sender: TObject); procedure ListBox_WorkstationsClick(Sender: TObject); procedure Edit_WorkstationKeyPress(Sender: TObject; var Key: Char); procedure Button_AddClick(Sender: TObject); procedure Edit_WorkstationChange(Sender: TObject); procedure RadioButton_AllClick(Sender: TObject); procedure RadioButton_ListedClick(Sender: TObject); procedure Button_DeleteClick(Sender: TObject); procedure Button_OKClick(Sender: TObject); private FCallingForm: TForm; FInPlaceEdit: TEdit; FOnApply: TApplyWorkstationsProc; procedure SetCallingForm(const Value: TForm); procedure SetWorkstations(const Value: string); procedure OnInPlaceEditKeyPress(Sender: TObject; var Key: Char); procedure OnInPlaceEditExit(Sender: TObject); public property CallingForm: TForm write SetCallingForm; property Workstations: string write SetWorkstations; property OnApply: TApplyWorkstationsProc read FOnApply write FOnApply; end; var Form_Workstations: TForm_Workstations; implementation {$R *.dfm} { TForm_Workstations } procedure TForm_Workstations.Button_AddClick(Sender: TObject); begin if (Edit_Workstation.Text <> '') and (ListBox_Workstations.Items.IndexOf(Edit_Workstation.Text) = -1) then ListBox_Workstations.Items.Add(Edit_Workstation.Text); Edit_Workstation.Text := ''; Edit_Workstation.SetFocus; end; procedure TForm_Workstations.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_Workstations.Button_ChangeClick(Sender: TObject); var LRect: TRect; begin LRect := ListBox_Workstations.ItemRect(ListBox_Workstations.ItemIndex); {Set the size of the TEdit} FInPlaceEdit.Top := LRect.Top; FInPlaceEdit.Left := LRect.Left + 1; FInPlaceEdit.Width := 150; //ListBox1.Canvas.TextWidth(ListBox1.Items.Strings[ListBox1.ItemIndex]) + 6; FInPlaceEdit.Height := (LRect.Bottom - LRect.Top); FInPlaceEdit.Text := ListBox_Workstations.Items.Strings[ListBox_Workstations.ItemIndex]; FInPlaceEdit.Visible := True; FInPlaceEdit.SelectAll; FInPlaceEdit.SetFocus; end; procedure TForm_Workstations.Button_DeleteClick(Sender: TObject); var i: Integer; begin i := ListBox_Workstations.ItemIndex; ListBox_Workstations.DeleteSelected; if ListBox_Workstations.Items.Count - 1 >= i then ListBox_Workstations.ItemIndex := i else if ListBox_Workstations.Items.Count > 0 then ListBox_Workstations.ItemIndex := i - 1; Button_Change.Enabled := ListBox_Workstations.ItemIndex > -1; Button_Delete.Enabled := ListBox_Workstations.ItemIndex > -1; end; procedure TForm_Workstations.Button_OKClick(Sender: TObject); begin if Assigned(FOnApply) then if RadioButton_All.Checked then FOnApply(Self, '') else FOnApply(Self, ListBox_Workstations.Items.CommaText); Close; end; procedure TForm_Workstations.Edit_WorkstationChange(Sender: TObject); begin Button_Add.Enabled := Edit_Workstation.Text <> ''; end; procedure TForm_Workstations.Edit_WorkstationKeyPress(Sender: TObject; var Key: Char); begin if (Edit_Workstation.Text <> '') and (Key = #13) then begin Button_AddClick(Self); Key := #0; end; end; procedure TForm_Workstations.FormClose(Sender: TObject; var Action: TCloseAction); begin RadioButton_All.Checked := True; Edit_Workstation.Clear; ListBox_Workstations.Clear; ListBox_WorkstationsClick(Self); FOnApply := nil; if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; end; procedure TForm_Workstations.FormCreate(Sender: TObject); begin RadioButton_All.Checked := True; FInPlaceEdit := TEdit.Create(nil); with FInPlaceEdit do begin Parent := ListBox_Workstations; Ctl3D := False; Visible := False; OnKeyPress := OnInPlaceEditKeyPress; OnExit := OnInPlaceEditExit; end; end; procedure TForm_Workstations.FormDestroy(Sender: TObject); begin FInPlaceEdit.Free; end; procedure TForm_Workstations.ListBox_WorkstationsClick(Sender: TObject); begin Button_Change.Enabled := ListBox_Workstations.ItemIndex > -1; Button_Delete.Enabled := ListBox_Workstations.ItemIndex > -1; end; procedure TForm_Workstations.OnInPlaceEditExit(Sender: TObject); var Key: Char; begin Key := #13; OnInPlaceEditKeyPress(Self, Key); end; procedure TForm_Workstations.OnInPlaceEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin ListBox_Workstations.Items[ListBox_Workstations.ItemIndex] := FInPlaceEdit.Text; FInPlaceEdit.Hide; Key := #0; end; end; procedure TForm_Workstations.RadioButton_AllClick(Sender: TObject); var i: Integer; begin for i := 0 to GroupBox_Workstation.ControlCount - 1 do GroupBox_Workstation.Controls[i].Enabled := False; Edit_Workstation.Color := clBtnFace; ListBox_Workstations.Color := clBtnFace; end; procedure TForm_Workstations.RadioButton_ListedClick(Sender: TObject); var i: Integer; begin for i := 0 to GroupBox_Workstation.ControlCount - 1 do GroupBox_Workstation.Controls[i].Enabled := True; Edit_Workstation.Color := clWindow; ListBox_Workstations.Color := clWindow; Edit_WorkstationChange(Self); ListBox_WorkstationsClick(Self); end; procedure TForm_Workstations.SetCallingForm(const Value: TForm); begin FCallingForm := Value; if FCallingForm <> nil then FCallingForm.Enabled := False; end; procedure TForm_Workstations.SetWorkstations(const Value: string); begin ListBox_Workstations.Clear; ListBox_Workstations.Items.CommaText := Value; if ListBox_Workstations.Items.Count = 0 then RadioButton_All.Checked := True else RadioButton_Listed.Checked := True end; end.
unit MetaInstances; interface uses ClassStorageInt, Classes, Languages {$IFNDEF CLIENT} , CacheAgent; {$ELSE} ; {$ENDIF} type // MetaIntances are objects to be collected in the ClassStorage. They act as // classes of other objects. Important features: // Id : string // Class Identifier (must be unique withing one class family). // Register( ClassFamily ) // Registers the MetaInstance in the class storage as [ClassFamily, Id] TMetaInstance = class public constructor Create( anId : string ); private fId : string; fFamily : string; fIndex : integer; fCacheable : boolean; published property Id : string read fId; property Family : string read fFamily; property Index : integer read fIndex; property Cacheable : boolean read fCacheable write fCacheable; public procedure RetrieveTexts( Container : TDictionary ); virtual; procedure StoreTexts ( Container : TDictionary ); virtual; procedure EvaluateTexts; virtual; procedure CloneTexts; virtual; public procedure Register( ClassFamily : TClassFamilyId ); end; function ObjectIs( ClassName : string; O : TObject ) : boolean; function ClassIs( ClassName : string; C : TClass ) : boolean; {$IFNDEF CLIENT} procedure CacheFamily( Family : string ); procedure CloneFamily( Family : string ); {$ENDIF} procedure RetrieveTexts( filename : string ); procedure StoreTexts( Family : string; filename : string ); procedure StoreMissingTexts( Family : string; filename, LangId : string ); procedure EvaluateTexts( Family : string ); implementation uses ClassStorage {$IFNDEF CLIENT} , ModelServerCache; {$ELSE} ; {$ENDIF} // TMetaInstance constructor TMetaInstance.Create( anId : string ); begin inherited Create; fId := anId; fCacheable := false; end; procedure TMetaInstance.RetrieveTexts( Container : TDictionary ); begin end; procedure TMetaInstance.StoreTexts( Container : TDictionary ); begin end; procedure TMetaInstance.EvaluateTexts; begin end; procedure TMetaInstance.CloneTexts; begin end; procedure TMetaInstance.Register( ClassFamily : TClassFamilyId ); begin fFamily := ClassFamily; TheClassStorage.RegisterClass( ClassFamily, fId, self ); fIndex := TheClassStorage.ClassCount[ClassFamily]; { if Cacheable then CacheMetaObject( self, noKind, noInfo ); } end; // ObjectIs function ObjectIs( ClassName : string; O : TObject ) : boolean; var SuperClass : TClass; begin try SuperClass := O.ClassType; while (SuperClass <> nil) and (SuperClass.ClassName <> ClassName) do SuperClass := SuperClass.ClassParent; result := (SuperClass <> nil); except result := false; end; end; // ClassIs function ClassIs( ClassName : string; C : TClass ) : boolean; var SuperClass : TClass; begin try SuperClass := C; while (SuperClass <> nil) and (SuperClass.ClassName <> ClassName) do SuperClass := SuperClass.ClassParent; result := (SuperClass <> nil); except result := false; end; end; {$IFNDEF CLIENT} // CacheFamily procedure CacheFamily( Family : string ); var count : integer; i : integer; begin count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try if TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).Cacheable then CacheMetaObject( TheClassStorage.ClassByIdx[Family, i], noKind, noInfo ); except end; end; //CloneFamily procedure CloneFamily( Family : string ); var count : integer; i : integer; begin count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).CloneTexts; except end; end; {$ENDIF} procedure RetrieveTexts( filename : string ); var Dict : TDictionary; Family : string; count : integer; i : integer; begin Dict := TDictionary.Create( filename ); try Family := Dict.Values['Target']; if Family <> '' then begin count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).RetrieveTexts( Dict ); except end; end; finally Dict.Free; end; end; procedure StoreTexts( Family : string; filename : string ); var Dict : TDictionary; count : integer; i : integer; begin Dict := TDictionary.Create( '' ); try count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).StoreTexts( Dict ); except end; Dict.Store( filename ); finally Dict.Free; end; end; procedure StoreMissingTexts( Family : string; filename, LangId : string ); var Dict : TDictionary; count : integer; i : integer; begin Dict := TDictionary.Create( '' ); Dict.LangId := LangId; try count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).StoreTexts( Dict ); except end; Dict.Store( filename ); finally Dict.Free; end; end; procedure EvaluateTexts( Family : string ); var count : integer; i : integer; begin count := TheClassStorage.ClassCount[Family]; for i := 0 to pred(count) do try TMetaInstance(TheClassStorage.ClassByIdx[Family, i]).EvaluateTexts; except end; end; end.
unit vcmBaseOperationsCollection; {* Коллекция операций. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmBaseOperationsCollection - } { Начат: 19.11.2003 13:15 } { $Id: vcmBaseOperationsCollection.pas,v 1.27 2011/07/29 15:08:37 lulin Exp $ } // $Log: vcmBaseOperationsCollection.pas,v $ // Revision 1.27 2011/07/29 15:08:37 lulin // {RequestLink:209585097}. // // Revision 1.26 2009/11/12 18:07:34 lulin // - убираем ненужные возвращаемые значения. // // Revision 1.25 2009/10/12 11:27:15 lulin // - коммитим после падения CVS. // // Revision 1.25 2009/10/08 12:46:44 lulin // - чистка кода. // // Revision 1.24 2009/09/17 09:47:24 lulin // - операции модуля публикуем в run-time, а не в формах. // // Revision 1.23 2009/08/28 17:15:47 lulin // - начинаем публикацию и описание внутренних операций. // // Revision 1.22 2009/08/06 13:27:16 lulin // {RequestLink:129240934}. №26. // // Revision 1.21 2009/08/04 08:35:42 lulin // - поправлен комментарий. // // Revision 1.20 2009/08/03 18:12:37 lulin // - публикуем операции. // // Revision 1.19 2009/02/20 15:19:00 lulin // - <K>: 136941122. // // Revision 1.18 2009/02/11 15:19:45 lulin // - чистка кода. // // Revision 1.17 2009/02/04 15:33:55 lulin // - исправляем ошибку ненахождения методов. http://mdp.garant.ru/pages/viewpage.action?pageId=136260278&focusedCommentId=136260289#comment-136260289 // // Revision 1.16 2007/01/20 17:35:45 lulin // - разрешаем вызывать операции только по заранее известным идентификаторам. // // Revision 1.15 2005/02/02 12:53:55 am // change: правки, связанные с переделками TvcmBaseOperationCollectionItem._Handled() // // Revision 1.14 2005/01/27 13:43:28 lulin // - bug fix: не все контролы отвязывались от операций (CQ OIT5-11924). // // Revision 1.13 2005/01/21 11:24:10 lulin // - переименовал метод, чтобы название более соответствовало смыслу. // // Revision 1.12 2005/01/21 11:10:05 lulin // - new behavior: не сохраняем операции, привязанные только к контролам. // // Revision 1.11 2004/11/25 10:44:11 lulin // - rename type: _TvcmExecuteEvent -> TvcmControlExecuteEvent. // - rename type: _TvcmTestEvent -> TvcmControlTestEvent. // - new type: TvcmControlGetTargetEvent. // // Revision 1.10 2004/11/25 09:08:31 lulin // - new behavior: - по-умолчанию показываем операции контролов только в контекстном меню. // // Revision 1.9 2004/11/24 12:35:55 lulin // - new behavior: обработчики операций от контролов теперь привязываются к операциям. // // Revision 1.8 2004/11/18 16:29:55 lulin // - отвязываем библиотеки от VCM без использования inc'ов. // // Revision 1.7 2004/09/27 16:26:25 lulin // - new behavior: в редакторе свойств для сущностей и операций показываем дополнительные параметры. // // Revision 1.6 2004/09/22 06:12:34 lulin // - оптимизация - методу TvcmBaseCollection.FindItemByID придана память о последнем найденном элементе. // // Revision 1.5 2004/09/22 05:41:24 lulin // - оптимизация - убраны код и данные, не используемые в Run-Time. // // Revision 1.4 2004/09/10 14:04:04 lulin // - оптимизация - кешируем EntityDef и передаем ссылку на EntityItem, а не на кучу параметров. // // Revision 1.3 2004/02/26 12:09:24 nikitin75 // + присваиваем shortcut'ы в runtime; // // Revision 1.2 2003/11/24 17:35:21 law // - new method: TvcmCustomEntities._RegisterInRep. // // Revision 1.1 2003/11/19 11:38:25 law // - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано. // {$Include vcmDefine.inc } interface {$IfNDef NoVCM} uses Classes, Menus, vcmUserControls, vcmInterfaces, vcmExternalInterfaces, vcmBase, vcmBaseCollection, vcmBaseCollectionItem ; type TvcmBaseOperationsCollection = class(TvcmBaseCollection) {* Коллекция операций. } protected // internal methods function GetAttrCount: Integer; override; {-} function GetAttr(Index: Integer): string; override; {-} function GetItemAttr(Index, ItemIndex: Integer): string; override; {-} public // public methods function NeedToBeStored: Boolean; {-} class function GetItemClass: TCollectionItemClass; override; {-} procedure Operation(aControl : TComponent; const aTarget : IUnknown; const anOperationID : TvcmControlID; aMode : TvcmOperationMode; const aParams : IvcmParams); {* - выполняет операцию сущности. } procedure GetOperations(anOperations: TvcmInterfaceList); {* - возвращает список описателей операций. } procedure RegisterInRep; {-} procedure PublishOp(const aControl : TComponent; const anOperation : TvcmString; anExecute : TvcmControlExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); {* - опубликовать операцию. } procedure PublishOpWithResult(const aControl : TComponent; const anOperation : TvcmString; anExecute : TvcmExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); {* - опубликовать операцию. } procedure UnlinkControl(aControl : TComponent); {* - отвязать контрол. } end;//TvcmBaseOperationsCollection {$EndIf NoVCM} implementation {$IfNDef NoVCM} uses TypInfo, SysUtils, vcmBaseOperationsCollectionItem, vcmOperationsCollectionItem, vcmBaseMenuManager, vcmModule ; // start class TvcmBaseOperationsCollection function TvcmBaseOperationsCollection.GetAttrCount: Integer; //override; {-} begin Result := inherited GetAttrCount + 4; end; function TvcmBaseOperationsCollection.GetAttr(Index: Integer): string; //override; {-} var l_C : Integer; begin l_C := inherited GetAttrCount; if (Index >= l_C) then begin Case Index - l_C of 0 : Result := 'Caption'; 1 : Result := 'Type'; 2 : Result := 'Name'; 3 : Result := 'ShortCut'; end;//Case Index - l_C end//Index >= l_C else Result := inherited GetAttr(Index); end; function TvcmBaseOperationsCollection.GetItemAttr(Index, ItemIndex: Integer): string; //override; {-} var l_C : Integer; begin l_C := inherited GetAttrCount; if (Index > l_C) then begin Case Index - l_C of 1 : Result := GetEnumName(TypeInfo(TvcmOperationType), Ord(TvcmBaseOperationsCollectionItem(Items[ItemIndex]).OperationType)); 2 : Result := TvcmBaseOperationsCollectionItem(Items[ItemIndex]).Name; 3 : Result := ShortCutToText(TvcmBaseOperationsCollectionItem(Items[ItemIndex]).ShortCut); end;//Case Index - l_C end//Index > l_C else Result := inherited GetItemAttr(Index, ItemIndex); end; function TvcmBaseOperationsCollection.NeedToBeStored: Boolean; {-} var l_Index : Integer; begin Result := false; for l_Index := 0 to Pred(Count) do with TvcmBaseOperationsCollectionItem(Items[l_Index]) do if not (Handled([vcm_htControl]) and not Handled([vcm_htGlobal, vcm_htContext])) OR SomePropStored then begin Result := true; break; end;//..HandledOnlyByControl.. end; class function TvcmBaseOperationsCollection.GetItemClass: TCollectionItemClass; //override; {-} begin Result := TvcmBaseOperationsCollectionItem; end; procedure TvcmBaseOperationsCollection.Operation(aControl : TComponent; const aTarget : IUnknown; const anOperationID : TvcmControlID; aMode : TvcmOperationMode; const aParams : IvcmParams); {* - выполняет операцию сущности. } var l_Item : TvcmBaseOperationsCollectionItem; begin l_Item := TvcmBaseOperationsCollectionItem(FindItemByID(anOperationID)); if (l_Item <> nil) then l_Item.Operation(aControl, aTarget, aMode, aParams, false); end; procedure TvcmBaseOperationsCollection.GetOperations(anOperations: TvcmInterfaceList); {* - возвращает список описателей операций. } var l_Index : Integer; begin if (anOperations <> nil) then begin for l_Index := 0 to Pred(Count) do anOperations.Add(TvcmBaseOperationsCollectionItem(Items[l_Index]).OperationDef); end;//anOperations <> nil end; procedure TvcmBaseOperationsCollection.RegisterInRep; {-} var l_Index : Integer; l_Item : TvcmBaseOperationsCollectionItem; begin for l_Index := 0 to Pred(Count) do begin l_Item := TvcmBaseOperationsCollectionItem(Items[l_Index]); if (l_Item Is TvcmOperationsCollectionItem) then TvcmOperationsCollectionItem(l_Item).Register; end;//for l_Index end; procedure TvcmBaseOperationsCollection.PublishOp(const aControl : TComponent; const anOperation : TvcmString; anExecute : TvcmControlExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); {* - опубликовать операцию. } var l_Item : TvcmBaseOperationsCollectionItem; begin l_Item := FindItemByName(anOperation) As TvcmBaseOperationsCollectionItem; if (l_Item = nil) then begin l_Item := Add As TvcmBaseOperationsCollectionItem; l_Item.Name := anOperation; l_Item.Options := [vcm_ooShowInContextMenu]; // - по-умолчанию показываем операции только в контекстном меню if (aControl Is TvcmModule) then l_Item.Options := l_Item.Options + [vcm_ooShowInMainToolbar]; end;//l_Item = nil l_Item.PublishOp(aControl, anExecute, aTest, aGetState); end; procedure TvcmBaseOperationsCollection.PublishOpWithResult(const aControl : TComponent; const anOperation : TvcmString; anExecute : TvcmExecuteEvent; aTest : TvcmControlTestEvent; aGetState : TvcmControlGetStateEvent); //overload; {* - опубликовать операцию. } var l_Item : TvcmBaseOperationsCollectionItem; begin l_Item := FindItemByName(anOperation) As TvcmBaseOperationsCollectionItem; if (l_Item = nil) then begin l_Item := Add As TvcmBaseOperationsCollectionItem; l_Item.Name := anOperation; l_Item.Options := [vcm_ooShowInContextMenu]; // - по-умолчанию показываем операции только в контекстном меню end;//l_Item = nil l_Item.PublishOp(aControl, anExecute, aTest, aGetState); end; procedure TvcmBaseOperationsCollection.UnlinkControl(aControl : TComponent); {* - отвязать контрол. } var l_Index : Integer; begin for l_Index := 0 to Pred(Count) do TvcmBaseOperationsCollectionItem(Items[l_Index]).UnlinkControl(aControl); end; {$EndIf NoVCM} end.
unit TransferFields; interface Uses SchObject, SysUtils; Type TSchGenericField = class( TSchObject ) private __String : String; __Integer : Integer; __TDateTime : TDateTime; __Boolean : Boolean; is__String : Boolean; is__Integer : Boolean; is__TDateTime : Boolean; procedure set_asString( Value : String ); procedure set_asInteger( Value : Integer ); procedure set_asDate( Value : TDateTime ); function get_asString() : String; function get_asInteger() : Integer; function get_asDate() : TDateTime; public FieldName : String; constructor Create(); destructor Destroy(); override; function Dupe() : TSchGenericField; property isString : Boolean read is__String; property isInteger : Boolean read is__Integer; property isDate : Boolean read is__TDateTime; property asString : String read get_asString write set_asString; property asInteger : Integer read get_asInteger write set_asInteger; property asDate : TDateTime read get_asDate write set_asDate; end; TSchGenericEntry = class( TSchObject ) private fCount : Integer; fList : array of TSchGenericField; function GetField(Index: Integer): TSchGenericField; procedure SetField(Index: Integer; const Value: TSchGenericField); function GetFieldStr(Index: String): TSchGenericField; procedure SetFieldStr(Index: String; const Value: TSchGenericField); public constructor Create(); destructor Destroy(); override; function New( sName : String ) : TSchGenericField; function Dupe() : TSchGenericEntry; property Count : Integer read fCount; property Items[ Index : Integer ] : TSchGenericField read GetField write SetField; property nItems[ Index : String ] : TSchGenericField read GetFieldStr write SetFieldStr; procedure Add( Field : TSchGenericField ); end; TSchGenericEntryList = class( TSchObject ) private fCount : Integer; fList : array of TSchGenericEntry; function GetEntry(Index: Integer): TSchGenericEntry; procedure SetEntry(Index: Integer; const Value: TSchGenericEntry); public constructor Create(); destructor Destroy(); override; function RemoveEntry( Index : Integer ) : TSchGenericEntry; function Dupe() : TSchGenericEntryList; procedure ClearRefs(); property Count : Integer read fCount; property Items[ Index : Integer ] : TSchGenericEntry read GetEntry write SetEntry; procedure Add( Entry : TSchGenericEntry ); end; implementation { TSchGenericFieldList } procedure TSchGenericEntry.Add(Field: TSchGenericField); begin Inc(fCount); SetLength(fList, fCount); fList[ fCount - 1 ] := Field; end; constructor TSchGenericEntry.Create; begin fCount := 0; SetLength(fList, 0); inherited; end; destructor TSchGenericEntry.Destroy; var i : Integer; begin if fCount > 0 then for i := 0 to fCount - 1 do fList[i].Destroy(); inherited; end; function TSchGenericEntry.GetField(Index: Integer): TSchGenericField; begin if (Index < 0) or (Index >= fCount) then raise ERangeError.Create('Index out of bounds'); result := fList[ Index ]; end; function TSchGenericEntry.GetFieldStr(Index: String): TSchGenericField; var I : Integer; begin if fCount > 0 then for I := 0 to fCount - 1 do if UpperCase(GetField( I ).FieldName) = UpperCase(Index) then begin Result := GetField( I ); Exit; end; raise ERangeError.Create('Named field not found in DB Entry'); Result := nil; end; procedure TSchGenericEntry.SetFieldStr(Index: String;const Value: TSchGenericField); var I : Integer; begin if fCount > 0 then for I := 0 to fCount - 1 do if GetField( I ).FieldName = Index then begin SetField(I, Value); Exit; end; raise ERangeError.Create('Named field not found in DB Entry'); end; procedure TSchGenericEntry.SetField(Index: Integer; const Value: TSchGenericField); begin if (Index < 0) or (Index >= fCount) then raise ERangeError.Create('Index out of bounds'); fList[ Index ] := Value; end; { TSchGenericField } constructor TSchGenericField.Create; begin is__String := false; is__Integer := false; is__TDateTime := false; inherited; end; destructor TSchGenericField.Destroy; begin __String := ''; inherited; end; function TSchGenericField.get_asDate: TDateTime; begin if not is__TDateTime then raise EConvertError.Create('Invalid typecasting of the field'); result := __TDateTime; end; function TSchGenericField.get_asInteger: Integer; begin if not is__Integer then raise EConvertError.Create('Invalid typecasting of the field'); result := __Integer; end; function TSchGenericField.get_asString: String; begin if not is__String then raise EConvertError.Create('Invalid typecasting of the field'); result := __String; end; procedure TSchGenericField.set_asDate(Value: TDateTime); begin __String := ''; is__String := false; is__Integer := false; is__TDateTime := true; __TDateTime := Value; end; procedure TSchGenericField.set_asInteger(Value: Integer); begin __String := ''; is__String := false; is__Integer := true; is__TDateTime := false; __Integer := Value; __Boolean := (Value > 0); end; procedure TSchGenericField.set_asString(Value: String); begin __String := ''; is__String := true; is__Integer := false; is__TDateTime := false; __String := Value; end; function TSchGenericField.Dupe: TSchGenericField; begin Result := TSchGenericField.Create(); Result.__String := __String; Result.__Integer := __Integer; Result.__TDateTime := __TDateTime; Result.__Boolean := __Boolean; Result.is__String := is__String; Result.is__Integer := is__Integer; Result.is__TDateTime := is__TDateTime; Result.FieldName := FieldName; end; { TSchGenericEntryList } procedure TSchGenericEntryList.Add( Entry: TSchGenericEntry); begin Inc(fCount); SetLength(fList, fCount); fList[ fCount - 1 ] := Entry; end; procedure TSchGenericEntryList.ClearRefs; begin fCount := 0; SetLength( fList, 0); end; constructor TSchGenericEntryList.Create; begin fCount := 0; SetLength(fList, 0); inherited; end; destructor TSchGenericEntryList.Destroy; var i : Integer; begin if fCount > 0 then for i := 0 to fCount - 1 do fList[i].Destroy(); inherited; end; function TSchGenericEntryList.Dupe: TSchGenericEntryList; var iX : Integer; begin Result := TSchGenericEntryList.Create(); if Count > 0 then for iX := 0 to Count - 1 do begin Result.Add( Items[iX].Dupe() ); end; end; function TSchGenericEntryList.GetEntry(Index: Integer): TSchGenericEntry; begin if (Index < 0) or (Index >= fCount) then raise ERangeError.Create('Index out of bounds'); result := fList[ Index ]; end; function TSchGenericEntryList.RemoveEntry(Index: Integer): TSchGenericEntry; var i : Integer; begin if (Index < 0) or (Index >= fCount) then raise ERangeError.Create('Index out of bounds'); Result := fList[ Index ]; if Index < (fCount - 1) then for i := Index to (fCount - 2) do fList[ i ] := fList[ i + 1 ]; Dec(fCount); SetLength(fList, fCount); end; procedure TSchGenericEntryList.SetEntry(Index: Integer; const Value: TSchGenericEntry); begin if (Index < 0) or (Index >= fCount) then raise ERangeError.Create('Index out of bounds'); fList[ Index ] := Value; end; function TSchGenericEntry.New(sName: String): TSchGenericField; begin Result := TSchGenericField.Create(); Result.FieldName := sName; Add( Result ); end; function TSchGenericEntry.Dupe: TSchGenericEntry; var iX : Integer; begin Result := TSchGenericEntry.Create(); if Count > 0 then for iX := 0 to Count - 1 do begin Result.Add( Items[iX].Dupe() ); end; end; end.
Program a5; { This program compares sorting methods. Your job is to fill in code for the Radix Sort procedure below} uses QueueADT; const MAX = 10000; type KeyType = integer; ArrayIndex = 1..MAX; SortingArray = array[ArrayIndex] of KeyType; (************************************ HEAP SORT ***********************************) (* SiftUp(A,i,n) preconditions: A is an array, [i..n] is the range to be reheapified. postconditions: A[i..n] has been reheapified using the SiftUp algorithm found in program 13.10 *) procedure SiftUp(var A: SortingArray; i,n: integer); var j: ArrayIndex; RootKey: KeyType; NotFinished: Boolean; begin RootKey := A[i]; j := 2*i; NotFinished := (j<=n); while NotFinished do begin if j<n then if A[j+1]>A[j] then j := j+1; if A[j] <= RootKey then NotFinished := FALSE else begin A[i] := A[j]; i := j; j := 2*i; NotFinished := (j<=n) end end; A[i] := RootKey end; (* HeapSort(A,n) preconditions: A is an array of size n storing values of type KeyType postconditions: A has been sorted using the HeapSort algorithm found in program 13.10 *) procedure HeapSort(var A: SortingArray; n: integer); var i: integer; Temp: KeyType; begin for i := (n div 2) downto 2 do SiftUp(A,i,n); for i := n downto 2 do begin SiftUp(A,1,i); Temp := A[1]; A[1] := A[i]; A[i] := Temp end end; (************************************ QUICK SORT ***********************************) (* Partition(A,i,j) preconditions: A is an array, and [i..j] is a range of values to be partitioned postconditions: A[i..j] has been partitioned using the Partition algorithm found in program 13.15 *) procedure Partition(var A: SortingArray; var i,j: integer); var Pivot, Temp: KeyType; begin Pivot := A[(i+j) div 2]; repeat while A[i]<Pivot do i := i+1; while A[j]>Pivot do j := j-1; if i<=j then begin Temp := A[i]; A[i] := A[j]; A[j] := Temp; i := i+1; j := j-1 end; until i>j end; (* QuickSort(A,m,n) preconditions: A is an array, and [m..n] is a range of values to be sorted postconditions: A[m..n] has been sorted using the QuickSort algorithm found in program 13.14 *) procedure QuickSort(var A: SortingArray; m,n: integer); var i,j: integer; begin if m<n then begin i := m; j := n; Partition(A,i,j); QuickSort(A,m,j); QuickSort(A,i,n) end end; (************************************ RADIX SORT ***********************************) (* Power(x,n) preconditions: x and n are integers postconditions: returns x^n HINT: you may need this when you are isolating the digits in RadixSort *) function power(x,n: integer): integer; var i, result: integer; begin result := 1; for i := 1 to n do result := result * x; power := result end; (* RadixSort(A,n) preconditions: A is an array of size n postconditions: A[1..n] has been sorted using the RadixSort algorithm *) procedure RadixSort(var A: SortingArray; n: integer); var begin { YOUR CODE GOES HERE } end; (************************************ EXTRA STUFF ***********************************) function Random(var seed: integer): real ; const MODULUS = 35537 ; MULTIPLIER = 27193 ; INCREMENT = 13849 ; begin Random := ((MULTIPLIER * seed) + INCREMENT) mod MODULUS ; end; (* MakeRandomArray(A,n) preconditions: n is the size of array to create postconditions: A[1..n] has been initialized with random numbers in the range 1..MAXINT *) procedure MakeRandomArray(var A: SortingArray; n: integer); var i: integer; begin for i := 1 to n do begin A[i] := trunc( MAXINT * Random(i) ) ; A[i] := Abs(A[i]) end end; (* PrintArray(A,n) preconditions: A is an array of size n postconditions: A[1..n] is printed to the screen *) procedure PrintArray(var A: SortingArray; n: integer); var i: integer; begin writeln; for i := 1 to n do write(A[i],' '); writeln end; (* IsSorted(A,n) preconditions: A is an array of size n postconditions: Returns TRUE if A[1..n] is sorted in ascending order. Returns FALSE otherwise *) function IsSorted(var A: SortingArray; n: integer): boolean; var i: integer; begin IsSorted := TRUE; for i := 2 to n do if A[i]<A[i-1] then IsSorted := FALSE end; (************************************ EXTRA STUFF ***********************************) var A: SortingArray; {Array to sort} n, {Number of elements in array} choice, {User input} i, {counter} t, {Number of trials} correct: integer; {Number of correct runs} begin { randomize; {initialize the random number seed} repeat writeln; writeln('1. HeapSort an Array,'); writeln('2. QuickSort an Array,'); writeln('3. RadixSort an Array,'); writeln('4. Test HeapSort,'); writeln('5. Test QuickSort,'); writeln('6. Test RadixSort,'); writeln('7. quit'); writeln; readln(choice); case choice of 1,2,3: begin Writeln('This option creates a random array and sorts it'); Writeln; Write('How many elements in the array?'); readln(n); MakeRandomArray(A,n); Writeln; Writeln('The random array: '); if n <= 300 then PrintArray(A,n) else Writeln('*** too BIG to print ***'); Writeln; Write('Press Enter to sort'); readln; case choice of 1: HeapSort(A,n) ; 2: QuickSort(A,1,n) ; 3: RadixSort(A,n) ; end; writeln; Writeln('The sorted array: '); if n <= 300 then PrintArray(A,n) else Writeln('*** too BIG to print ***'); Writeln; Write('"IsSorted" returned ', IsSorted(A,n) ) ; readln; end; 4,5,6: begin Writeln('This option tests a sorting algorithm on a bunch of arrays.'); Writeln; Write('How many elements in each array?'); readln(n); Write('How many tests do you want to do?'); readln(t); correct := 0; for i := 1 to t do begin MakeRandomArray(A,n); case choice of 4: HeapSort(A,n) ; 5: QuickSort(A,1,n) ; 6: RadixSort(A,n) ; end; if IsSorted(A,n) then correct := correct + 1; end; writeln; writeln('IsSorted returned TRUE ', correct, ' times in ', t, ' trials.'); readln; end; end; until (choice = 7); end.
{ Subroutine SST_R_PAS_SMENT_ROUT (STR_ALL_H) * * Process the ROUTINE_HEADING syntax and put the appropriate information into * the symbol table. STR_ALL_H is the string handle to the whole * ROUTINE_HEADING syntax. } module sst_r_pas_SMENT_ROUT; define sst_r_pas_sment_rout; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_sment_rout ( {process ROUTINE_HEADING syntax} in str_all_h: syo_string_t); {string handle for whole statement} const max_msg_parms = 3; {max parameters we can pass to a message} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} func: boolean; {TRUE if subroutine is a function} here: boolean; {routine actually defined right here} existed: boolean; {TRUE if routine previously declared} declared: boolean; {TRUE if symbol already declared as routine} scope_internal: boolean; {TRUE if routine explicitly INTERNAL} sym_p: sst_symbol_p_t; {points to routine name symbol descriptor} sym_old_p: sst_symbol_p_t; {points to old symbol if already declared} sym_arg_p: sst_symbol_p_t; {points to dummy argument symbol descriptor} mem_p: util_mem_context_p_t; {points to mem context for temp scope} arg_p: sst_proc_arg_p_t; {points to current routine argument desc} fnam: string_treename_t; {file name passed to a message} lnum: sys_int_machine_t; {line number passed to a message} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label next_opt, vparam, done_opt, proc_mismatch; begin fnam.max := sizeof(fnam.str); syo_level_down; {down into ROUTINE_HEADING syntax} syo_get_tag_msg {get PROCEDURE/FUNCTION tag} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); case tag of {what type of routine is this} 1: begin {routine is a procedure} func := false; end; 2: begin {routine is a function} func := true; end; otherwise syo_error_tag_unexp (tag, str_h); end; {done with routine type keyword cases} syo_get_tag_msg {get routine name tag} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); sst_symbol_new ( {try to create new symbol for routine name} str_h, syo_charcase_asis_k, sym_p, stat); existed := {true if symbol previously declared} sys_stat_match(sst_subsys_k, sst_stat_sym_prev_def_k, stat); declared := false; {init to symbol new declared as routine} syo_error_abort (stat, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); { * Make sure we are in a nested scope for creating the routine descriptor. * We will always create a nested scope here, whether the routine was previously * declared or not. This allows us to always build a new routine descriptor * from the incoming data. If the routine was already declared, then later * the new descriptor is compared to the old, and the whole nested scope deleted. } sst_scope_new; {create nested scope for the routine} sym_old_p := nil; {init to no previous declaration existed} if existed then begin {symbol did exist previously ?} case sym_p^.symtype of {what kind of symbol is it so far ?} sst_symtype_proc_k: begin {symbol was already declared as a routine} declared := true; {remember that routine already declared} sym_old_p := sym_p; {save pointer to old symbol} sst_symbol_new ( {create temporary symbol in new scope} str_h, syo_charcase_down_k, sym_p, stat); sym_p^.flags := sym_old_p^.flags; {init with existing symbol flags} end; sst_symtype_illegal_k: ; {symbol defined, but not declared as anything} otherwise sst_charh_info (sym_p^.char_h, fnam, lnum); sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], lnum); sys_msg_parm_vstr (msg_parm[3], fnam); syo_error (str_h, 'sst_pas_read', 'symbol_already_def', msg_parm, 3); end; end; {done handling symbol already existed case} sst_scope_p^.symbol_p := sym_p; {point scope to its defining symbol} { * The symbol descriptor SYM_P^ is new and will be filled in with this * routine declaration. If the routine was declared before, then SYM_OLD_P * is pointing to the old symbol descriptor. In that case, the resulting data * structure will be compared with the old one later. } sym_p^.proc_scope_p := sst_scope_p; {save pointer to routine's scope} sym_p^.symtype := sst_symtype_proc_k; {symbol is a routine} sym_p^.proc.sym_p := sym_p; {point routine descriptor to name symbol} sym_p^.proc.dtype_func_p := nil; {no data type for function value exists yet} sym_p^.proc.flags := []; {init separate flags} sst_dtype_new (sym_p^.proc_dtype_p); {create new data type for this routine} sym_p^.proc_dtype_p^.symbol_p := sym_p; {fill in dtype descriptor for this routine} sym_p^.proc_dtype_p^.dtype := sst_dtype_proc_k; sym_p^.proc_dtype_p^.bits_min := 0; sym_p^.proc_dtype_p^.align_nat := 1; sym_p^.proc_dtype_p^.align := 1; sym_p^.proc_dtype_p^.size_used := 0; sym_p^.proc_dtype_p^.size_align := 0; sym_p^.proc_dtype_p^.proc_p := addr(sym_p^.proc); syo_get_tag_msg {get tag for routine arguments} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); if tag <> 1 then syo_error_tag_unexp (tag, str_h); sst_r_pas_proc_args (sym_p^.proc); {process call arguments, if any} syo_get_tag_msg {get tag for function return data type} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); case tag of 1: begin {no function data type is declared} if func then begin syo_error (str_h, 'sst_pas_read', 'func_no_data_type', nil, 0); end end; 2: begin {function data type IS declared} if func then begin {routine is a function} sst_r_pas_data_type (sym_p^.proc.dtype_func_p); {read in data type} end else begin {routine is a procedure} syo_error (str_h, 'sst_pas_read', 'proc_data_type', nil, 0); end ; end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of function dtype tag cases} { * Done processing call arguments and function return data type, if any. * Now handle routine options. } here := true; {init to routine is defined right here} scope_internal := false; {init to not explicitly internal routine} next_opt: {back here each new routine option} syo_get_tag_msg {get tag for next routine option} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); if tag = syo_tag_end_k then goto done_opt; {finished all routine options ?} if tag <> 1 then syo_error_tag_unexp (tag, str_h); {unexpected TAG value ?} syo_level_down; {down into ROUTINE_OPTION syntax} syo_get_tag_msg {get tag to identify routine option} (tag, str_h, 'sst_pas_read', 'statement_proc_bad', nil, 0); case tag of 1: begin {routine option FORWARD} here := false; {routine defined later} end; 2: begin {routine option EXTERN} if sym_old_p <> nil then begin {routine previously declared ?} sst_charh_info (sym_old_p^.char_h, fnam, lnum); sys_msg_parm_vstr (msg_parm[1], sym_old_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], lnum); sys_msg_parm_vstr (msg_parm[3], fnam); syo_error (str_h, 'sst_pas_read', 'proc_redeclare', msg_parm, 3); end; if not (sst_symflag_global_k in sym_p^.flags) then begin {not already global ?} sym_p^.flags := sym_p^.flags + [ sst_symflag_def_k, {symbol is properly defined} sst_symflag_global_k, {symbol will be globally known} sst_symflag_extern_k]; {symbol lives externally to this module} end; here := false; {routine defined later, if at all} end; 3: begin {routine option INTERNAL} if sst_symflag_global_k in sym_p^.flags then begin {already global symbol ?} sys_message_parms ('sst_pas_read', 'proc_global', nil, 0); goto proc_mismatch; end; scope_internal := true; {routine is explicitly not globally known} goto vparam; {go to common code with VAL_PARAM option} end; 4: begin {routine option VAL_PARAM} vparam: {jump here from INTERNAL option} sst_r_pas_vparam (sym_p^.proc); {adjust call args to VAL_PARAM option} end; 5: begin {routine option NO_RETURN} sym_p^.proc.flags := sym_p^.proc.flags + [ sst_procflag_noreturn_k]; end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of routine option type cases} syo_level_up; {back up from ROUTINE_OPTION syntax} goto next_opt; {back to handle next routine option} done_opt: {all done with routine options} if {this is a top subroutine in MODULE block ?} (not scope_internal) and {not explicitly flagged as non-global ?} (nest_level = 1) and {just inside top block ?} (top_block = top_block_module_k) and {top block is a MODULE ?} (not (sst_symflag_extern_k in sym_p^.flags)) {not already declared external ?} then begin sym_p^.flags := sym_p^.flags + {routine will be globally known} [sst_symflag_global_k]; end; { * The symbol descriptor SYM_P has been all filled in. } if declared { * The routine was declared before. Now compare the new declaration to the * old, and then completely delete the new symbol with its whole scope. } then begin {routine was declared before} sst_routines_match ( {compare old and new routine descriptors} sym_old_p^.proc, {original procedure descriptor} sym_p^.proc, {new procedure descriptor} stat); {returned status} if sys_error(stat) then begin {routine declarations mismatched ?} sys_error_print (stat, '', '', nil, 0); goto proc_mismatch; end; sym_old_p^.flags := sym_p^.flags; {update accumulated symbol flags} mem_p := sst_scope_p^.mem_p; {get pointer to mem context for temp scope} sst_scope_old; {back to original scope} sst_scope_p := sym_old_p^.proc_scope_p; {swap to routine's scope} sst_names_p := sst_scope_p; util_mem_context_del (mem_p); {deallocate all traces of temporary scope} sym_p := sym_old_p; {point back to old symbol declared before} end { * This was the first declaration of this routine. Put the call arguments into * the symbol table for the routine's scope. If the routine is a function, * this includes the function name. } else begin {routine was not declared before} arg_p := sym_p^.proc.first_arg_p; {init first argument as current} while arg_p <> nil do begin {loop thru each routine argument descriptor} sst_symbol_new_name ( {install call arg in symbol table} arg_p^.name_p^, {dummy argument name} sym_arg_p, {returned pointer to symbol descriptor} stat); sys_error_abort (stat, '', '', nil, 0); sym_arg_p^.symtype := sst_symtype_var_k; {set up symbol as dummy arg} sym_arg_p^.var_dtype_p := arg_p^.dtype_p; sym_arg_p^.var_val_p := nil; sym_arg_p^.var_arg_p := arg_p; sym_arg_p^.var_proc_p := addr(sym_p^.proc); sym_arg_p^.var_com_p := nil; sym_arg_p^.var_next_p := nil; arg_p^.sym_p := sym_arg_p; {point arg descriptor to its symbol} arg_p := arg_p^.next_p; {advance to next call argument in routine} end; {back to process this new call argument} sym_p^.proc_funcvar_p := nil; {init to no function value variable exists} if sym_p^.proc.dtype_func_p <> nil then begin {routine is a function ?} sst_symbol_new_name ( {install function name as variable name} sym_p^.name_in_p^, {function name} sym_arg_p, {returned pointer to symbol descriptor} stat); sys_error_abort (stat, '', '', nil, 0); sym_arg_p^.symtype := sst_symtype_var_k; {set up symbol as dummy arg} sym_arg_p^.var_dtype_p := sym_p^.proc.dtype_func_p; sym_arg_p^.var_val_p := nil; sym_arg_p^.var_arg_p := nil; sym_arg_p^.var_proc_p := addr(sym_p^.proc); sym_arg_p^.var_com_p := nil; sym_arg_p^.var_next_p := nil; sym_p^.proc_funcvar_p := sym_arg_p; {save pointer to function value variable} end; {done installing function name as local var} end ; if here then begin {routine is defined right here} sym_p^.flags := sym_p^.flags + [sst_symflag_def_k]; {routine is defined} sst_opcode_new; {create opcode for this routine} sst_opc_p^.opcode := sst_opc_rout_k; {opcode is a routine} sst_opc_p^.str_h := str_all_h; {save string handle to routine declaration} sst_opc_p^.rout_sym_p := sym_p; {point opcode to routine name symbol} sst_opcode_pos_push (sst_opc_p^.rout_p); {new opcodes are for this routine} nest_level := nest_level + 1; {one more layer deep in nested blocks} end else begin {routine will be defined elswhere, if at all} sst_scope_old; {pop back to original scope} end ; syo_level_up; {back up from ROUTINE_HEADING syntax} return; proc_mismatch: {print routines mismatch error and abort} if sym_old_p = nil then begin {there was no previous declaration} syo_error (str_h, '', '', nil, 0); end else begin {previous declaration existed} sst_charh_info (sym_old_p^.char_h, fnam, lnum); sys_msg_parm_vstr (msg_parm[1], sym_old_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], lnum); sys_msg_parm_vstr (msg_parm[3], fnam); syo_error (str_all_h, 'sst_pas_read', 'proc_mismatch', msg_parm, 3); end ; end;
unit GameUnit; // And explanation of scoring that I can understand // https://www.thoughtco.com/bowling-scoring-420895 interface type IBowlingGame = Interface ['{6F4E6568-9CEC-4703-A544-1C7ADA4D38F9}'] procedure StartGame; function AddPlayer(const Name: String; DisplayInSingleLine: Boolean): Integer; // index function GetPlayersCurrentFrameNo(const Name: String): Integer; // get the frame the player is playing function AddRoll(const PlayerName: String; NoPins: Integer): integer; //frame function IsCurrentFrameComplete(const PlayerName: String): Boolean; function IsGameOver(Index: Integer): Boolean; function GetPlayerStats(const PlayerName: String): String; function GetPlayersLastFrameStats(Index: Integer): String; function GetAllPlayersStats: String; function GetAllPlayersTotals: String; procedure SetDisplayLastTwoFrames(Value: Boolean); End; function BowlingGame: IBowlingGame; implementation uses Contnrs, Classes, SysUtils, TypInfo, Windows; type // fsDoubleStrikeBonusRoll = two strikes in a row TGameState = (fsFirstRoll, fsSecondRoll, fsOpen, fsSpareBonusRoll, fsSpare, fsStrikeBonusFirstRoll, fsStrikeBonusSecondRoll, fsStrike, fsGameOver, fsDoubleStrikeBonusRoll, fsSpareBonusRollFrame10, fsStrikeBonusFirstRollFrame10, fsStrikeBonusSecondRollFrame10, fsDoubleStrikeBonusRollFrame10); TFrameState = fsFirstRoll..fsGameOver; TRoll = (trFirst=1, trSecond); const cCrLf = #$D#$A; cMaxFrames = 10; // Frames collection starts at "0" cDisplayLastTwoFrames = false; // should NOT of brought these out to the UI, but oh well ;-( cDisplayInLine = true; // displays stats in a single line.. Same here with UI ;-( cShowLastTwoFrameState = ([fsSpareBonusRoll, fsSpare, fsStrikeBonusFirstRoll, fsStrikeBonusSecondRoll, fsStrike, fsDoubleStrikeBonusRoll, fsSpareBonusRollFrame10, fsStrikeBonusFirstRollFrame10, fsStrikeBonusSecondRollFrame10]); type TFrame = class private FState: TFrameState; FFrameTotal: Integer; // FRoll Each frame contains two rolls // Two rolls for a total of ten for a Spare // or 10 on the first roll is a Strike // in which case the second roll is a StrikeBonus // // after reading the link above about scoring, i should // probably keep track of 4 rolls // a spare gets 1 Bonus roll // a strike get 2 Bonus rolls FRoll: array[1..2] of Integer; FBonusRoll: array[1..2] of Integer; function GetRoll(Roll: TRoll): Integer; procedure SetState(AState: TFrameState); function GetState: TFrameState; function IsCurrentFrameComplete: Boolean; function IsFinalFrameComplete: Boolean; procedure TotalUpFrame; function GetFrameTotal: Integer; public FDisplayInLine: Boolean; // ;-( constructor Create(DisplayInLine: Boolean); procedure AddRoll(AState: TFrameState; NoPins: Integer); function GetScore: String; property Roll[Roll: TRoll]: Integer read GetRoll; property State: TFrameState read GetState write SetState; property FrameTotal: Integer read GetFrameTotal; property FinalFrameCompleted: Boolean read IsFinalFrameComplete; property CurrentFrameCompleted: Boolean read IsCurrentFrameComplete; end; TFrames = class(TObjectList) private FGameState: TGameState; FDisplayInLine: Boolean; Procedure DebugStr(const S: String); function GetFrameState(Index: Integer): TFrameState; procedure UpdateState; function IsCurrentFrameComplete: Boolean; function IsGameOver: Boolean; function GetLast(NoFrames: Integer): String; public constructor Create(DisplayInSingleLine: Boolean); function AddRoll(NoPins: Integer): Integer; // return frame; function GetGameState: String; function GetFrameStats(Index: Integer): String; function GetFrameTotal(Index: Integer): Integer; function GetGameTotal: Integer; function GetLastTwoFrames: String; function GetLastFrame: String; function GetAllFrameStats: String; property FrameState[frame: Integer]: TFrameState read GetFrameState; property CurrentFrameCompleted: Boolean read IsCurrentFrameComplete; property GameOver: Boolean read IsGameOver; end; TPlayers = class(TStringList) private FDisplayLastTwoFrames: Boolean; public procedure Clear; override; function AddPlayer(const Name: String; DisplayInSingleLine: Boolean): Integer; //return index function GetPlayersCurrentFrameNo(const Name: String): Integer; function AddRoll(const Name: String; NoPins: Integer): integer; // return frame function IsPlayerCurrentFrameComplete(const Name: String): Boolean; function IsGameOver(Index: Integer): Boolean; function GetPlayerTotals(const Name: String): String; function GetPlayerStats(const Name: String): String; function GetPlayersLastFrameStats(Index: Integer): String; overload; function GetPlayersLastFrameStats(const Name: String): String; overload; function GetAllPlayersStats: String; function GetAllPlayersTotals: String; property DisplayLastTwoFrames: Boolean read FDisplayLastTwoFrames write FDisplayLastTwoFrames; end; TBowlingGame = Class(TInterfacedObject, IBowlingGame) private FPlayers: TPlayers; public procedure StartGame; procedure SetDisplayLastTwoFrames(Value: Boolean); function AddPlayer(const PlayerName: String; DisplayInSingleLine: BOolean): Integer; // return index function GetPlayersCurrentFrameNo(const Player: String): Integer; // current frame number function AddRoll(const PlayerName: String; NoPins: Integer): Integer;// return frame; function IsCurrentFrameComplete(const PlayerName: String): Boolean; function IsGameOver(Index: Integer): Boolean; function GetPlayerStats(const PlayerName: String): String; function GetPlayersLastFrameStats(Index: Integer): String; function GetAllPlayersStats: String; function GetAllPlayersTotals: String; end; procedure TFrames.DebugStr(const S: String); begin OutputDebugString(pChar(S)); end; constructor TFrame.Create(DisplayInLine: Boolean); begin inherited Create; FDisplayInLine := DisplayInLine; FillChar(FRoll,SizeOf(FRoll),0); FillChar(FBonusRoll, SizeOf(FBonusRoll), 0); end; function TFrame.GetRoll(Roll: TRoll): Integer; begin result := FRoll[Ord(Roll)]; end; Procedure TFrame.SetState(AState: TFrameState); begin FState := AState; end; function TFrame.GetState: TFrameState; begin result := FState; end; function TFrame.IsFinalFrameComplete: Boolean; begin result := FState in [fsSpare, fsStrike, fsOpen]; end; function TFrame.IsCurrentFrameComplete: Boolean; begin result := FState in [fsSpareBonusRoll, fsSpare, fsStrikeBonusFirstRoll, fsStrike, fsOpen]; end; // FRoll Each frame contains two rolls // Two rolls for a total of ten for a Spare // or 10 on the first roll is a Strike // in which case the second roll is a StrikeBonus procedure TFrame.AddRoll(AState: TFrameState; NoPins: Integer); begin case AState of fsFirstRoll: FRoll[1] := NoPins; fsSecondRoll: FRoll[2] := NoPins; fsOpen: ; fsSpare: ; fsSpareBonusRoll: FBonusRoll[1] := NoPins; fsStrike: ; fsStrikeBonusFirstRoll: FBonusRoll[1] := NoPins; fsStrikeBonusSecondRoll: FBonusRoll[2] := NoPins; end; TotalUpFrame; end; procedure TFrame.TotalUpFrame; begin FFrameTotal := FRoll[1]+FRoll[2]+FBonusRoll[1]+FBonusRoll[2]; end; function TFrame.GetFrameTotal: Integer; begin result := FFrameTotal; end; function TFrame.GetScore: String; begin if FDisplayInLine then result := Format('FirstRoll: %2d SecondRoll: %2d '+ 'BonusRoll 1: %2d BonusRoll 2: %2d '+ 'FrameTotal: %3d '+ 'State: %s', [FRoll[1], FRoll[2], FBonusRoll[1], FBonusRoll[2], FFrameTotal, GetEnumName(TypeInfo(TFrameState), Ord(FState))]) else result := Format('FirstRoll: %d%sSecondRoll: %d%s'+ 'BonusRoll 1: %d%sBonusRoll 2: %d%s'+ 'FrameTotal: %d%s'+ 'State: %s%s', [FRoll[1], cCrLf, FRoll[2], cCrLf, FBonusRoll[1], cCrLf, FBonusRoll[2], cCrLf, FFrameTotal, cCrLf, GetEnumName(TypeInfo(TFrameState), Ord(FState)), cCrLf]); end; constructor TFrames.Create(DisplayInSingleLine: Boolean); begin inherited Create(True); FDisplayInLine := DisplayInSingleLine; end; function TFrames.GetGameState: String; begin result := GetEnumName(TypeInfo(TGameState), Ord(FGameState)); end; function TFrames.GetFrameState(Index: Integer): TFrameState; begin result := (Items[Index] as TFrame).State; end; function TFrames.GetFrameStats(Index: integer): String; begin result := (Items[Index] as TFrame).GetScore; end; function TFrames.GetFrameTotal(Index: Integer): Integer; begin result := (Items[Index] as TFrame).GetFrameTotal; end; function TFrames.GetGameTotal: Integer; var t, TotalScore: Integer; begin TotalScore := 0; result := 0; for t := 0 to Count - 1 do TotalScore := TotalScore + GetFrameTotal(t); result := TotalScore; end; function TFrames.GetLastTwoFrames: String; var iShowFrames: Integer; begin iShowFrames := 1; if (Count > 1) AND (GetFrameState(Count-2) in cShowLastTwoFrameState) then iShowFrames := 2; result := GetLast(iShowFrames); end; function TFrames.GetLast(NoFrames: Integer): String; var t: integer; TotalScore: Integer; begin TotalScore := 0; result := ''; for t := 0 to Count - 1 do begin if (t < (Count-NoFrames)) then continue; if FDisplayInLine then result := Format('%sFrame: %2d %s ', [result, // GetGameState, cCrLf, Succ(t), GetFrameStats(t)]) else result := Format('%sFrame: %d%s%s', [result, // GetGameState, cCrLf, Succ(t), cCrLf, GetFrameStats(t)]); TotalScore := TotalScore+GetFrameTotal(t); result := Format('%sTotal score: %d%s%s', [result, TotalScore, cCrLf, cCrLf]); end; end; function TFrames.GetAllFrameStats: String; var t: integer; TotalScore: Integer; begin TotalScore := 0; result := ''; for t := 0 to Count - 1 do begin if FDisplayInLine then result := Format('%sFrame: %2d %s ', [result, Succ(t), GetFrameStats(t)]) else result := Format('%sFrame: %d%s%s', [result, Succ(t), cCrLf, GetFrameStats(t)]); TotalScore := TotalScore+GetFrameTotal(t); result := Format('%sTotal score: %d%s%s', [result, TotalScore, cCrLf, cCrLf]); end; end; function TFrames.GetLastFrame: String; var t: integer; TotalScore: Integer; begin TotalScore := 0; result := ''; for t := 0 to Count - 1 do begin TotalScore := TotalScore+GetFrameTotal(t); if t=Pred(Count) then begin result := Format('%sFrame: %2d%s%s', [result, // GetGameState, cCrLf, Succ(t), cCrLf, GetFrameStats(t)]); result := Format('%sTotal score: %d%s', [result, TotalScore, cCrLf]); end end; end; function TFrames.IsCurrentFrameComplete: BOolean; begin if (Count<cMaxFrames) then result := (Items[Count-1] as TFrame).CurrentFrameCompleted else result := (Items[Count-1] as TFrame).FinalFrameCompleted end; function TFrames.IsGameOver: Boolean; var State: TFrameState; bOk, bInState: boolean; begin result := false; if Count=0 then exit; bOk := Count = cMaxFrames; State := (Items[Count-1] as TFrame).GetState; bInState := State in [fsOpen, fsSpare, fsStrike]; result := bOk AND bInState; DebugStr(Format('CurrentFrameComplete: %s', [BoolToStr(result)])); end; function TFrames.AddRoll(NoPins: Integer): Integer; // frame var Frame: TFrame; begin result := -1; if (Count = 0) OR ((Count<cMaxFrames) AND (FGameState in [fsOpen, fsSpareBonusRoll, fsStrikeBonusFirstRoll, fsDoubleStrikeBonusRoll])) then begin if (Count=0) OR (FGameState=fsOpen) then FGameState := fsFirstRoll; Add(TFrame.Create(FDisplayInLine)); end; Frame := Items[Pred(Count)] as TFrame; if ((NoPins>10) OR (NoPins<0)) OR ((Frame.State=fsSecondRoll) AND (Frame.Roll[trFirst]+NoPins >10)) then raise Exception.CreateFmt('%d for the number of pins out of range', [NoPins]); case FGameState of fsFirstRoll, fsSecondRoll: begin Frame.AddRoll(FGameState, NoPins); end; fsSpareBonusRoll: begin Frame.AddRoll(fsFirstRoll, NoPins); Frame := Items[Count-2] as TFrame; Frame.AddRoll(fsSpareBonusRoll, NoPins); end; fsStrikeBonusFirstRoll: begin Frame.AddRoll(fsFirstRoll, NoPins); Frame := Items[Count-2] as TFrame; Frame.AddRoll(fsStrikeBonusFirstRoll, NoPins); end; fsStrikeBonusSecondRoll: begin Frame.AddRoll(fsSecondRoll, NoPins); Frame := Items[Count-2] as TFrame; Frame.AddRoll(FGameState, NoPins); end; // two strikes in a row fsDoubleStrikeBonusRoll: begin Frame.AddRoll(fsFirstRoll, NoPins); (Items[Count-2] as TFrame).AddRoll(fsStrikeBonusFirstRoll, NoPins); (Items[Count-3] as TFrame).AddRoll(fsStrikeBonusSecondRoll, NoPins); end; fsSpareBonusRollFrame10: Frame.AddRoll(fsSpareBonusRoll, NoPins); fsStrikeBonusFirstRollFrame10: Frame.AddRoll(fsStrikeBonusFirstRoll, NoPins); fsStrikeBonusSecondRollFrame10: Frame.AddRoll(fsStrikeBonusSecondRoll, NoPins); fsDoubleStrikeBonusRollFrame10: begin Frame.AddRoll(fsStrikeBonusFirstRoll, NoPins); (Items[Count-2] as TFrame).AddRoll(fsStrikeBonusSecondRoll, NoPins); end; end; UpdateState; result := Count; end; procedure TFrames.UpdateState; var Frame: TFrame; begin Frame := (Items[Count-1] as TFrame); case FGameState of fsFirstRoll: begin if Frame.Roll[trFirst]=10 then FGameState := fsStrikeBonusFirstRoll else FGameState := fsSecondRoll; Frame.State := FGameState; end; fsSecondRoll: begin if Frame.Roll[trFirst]+Frame.Roll[trSecond]=10 then FGameState := fsSpareBonusRoll else FGameState := fsOpen; Frame.State := FGameState; end; fsSpareBonusRoll: begin if Frame.Roll[trFirst]=10 then FGameState := fsStrikeBonusFirstRoll else FGameState := fsSecondRoll; Frame.State := FGameState; (Items[Count-2] as TFrame).State := fsSpare; end; fsStrikeBonusFirstRoll: begin if Frame.Roll[trFirst]=10 then begin Frame.State := fsStrikeBonusFirstRoll; FGameState := fsDoubleStrikeBonusRoll; end else begin FGameState := fsStrikeBonusSecondRoll; Frame.State := fsSecondRoll; end; (Items[Count-2] as TFrame).State := fsStrikeBonusSecondRoll; end; fsStrikeBonusSecondRoll: begin if Frame.Roll[trFirst]+Frame.Roll[trSecond]=10 then FGameState := fsSpareBonusRoll else FGameState := fsOpen; Frame.State := FGameState; (Items[Count-2] as TFrame).State := fsStrike; end; fsDoubleStrikeBonusRoll: begin if Frame.Roll[trFirst]=10 then begin Frame.State := fsStrikeBonusFirstRoll; FGameState := fsDoubleStrikeBonusRoll end else begin FGameState := fsStrikeBonusSecondRoll; Frame.State := fsSecondRoll; end; (Items[Count-2] as TFrame).State := fsStrikeBonusSecondRoll; (Items[Count-3] as TFrame).State := fsStrike; end; end; // tenth frame fix up if Count=10 then begin case FGameState of fsSpareBonusRoll: FGameState := fsSpareBonusRollFrame10; fsSpareBonusRollFrame10: begin FGameState := fsSpare; Frame.State := fsSpare; end; fsStrikeBonusFirstRoll: begin FGameState := fsStrikeBonusFirstRollFrame10; Frame.State := fsStrikeBonusFirstRoll; end; fsDoubleStrikeBonusRoll: begin FGameState := fsDoubleStrikeBonusRollFrame10 end; fsStrikeBonusFirstRollFrame10: begin FGameState := fsStrikeBonusSecondRollFrame10; Frame.State := fsStrikeBonusSecondRoll; end; fsStrikeBonusSecondRollFrame10: begin FGameState := fsStrike; Frame.State := FGameState; end; fsDoubleStrikeBonusRollFrame10: begin Frame.State := fsStrikeBonusSecondRoll; FGameState := fsStrikeBonusSecondRollFrame10; (Items[Count-2] as TFrame).State := fsStrike; end; end; end; end; procedure TPlayers.Clear; var t: Integer; begin for t := 0 to Count - 1 do Objects[t].Free; inherited clear; end; function TPlayers.AddPlayer(const Name: String; DisplayInSingleLine: Boolean): Integer; begin if IndexOf(Name) = -1 then result := AddObject(Name, TFrames.Create(DisplayInSingleLine)) else raise Exception.CreateFmt('Player: [%s] already exists in this game.', [Name]); end; function TPlayers.GetPlayersCurrentFrameNo(const Name: String): Integer; var Frames: TFrames; begin if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); Frames := Objects[IndexOf(Name)] as TFrames; result := Frames.Count; end; function TPlayers.AddRoll(const Name: String; NoPins: Integer): Integer; //frame var Frames: TFrames; begin if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); Frames := Objects[IndexOf(Name)] as TFrames; result := Frames.AddRoll(NoPins); end; function TPlayers.GetPlayerTotals(const Name: String): String; var Frames: TFrames; GameTotal: Integer; begin if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); Frames := Objects[IndexOf(Name)] as TFrames; GameTotal := Frames.GetGameTotal; result := IntToStr(GameTotal); end; function TPlayers.GetPlayerStats(const Name: String): String; var Frames: TFrames; begin if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); Frames := Objects[IndexOf(Name)] as TFrames; result := Frames.GetAllFrameStats; end; function TPlayers.IsGameOver(Index: Integer): Boolean; var Name: String; begin Name := Strings[Index]; if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); result := (Objects[IndexOf(Name)] as TFrames).GameOver; end; function TPlayers.GetPlayersLastFrameStats(Index: Integer): String; var Name: String; begin Name := Strings[Index]; result := GetPlayersLastFrameStats(Name); end; function TPlayers.GetPlayersLastFrameStats(const Name: String): String; var Frames: TFrames; begin result := ''; if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); Frames := Objects[IndexOf(Name)] as TFrames; if NOT cDisplayLastTwoFrames then result := Format('%s%sGame State: %s%s%s', [Name, cCrLf, Frames.GetGameState, cCrLf, Frames.GetLastFrame]) else result := Format('%s%s%s%s%s', [Name, cCrLf, Frames.GetGameState, cCrLf, Frames.GetLastTwoFrames]) end; function TPlayers.GetAllPlayersStats: String; var I: Integer; Frames: TFrames; begin result := ''; for I := 0 to Count - 1 do begin Result := Format('%s%s:%s%s', [result, Strings[i], cCrLf, GetPlayerStats(Strings[i]), cCrLf]); Frames := Objects[IndexOf(Strings[i])] as TFrames; result := Format('%sGame State: %s%s%s', [result, Frames.GetGameState, cCrlf, cCrLf]); end; end; function TPlayers.GetAllPlayersTotals: String; var i: Integer; begin result := ''; for I := 0 to Count - 1 do begin Result := Format('%s%s: %s%s', [result, Strings[i], GetPlayerTotals(Strings[i]), cCrLf]); end; end; function TPlayers.IsPlayerCurrentFrameComplete(const Name: string): Boolean; begin if IndexOf(Name) = -1 then raise Exception.CreateFmt('Player: [%s] does not exist.', [Name]); result := (Objects[IndexOf(Name)] as TFrames).CurrentFrameCompleted; end; procedure TBowlingGame.StartGame; begin if NOT Assigned(FPlayers) then FPlayers := TPlayers.Create else FPlayers.Clear; end; procedure TBowlingGame.SetDisplayLastTwoFrames(Value: Boolean); begin FPlayers.DisplayLastTwoFrames := Value; end; function TBowlingGame.AddPlayer(const PlayerName: String; DisplayInSingleLine: Boolean): Integer; begin result := FPlayers.AddPlayer(PlayerName, DisplayInSingleLine); end; function TBowlingGame.GetPlayersCurrentFrameNo(const Player: string): Integer; begin result := FPlayers.GetPlayersCurrentFrameNo(Player); end; function TBowlingGame.AddRoll(const PlayerName: String; NoPins: Integer): Integer; begin result := FPlayers.AddRoll(PlayerName, NoPins); end; function TBowlingGame.IsCurrentFrameComplete(const PlayerName: string): Boolean; begin result := FPlayers.IsPlayerCurrentFrameComplete(PlayerName); end; function TBowlingGame.IsGameOver(Index: Integer): Boolean; begin result := FPlayers.IsGameOver(Index); end; function TBowlingGame.GetPlayerStats(const PlayerName: string): String; begin result := FPlayers.GetPlayerStats(PlayerName); end; function TBowlingGame.GetAllPlayersStats: String; begin result := FPlayers.GetAllPlayersStats; end; function TBowlingGame.GetAllPlayersTotals: String; begin result := FPlayers.GetAllPlayersTotals; end; function TBowlingGame.GetPlayersLastFrameStats(Index: Integer): String; begin result := FPlayers.GetPlayersLastFrameStats(Index); end; function BowlingGame: IBowlingGame; begin result := TBowlingGame.Create; end; end.
unit ProgTypes; interface const ProfileDir = 'Profiles\Engineer\'; ProfileFile = 'eng1280.dat'; type {Scadus function prototypes} TScadusProc = procedure; {library's function prototypes} TLibExeFnc = function(Idx: integer): byte; stdcall; TLibCntFnc = function: integer; stdcall; TLibNameFnc = function(Idx: integer): string; stdcall; {function information for menu, buttons and executable events} TLibFnc = record IdxLib: integer; IdxFnc: integer; end; {scadus class} TScadus = class private {dll variables} LibCount: integer; LibHandles: array of THandle; // handle to library LibExeFncs: array of Pointer; // handle to function "ExecuteFnc" from library LibCntFncs: array of Pointer; // handle to function "GetProcCount" from library LibNameFncs: array of Pointer; // handle to function "GetProcName" from library LibNames: array of string; FncNames: array of array of string; MenuCount: integer; MenuList: array of TLibFnc; BtnCount: integer; BtnList: array of TLibFnc; {event variables} EventCount: integer; EventQueue: array of integer; EventExList: array of array of TLibFnc; public StartDir: string; {profile variables} UserDir: string; LoadProfile: string; IsBtn: boolean; IsMenu: boolean; IsEvent: boolean; IsStart: boolean; OnAnyEvent: array[1..50] of Pointer; constructor Create; procedure GetFncIndex(FncName: string; var IdxL, IdxF: integer); procedure PrepareLibraryList(CntL: integer); procedure OpenLibrary(IdxL: integer; LibFile: string); procedure AddLibToLibraryList(IdxL: integer; LibName: string); procedure PrepareMenuList(CntM: integer); procedure AddFncToMenuList(IdxM: integer; FncName: string); procedure PrepareEventList(CntE: integer); procedure AddFncToEventExList(IdxE: integer; FncName: string); procedure SetOnAnyEvent(IdxE: integer; Point: Pointer); procedure ExecuteFnc(IdxL: integer; IdxF: integer); procedure ExecuteEvent(IdxE: integer; Who: THandle); procedure ExecuteMenu(IdxM: integer); procedure ExecuteBtn(IdxB: integer); end; var ScadusX: TScadus; implementation uses Windows, SysUtils, ContInt; constructor TScadus.Create; var Idx: integer; begin StartDir:=ExtractFilePath(ParamStr(0)); UserDir:=StartDir+ProfileDir; LoadProfile:=StartDir+ProfileDir+ProfileFile; for Idx:=1 to 50 do OnAnyEvent[Idx]:=nil; LibCount:=0; MenuCount:=0; BtnCount:=0; EventCount:=0; IsBtn:=False; IsMenu:=False; IsEvent:=False; IsStart:=False; end; procedure TScadus.GetFncIndex(FncName: string; var IdxL, IdxF: integer); var Pos_: integer; NameL: string; NameF: string; begin IdxL:=-1; IdxF:=0; if (FncName <> '') then begin Pos_:=Pos('_', FncName); if (Pos_ > 0) then begin NameL:=copy(FncName, 1, Pos_-1); NameF:=copy(FncName, Pos_+1, Length(FncName)-Pos_); IdxL:=0; while (IdxL < Length(LibNames)) and (CompareText(LibNames[IdxL], NameL) <> 0) do IdxL:=IdxL+1; if (IdxL < Length(LibNames)) then begin IdxF:=0; while (IdxF < Length(FncNames[IdxL])) and (CompareText(FncNames[IdxL, IdxF], NameF) <> 0) do IdxF:=IdxF+1; if not (IdxF < Length(FncNames[IdxL])) then begin IdxL:=-1; IdxF:=0; end; end else IdxL:=-1; end; end; end; procedure TScadus.PrepareLibraryList(CntL: integer); begin LibCount:=CntL; SetLength(LibHandles, LibCount); SetLength(LibExeFncs, LibCount); SetLength(LibCntFncs, LibCount); SetLength(LibNameFncs, LibCount); SetLength(LibNames, LibCount); SetLength(FncNames, LibCount); end; procedure TScadus.OpenLibrary(IdxL: integer; LibFile: string); begin LibHandles[IdxL]:=LoadLibrary(PAnsiChar(LibFile)); if (LibHandles[IdxL] > 0) then begin LibExeFncs[IdxL]:=GetProcAddress(LibHandles[IdxL], 'ExecuteFnc'); LibCntFncs[IdxL]:=GetProcAddress(LibHandles[IdxL], 'GetProcCount'); LibNameFncs[IdxL]:=GetProcAddress(LibHandles[IdxL], 'GetProcName'); end; end; procedure TScadus.AddLibToLibraryList(IdxL: integer; LibName: string); var CntFnc: TLibCntFnc; NameFnc: TLibNameFnc; FncC: integer; IdxF: integer; NameF: string; function ClearSpaces(Txt: string): string; var IdxS: integer; begin Result:=''; for IdxS:=1 to Length(Txt) do if (Txt[IdxS] <> ' ') then Result:=Result+Txt[IdxS]; end; begin if (IdxL >= 0) and (IdxL < LibCount) then begin LibNames[IdxL]:=LibName; CntFnc:=LibCntFncs[IdxL]; if (@CntFnc <> nil) then begin FncC:=CntFnc+1; SetLength(FncNames[IdxL], FncC); NameFnc:=LibNameFncs[IdxL]; for IdxF:=0 to FncC-1 do begin if (@NameFnc <> nil) then NameF:=NameFnc(IdxF) else NameF:=''; NameF:=ClearSpaces(NameF); FncNames[IdxL, IdxF]:=NameF; end; end; end; end; procedure TScadus.PrepareMenuList(CntM: integer); begin MenuCount:=CntM; SetLength(MenuList, MenuCount); end; procedure TScadus.AddFncToMenuList(IdxM: integer; FncName: string); var IdxL: integer; IdxF: integer; begin GetFncIndex(FncName, IdxL, IdxF); MenuList[IdxM].IdxLib:=IdxL; MenuList[IdxM].IdxFnc:=IdxF; end; procedure TScadus.PrepareEventList(CntE: integer); begin EventCount:=GetEventCount; SetLength(EventExList, EventCount); end; procedure TScadus.AddFncToEventExList(IdxE: integer; FncName: string); var IdxL: integer; IdxF: integer; begin if (IdxE > 0) and (IdxE <= EventCount) then begin SetLength(EventExList[IdxE-1], Length(EventExList[IdxE-1])+1); GetFncIndex(FncName, IdxL, IdxF); EventExList[IdxE-1][Length(EventExList[IdxE-1])-1].IdxLib:=IdxL; EventExList[IdxE-1][Length(EventExList[IdxE-1])-1].IdxFnc:=IdxF; end; end; procedure TScadus.ExecuteFnc(IdxL: integer; IdxF: integer); var ExeFnc: TLibExeFnc; begin if (IdxL >= 0) and (IdxL < LibCount) then begin ExeFnc:=LibExeFncs[IdxL]; if (@ExeFnc <> nil) then ExeFnc(IdxF); end; end; procedure TScadus.SetOnAnyEvent(IdxE: integer; Point: Pointer); begin OnAnyEvent[IdxE]:=Point; end; procedure TScadus.ExecuteEvent(IdxE: integer; Who: THandle); var ExeProc: TScadusProc; Idx: integer; CurrentEvent: integer; begin if (IdxE > 0) and (IdxE <= EventCount) then begin IsEvent:=True; if (IdxE = seStartOfTesting) then IsStart:=True; // add event to EventQueue SetLength(EventQueue, Length(EventQueue)+1); EventQueue[Length(EventQueue)-1]:=IdxE; // execute functions for current event if event queue doesn't have other event // else functions will be executed from first calling if (Length(EventQueue) = 1) then begin CurrentEvent:=EventQueue[0]; while (CurrentEvent > 0) do begin SetActiveEvent(CurrentEvent); // execute all functions hooked to current event if (Length(EventExList[CurrentEvent-1]) > 0) then begin Idx:=0; while (Idx < Length(EventExList[CurrentEvent-1])) do begin ExecuteFnc(EventExList[CurrentEvent-1][Idx].IdxLib, EventExList[CurrentEvent-1][Idx].IdxFnc); Idx:=Idx+1; end; end; // execute scadus functions if (OnAnyEvent[CurrentEvent] <> nil) then begin ExeProc:=OnAnyEvent[CurrentEvent]; ExeProc; end; if (Length(EventQueue) > 1) then begin for Idx:=1 to Length(EventQueue)-1 do EventQueue[Idx-1]:=EventQueue[Idx]; SetLength(EventQueue, Length(EventQueue)-1); end else EventQueue:=nil; if (EventQueue <> nil) then CurrentEvent:=EventQueue[0] else CurrentEvent:=0; end; SetActiveEvent(0); end; if (IdxE = seEndOfTesting) then IsStart:=False; if (EventQueue = nil) then IsEvent:=False; end; end; procedure TScadus.ExecuteMenu(IdxM: integer); begin if (IdxM >= 0) and (IdxM < MenuCount) then if (MenuList[IdxM].IdxLib >= 0) then ExecuteFnc(MenuList[IdxM].IdxLib, MenuList[IdxM].IdxFnc); end; procedure TScadus.ExecuteBtn(IdxB: integer); begin if (IdxB >= 0) and (IdxB < BtnCount) then if (BtnList[IdxB].IdxLib >= 0) then ExecuteFnc(BtnList[IdxB].IdxLib, BtnList[IdxB].IdxFnc); end; end.
{ Subroutine SST_W_C_POS_PUSH (STYPE) * * Push the state for the current statement on the stack, and set up the * output writing state for a previous position. STYPE is the type of statement * that will be written at the new position. It is used to decide where to * re-position to. Supported statement types are global declaration, local * declaration, and executable. } module sst_w_c_POS_PUSH; define sst_w_c_pos_push; %include 'sst_w_c.ins.pas'; procedure sst_w_c_pos_push ( {push curr pos, set to a previous position} in stype: sment_type_k_t); {statement type that will be written} const max_msg_parms = 1; {max parameters we can pass to a message} var frame_p: frame_posp_p_t; {pointer to this stack frame} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label leave; begin %debug; write (sst_stack^.last_p^.curr_adr, ' '); %debug; writeln ('POS PUSH'); { * Create new stack frame and push the old state on it. } util_stack_push (sst_stack, sizeof(frame_p^), frame_p); {make stack frame} frame_p^.dyn_p := sst_out.dyn_p; {save old pointer to current position} frame_p^.sment_type := frame_scope_p^.sment_type; {save statement type ID} { * If we are currently inside the same statement type requested by STYPE, then * use the position of the start of the statement. } if (frame_sment_p <> nil) and then {we are inside a statement ?} (frame_scope_p^.sment_type = stype) {same sment type we want to switch to ?} then begin sst_out.dyn_p := addr(frame_sment_p^.pos_before); {go to before curr statement} goto leave; end; { * We have to switch to the last known location of the requested statement type. } case stype of sment_type_declg_k: sst_out.dyn_p := addr(pos_declg); {global declaration} sment_type_decll_k: sst_out.dyn_p := addr(frame_scope_p^.pos_decll); {local decl} otherwise sys_msg_parm_int (msg_parm[1], ord(stype)); sys_message_bomb ('sst_c_write', 'statement_type_bad', msg_parm, 1); end; frame_scope_p^.sment_type := stype; {set new statement type as current} leave: {common exit point} if sst_out.dyn_p^.str_p = nil then begin {not pointing to any line ?} sst_out.dyn_p^.str_p := sst_out.first_str_p; {init to before first line} end; end;
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElCRC32; interface uses Windows, {$ifdef VCL_6_USED} Types, {$endif} Consts; function CRC32(crc : longint; const c : byte) : longint; function CRCBuffer(InitialCRC : longint; Buffer : Pointer; BufLen : integer) : Longint; function CRCStr(Str : string) : longint; implementation const CRC32_POLYNOMIAL = $EDB88320; var Ccitt32Table : array[0..255] of longint; function CRCBuffer(InitialCRC : longint; Buffer : Pointer; BufLen : integer) : Longint; var c, i : integer; P : PByte; begin c := InitialCRC; P := PByte(Buffer); for i := 0 to BufLen -1 do { Iterate } begin c := crc32(c, P^); //P := PChar(j); Inc(P); end; { for } result := c; end; function CrcStr(Str : string) : longint; var i, l, c : integer; begin l := length(Str); c := 0; for i := 1 to l do c := crc32(c, byte(str[i])); result := c; end; function crc32(crc : longint; const c : byte) : longint; begin crc32 := (((crc shr 8) and $00FFFFFF) xor (Ccitt32Table[(crc xor c) and $FF])); end; procedure BuildCRCTable; var i, j, value : DWORD; begin for i := 0 to 255 do begin value := i; for j := 8 downto 1 do begin if ((value and 1) <> 0) then value := (value shr 1) xor CRC32_POLYNOMIAL else value := value shr 1; end; Ccitt32Table[i] := value; end end; initialization BuildCRCTable; end.
program ch9(input, output, data8, out8); { Chapter 8 Assignment Alberto Villalobos March 28, 2014 Description: Read lines from a file, in which each line contains first a code letter, followed by four numbers. The codes are S, C and A, meaning Sum of Squares, Sum of Cubes and Average of Squares. The values domain is [10,20], otherwise output an error. Input: A file with lines representing a code and group of values each. Output: Show data data found and specify what function was done, eg: Data Line: C 10 10 10 20 11000 Sum of Squares Level 0: Initialize variables Reset input file Read each line Execute in range function Execute code function Print output Level 1: Initialize variables Reset input file While not EOF loop Read whole line Send to code function, pass values as args Execute inRange function Print Outpue } {main program vars} var data8,out8: Text; letterCode: Char; a, b, c, d: Integer; function avSqrSum(a,b,c,d : integer): Real; var sum: Real; begin sum:= sum + (a*a) + (b*b) + (c*c) + (d*d); sum:= sum/4; avSqrSum:=sum; end; function sqrSum(a,b,c,d : integer): Integer; var sum: Integer; begin sum:=0; sum:= sum + (a*a) + (b*b) + (c*c) + (d*d); sqrSum:= sum; end; function cubeSum(a,b,c,d : integer): Integer; var sum: Integer; begin sum:= sum + (a*a*a) + (b*b*b) + (c*c*c) + (d*d*d); cubeSum:=sum; end; function inRange(a,b,c,d : integer): Integer; var errorIndex, valid: integer; begin errorIndex:=0; if (a<10) OR (a>20) OR (b<10) OR (b>20) OR (c<10) OR (c>20) OR (d<10) OR (d>20) then begin {errorIndex:=errorIndex+1;} valid:= 0; end else begin valid:= 1; end; inRange := valid; end; procedure printOutput(letterCode: Char; a,b,c,d : Integer); var valid: Integer; begin valid := inRange(a,b,c,d); writeln(out8, 'Data Line':9, letterCode:4, a:4, b:4, c:4, d:4); if valid = 1 then begin case letterCode of 'S': writeln(out8,sqrSum(a,b,c,d):6,'Sum of squares':15); 'C': writeln(out8,cubeSum(a,b,c,d):6,'Sum of cubes':15); 'A': writeln(out8,avSqrSum(a,b,c,d):6:0,'Average of squares':20); else writeln('not found'); end end else begin writeln(out8,'Invalid Data'); end; writeln(out8,' '); end; {main program} begin reset(data8, 'datafiles/data8.dat'); rewrite(out8, 'outputfiles/out8.dat'); while not eof(data8) do begin Read(data8, letterCode); Read(data8, a); Read(data8, b); Read(data8, c); Read(data8, d); printOutput(letterCode, a,b,c,d); if eoln(data8) then readln(data8); end; end.
unit fcEvaluator; interface uses Classes, SysUtils, fcCommon; type TOperator = (opMultiply, opDivide, opAdd, opSubtract); TOperators = set of TOperator; TfcEvaluator = class protected class function GetOperands(s: string; Operators: TOperators; var LOperand, ROperand: string; var FoundOp: TOperator): Boolean; class procedure ValidateString(s: String); class procedure FixString(var s: String); public class function Evaluate(s: string): Integer; end; const OPERATORSCHAR: array[TOperator] of Char = ('*', '/', '+', '-'); implementation class function TfcEvaluator.GetOperands(s: string; Operators: TOperators; var LOperand, ROperand: string; var FoundOp: TOperator): Boolean; var OpIndex, CurOpIndex: Integer; CurOp: TOperator; begin OpIndex := -1; for CurOp := Low(TOperator) to High(TOperator) do if (CurOp in Operators) then begin CurOpIndex := fcFindToken(s, ' ', OPERATORSCHAR[CurOp]); if (CurOpIndex <> -1) and ((OpIndex = -1) or (CurOpIndex < OpIndex)) then begin OpIndex := CurOpIndex; FoundOp := CurOp; end; end; if OpIndex = -1 then begin result := False; Exit; end; LOperand := fcGetToken(s, ' ', OpIndex - 1); ROperand := fcGetToken(s, ' ', OpIndex + 1); result := True; end; class procedure TfcEvaluator.ValidateString(s: String); var i: Integer; begin for i := 1 to Length(s) do if (not (s[i] in ['+', '-', '*', '/', ',', ' '])) and (not (ord(s[i]) in [48..57])) then raise EInvalidOperation.Create('Only alpha characters "+", "-", "x", and "/" are allowed.'); end; class procedure TfcEvaluator.FixString(var s: String); var CurOp: TOperator; begin for CurOp := Low(TOperator) to High(TOperator) do s := fcReplace(s, OPERATORSCHAR[CurOp], ' ' + OPERATORSCHAR[CurOp] + ' '); while Pos(' ', s) > 0 do s := fcReplace(s, ' ', ' '); end; class function TfcEvaluator.Evaluate(s: string): Integer; var LOperand, ROperand: string; IntLOperand, IntROperand: Integer; FoundOp: TOperator; CurResult: Integer; begin ValidateString(s); FixString(s); CurResult := -1; while GetOperands(s, [opMultiply, opDivide], LOperand, ROperand, FoundOp) or GetOperands(s, [opAdd, opSubtract], LOperand, ROperand, FoundOp) do begin IntLOperand := StrtoInt(LOperand); IntROperand := StrtoInt(ROperand); case FoundOp of opMultiply: CurResult := IntLOperand * IntROperand; opDivide: if IntROperand <> 0 then CurResult := IntLOperand div IntROperand else raise EInvalidOperation.Create('Divide By Zero Error'); opAdd: CurResult := IntLOperand + IntROperand; opSubtract: CurResult := IntLOperand - IntROperand; end; s := fcReplace(s, LOperand + ' ' + OPERATORSCHAR[FoundOp] + ' ' + ROperand, InttoStr(CurResult)); end; result := StrToInt(s); end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Mapper.Intf Description : Quick Mapper Interface Author : Kike Pérez Version : 1.8 Created : 07/02/2020 Modified : 14/02/2020 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Mapper.Intf; {$i QuickLib.inc} interface type TMapTarget = record private fSrcObj : TObject; public constructor Create(aSrcObj : TObject); function AsType<T : class, constructor> : T; end; IMapper = interface ['{A4EBC4BC-94D0-4F32-98FD-4888E1EF199A}'] procedure Map(aSrcObj, aTgtObj : TObject); overload; function Map(aSrcObj : TObject) : TMapTarget; overload; end; implementation end.
unit StatusBarButtonWords; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\StatusBarButtonWords.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "StatusBarButtonWords" MUID: (54DB6FD1016A) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If Defined(Nemesis) AND NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // Defined(Nemesis) AND NOT Defined(NoScripts) implementation {$If Defined(Nemesis) AND NOT Defined(NoScripts)} uses l3ImplUses , nscStatusBarButton , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *54DB6FD1016Aimpl_uses* //#UC END# *54DB6FD1016Aimpl_uses* ; type TkwPopStatusBarButtonIsDown = {final} class(TtfwClassLike) {* Слово скрипта pop:StatusBarButton:IsDown } private function IsDown(const aCtx: TtfwContext; aStatusBarButton: TnscStatusBarButton): Boolean; {* Реализация слова скрипта pop:StatusBarButton:IsDown } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopStatusBarButtonIsDown function TkwPopStatusBarButtonIsDown.IsDown(const aCtx: TtfwContext; aStatusBarButton: TnscStatusBarButton): Boolean; {* Реализация слова скрипта pop:StatusBarButton:IsDown } //#UC START# *552FC9C10154_552FC9C10154_503DE6F30027_Word_var* //#UC END# *552FC9C10154_552FC9C10154_503DE6F30027_Word_var* begin //#UC START# *552FC9C10154_552FC9C10154_503DE6F30027_Word_impl* Result := aStatusBarButton.Down; //#UC END# *552FC9C10154_552FC9C10154_503DE6F30027_Word_impl* end;//TkwPopStatusBarButtonIsDown.IsDown class function TkwPopStatusBarButtonIsDown.GetWordNameForRegister: AnsiString; begin Result := 'pop:StatusBarButton:IsDown'; end;//TkwPopStatusBarButtonIsDown.GetWordNameForRegister function TkwPopStatusBarButtonIsDown.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopStatusBarButtonIsDown.GetResultTypeInfo function TkwPopStatusBarButtonIsDown.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopStatusBarButtonIsDown.GetAllParamsCount function TkwPopStatusBarButtonIsDown.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TnscStatusBarButton)]); end;//TkwPopStatusBarButtonIsDown.ParamsTypes procedure TkwPopStatusBarButtonIsDown.DoDoIt(const aCtx: TtfwContext); var l_aStatusBarButton: TnscStatusBarButton; begin try l_aStatusBarButton := TnscStatusBarButton(aCtx.rEngine.PopObjAs(TnscStatusBarButton)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aStatusBarButton: TnscStatusBarButton : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsDown(aCtx, l_aStatusBarButton)); end;//TkwPopStatusBarButtonIsDown.DoDoIt initialization TkwPopStatusBarButtonIsDown.RegisterInEngine; {* Регистрация pop_StatusBarButton_IsDown } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscStatusBarButton)); {* Регистрация типа TnscStatusBarButton } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // Defined(Nemesis) AND NOT Defined(NoScripts) end.
Program roman (output); Var i : integer; Procedure romanout(i: integer); (* prints roman representation of i *) Var pos: integer; scale: array [1..7] Of Record amount: integer; sign : char End; Begin (*romanout*) scale[1]. amount := 1; scale[1]. sign := 'I'; scale[2]. amount := 5; scale[2]. sign := 'V'; scale[3]. amount := 10; scale[3]. sign := 'X'; scale[4]. amount := 50; scale[4]. sign := 'L'; scale[5]. amount := 100; scale[5]. sign := 'C'; scale[6]. amount := 500; scale[6]. sign := 'D'; scale[7]. amount := 1000; scale[7]. sign := 'M'; write(' '); For pos := 7 Downto 1 Do While i>= scale[pos].amount Do Begin i := i- scale[pos].amount; write(scale[pos].sign) End; End (*romanout*); Begin (*main program*) i := 1; While i<= 5000 Do Begin write(i); romanout(i); writeln; i := i*2 End End (*roman*).
unit parser; { ################################################################################ Author: Ulrich Hornung Date: 16.6.2008 Modified: 13.02.2010 This Unit is only for parsing HTML-Code in single tags. Thus html is a kind of XML it can also be used for parsing XML-Code. WARNING: Some spezial HTML-Tags are treated in an unnormal way! i.e. <script></script> ################################################################################ } interface uses Classes, SysUtils, fast_strings, parser_types; type THTMLParser = class private fCurPos: integer; AttrList: TList; fHTMLCode: string; procedure ClearAttrList; function GetCurrAttr(Index: Integer): THTMLParser_Attribute; function AddAttribute(Name, Value: String): Integer; function getCP: Integer; procedure setCP(const Value: Integer); procedure StartParser; public CurName: string; CurTagType: THTMLParserTagType; CurContent: String; Ready: Boolean; property CurPosition: Integer read getCP write setCP; property CurrAttr[Index: Integer]: THTMLParser_Attribute read GetCurrAttr; function Parse: Boolean; constructor Create(htmlcode: string); destructor Destroy; override; function AttrCount: Integer; end; function ReadTagValue(html: string; pos: Integer; var TagValue: string): Integer; function ReadAttribute(html: string; var Position: integer; var TagName, TagValue: string): boolean; implementation function THTMLParser.AddAttribute(Name, Value: String): Integer; var attr: PHTMLParser_Attribute; begin New(attr); attr^.Name := Name; attr^.Value := Value; Result := AttrList.Add(attr); end; function THTMLParser.AttrCount: Integer; begin Result := AttrList.Count; end; procedure THTMLParser.ClearAttrList; begin while AttrList.Count > 0 do begin { Hier war das Speicherleck: Dispose(AttrList[0]); Wenn Dispose nicht weis welchen Typ es freizugeben hat, Kann es keine Dynamischen String/Arrays mitfreigeben! Siehe Online-Hilfe "Finalize" Deswegen: } Dispose(PHTMLParser_Attribute(AttrList[0])); AttrList.Delete(0); end; end; constructor THTMLParser.Create(htmlcode: string); begin inherited Create(); fHTMLCode := htmlcode; AttrList := TList.Create; StartParser; end; destructor THTMLParser.Destroy; begin AttrList.Free; inherited; end; function THTMLParser.getCP: Integer; begin result := fCurPos; end; function THTMLParser.GetCurrAttr(Index: Integer): THTMLParser_Attribute; begin Result := THTMLParser_Attribute(AttrList[Index]^); end; function THTMLParser.Parse: Boolean; var ps, pe, tmp: Integer; aname, aval: string; treffer: char; begin ClearAttrList(); //Wenn am ende des strings angekommen -> fertig! If CurPosition >= length(fHTMLCode) then begin Result := False; Ready := True; Exit; end; ps := CurPosition; //Wenn Letzter Tag ein Starttag war und "script" hieß, muss der nächste tag </script> sein! if (CurTagType = pttStartTag)and(LowerCase(CurName) = 'script') then CurPosition := pos_no_case(fHTMLCode,'</script',length(fHTMLCode),8,CurPosition) else CurPosition := char_pos(fHTMLCode,'<',CurPosition); CurTagType := pttNone; //Wenn Ende erreicht, rest noch als content zurückgeben! if CurPosition = 0 then CurPosition := length(fHTMLCode)+1; //teste auf content if (ps < CurPosition) then begin CurTagType := pttContent; CurContent := Copy(fHTMLCode,ps,CurPosition-ps); Result := true; Exit; end; if (CurPosition > 0)and(fHTMLCode[CurPosition+1] = '/') then begin CurTagType := pttEndTag; CurPosition := CurPosition+1; end else CurTagType := pttStartTag; //Tagname lesen treffer := find_first_char(fHTMLCode, '! >'#9#13, CurPosition, pe); if fHTMLCode[pe-1] = '/' then pe := pe-1; CurName := Copy(fHTMLCode,CurPosition+1,pe-CurPosition-1); // Kommentar? oder CDATA? if (treffer = '!') then begin CurName := Copy(fHTMLCode, CurPosition+1, 3); if CurName = '!--' then begin CurTagType := pttComment; pe := fast_pos(fHTMLCode,'-->',length(fHTMLCode),3,CurPosition); CurContent := Copy(fHTMLCode,CurPosition,pe-CurPosition+3); CurPosition := pe+3; Result := true; Exit; end else begin CurName := Copy(fHTMLCode, CurPosition+1, 8); if CurName = '![CDATA[' then begin CurPosition := CurPosition + 9; CurTagType := pttContent; pe := fast_pos(fHTMLCode,']]>',length(fHTMLCode),3,CurPosition); CurContent := Copy(fHTMLCode,CurPosition,pe-CurPosition); CurPosition := pe+3; Result := true; Exit; end else begin CurName := '!???'; end; end; end; CurPosition := pe; tmp := CurPosition; while ReadAttribute(fHTMLCode, tmp, aname, aval) do begin //Wenn Attribute vorhanden, dann lese die erst ein. Ansonsten breche ab! AddAttribute(aname,aval); end; CurPosition := tmp; if (fHTMLCode[CurPosition] = '/') then begin CurPosition := CurPosition+1; if(CurTagType = pttStartTag) then CurTagType := pttEmptyTag; end; CurPosition := CurPosition+1; Result := True; end; procedure THTMLParser.setCP(const Value: Integer); begin if Value >= fCurPos then fCurPos := Value else raise Exception.Create('THTMLParser.setCP: Step Backward detected!'); end; procedure THTMLParser.StartParser; begin CurPosition := 1; CurName := ''; CurTagType := pttNone; Ready := False; end; function ReadTagValue(html: string; pos: Integer; var TagValue: string): Integer; var Quote: Char; pe, ps: Integer; begin Result := pos; Quote := UTF8Encode(html[Result])[1]; if not((Quote = '"')or(Quote = '''')) then begin Quote := #0; ps := char_pos(html,' ',Result); pe := char_pos(html,'>',Result); // class=inactive> if (pe > 0)and((ps = 0)or(pe < ps)) then begin Result := pe; if html[Result-1] = '/' then Result := Result-1; end else Result := ps; if Result = 0 then Result := length(html)+1; end else begin pos := pos+1; while true do begin Result := char_pos(html,Quote,Result+1); if (Result = 0) then begin Result := char_pos(html,'>',Result+1); if (Result = 0) then Result := length(html)+1 else if html[Result-1] = '/' then Result := Result-1; break; end else if (not(html[Result-1] = '\')) then break; end; end; TagValue := Copy(html,pos,Result-pos); if Quote <> #0 then inc(Result); end; function ReadAttribute(html: string; var Position: integer; var TagName, TagValue: string): boolean; var pe, pl, pg: integer; begin // trim all whitespaces at actual position while (position <= length(html))and (html[Position] <= ' ' {in [' ', #10, #13, #9]}) do Position := Position + 1; pe := char_pos(html, '>', Position); if (pe = 0) then pe := length(html); pg := char_pos(html, '=', Position); if (pg = 0) then pg := high(integer); pl := char_pos(html, ' ', Position); if (pl = 0) then pl := high(integer); //Wenn '>' das erste gefundene Zeichen ist if (pe <= pg)and(pe <= pl) then begin if html[pe-1] = '/' then dec(pe); TagName := trim(copy(html, Position, pe-position)); TagValue := TagName; Position := pe; end else //Wenn '=' das erste gefundene Zeichen ist if (pg <= pl) then begin TagName := trim(copy(html, Position, pg-position)); Position := ReadTagValue(html, pg+1, TagValue); end else //Wenn ' ' das erste gefundene Zeichen ist begin TagName := trim(copy(html, Position, pl-position)); TagValue := TagName; Position := pl; end; Result := (TagName <> ''); end; end.
unit AdoOrdenDlg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Dialogs, Controls, StdCtrls, Buttons, ImgList, htmlHelp, Db; type TAdoOrdenDialogo = class(TForm) OKBtn: TButton; CancelBtn: TButton; HelpBtn: TButton; SrcList: TListBox; DstList: TListBox; SrcLabel: TLabel; DstLabel: TLabel; IncludeBtn: TSpeedButton; IncAllBtn: TSpeedButton; ExcludeBtn: TSpeedButton; ExAllBtn: TSpeedButton; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; spUp: TSpeedButton; spDn: TSpeedButton; Img: TImageList; procedure IncludeBtnClick(Sender: TObject); procedure ExcludeBtnClick(Sender: TObject); procedure IncAllBtnClick(Sender: TObject); procedure ExcAllBtnClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure spUpClick(Sender: TObject); procedure spDnClick(Sender: TObject); procedure DstListMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); procedure DstListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure HelpBtnClick(Sender: TObject); private { Private declarations } FOrden: array of boolean; FBitUp, FBitDn: TBitmap; public { Public declarations } procedure MoveSelected(List: TCustomListBox; Items: TStrings); procedure SetItem(List: TListBox; Index: Integer); function GetFirstSelection(List: TCustomListBox): Integer; procedure SetButtons; end; var AdoOrdenDialogo: TAdoOrdenDialogo; function ShowAdoOrderDlg( Campos: TFieldList ):string; implementation {$R *.DFM} function ShowAdoOrderDlg( Campos: TFieldList ):string; var x: integer; begin with TAdoOrdenDialogo.create( application ) do try Result := ''; SrcList.Items.Assign( TStringList( Campos )); SetLength( FOrden, Campos.Count ); for x:=0 to Campos.Count-1 do FOrden[ x ] := true; ShowModal; if ModalResult = mrOK then begin for x:=0 to DstList.Items.Count-1 do begin Result := Result + DstList.Items[x]; if x < DstList.Items.Count-1 then Result := Result + ','; end; end; finally FOrden := nil; free; end; end; procedure TAdoOrdenDialogo.IncludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(SrcList); MoveSelected(SrcList, DstList.Items); SetItem(SrcList, Index); end; procedure TAdoOrdenDialogo.ExcludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(DstList); MoveSelected(DstList, SrcList.Items); SetItem(DstList, Index); end; procedure TAdoOrdenDialogo.IncAllBtnClick(Sender: TObject); var I: Integer; begin for I := 0 to SrcList.Items.Count - 1 do DstList.Items.AddObject(SrcList.Items[I], SrcList.Items.Objects[I]); SrcList.Items.Clear; SetItem(SrcList, 0); end; procedure TAdoOrdenDialogo.ExcAllBtnClick(Sender: TObject); var I: Integer; begin for I := 0 to DstList.Items.Count - 1 do SrcList.Items.AddObject(DstList.Items[I], DstList.Items.Objects[I]); DstList.Items.Clear; SetItem(DstList, 0); end; procedure TAdoOrdenDialogo.MoveSelected(List: TCustomListBox; Items: TStrings); var I: Integer; begin for I := List.Items.Count - 1 downto 0 do if List.Selected[I] then begin Items.AddObject(List.Items[I], List.Items.Objects[I]); List.Items.Delete(I); end; end; procedure TAdoOrdenDialogo.SetButtons; var SrcEmpty, DstEmpty: Boolean; begin SrcEmpty := SrcList.Items.Count = 0; DstEmpty := DstList.Items.Count = 0; IncludeBtn.Enabled := not SrcEmpty; IncAllBtn.Enabled := not SrcEmpty; ExcludeBtn.Enabled := not DstEmpty; ExAllBtn.Enabled := not DstEmpty; end; function TAdoOrdenDialogo.GetFirstSelection(List: TCustomListBox): Integer; begin for Result := 0 to List.Items.Count - 1 do if List.Selected[Result] then Exit; Result := LB_ERR; end; procedure TAdoOrdenDialogo.SetItem(List: TListBox; Index: Integer); var MaxIndex: Integer; begin with List do begin SetFocus; MaxIndex := List.Items.Count - 1; if Index = LB_ERR then Index := 0 else if Index > MaxIndex then Index := MaxIndex; Selected[Index] := True; end; SetButtons; end; procedure TAdoOrdenDialogo.SpeedButton1Click(Sender: TObject); var x, FSel: integer; Provi: string; begin FSel := -1; if DstList.SelCount > 0 then for x:=0 to DstList.Items.Count-1 do begin if DstList.Selected[ x ] then if x = 0 then exit else begin if FSel = -1 then FSel := x-1; Provi := DstList.Items[ x-1 ]; DstList.Items[ x-1 ] := DstList.Items[ x ]; DstList.Items[ x ] := Provi; end; end; if FSel <> -1 then DstList.Selected[ FSel ] := true; end; procedure TAdoOrdenDialogo.SpeedButton2Click(Sender: TObject); var x, FSel: integer; Provi: string; begin FSel := -1; if DstList.SelCount > 0 then for x:=DstList.Items.Count-1 downto 0 do begin if DstList.Selected[ x ] then if x = DstList.Items.Count-1 then exit else begin if FSel = -1 then FSel := x+1; Provi := DstList.Items[ x+1 ]; DstList.Items[ x+1 ] := DstList.Items[ x ]; DstList.Items[ x ] := Provi; end; end; if FSel <> -1 then DstList.Selected[ FSel ] := true; end; procedure TAdoOrdenDialogo.spUpClick(Sender: TObject); var x: integer; begin if DstList.SelCount > 0 then for x:=0 to DstList.Items.Count-1 do if DstList.Selected[ x ] then FOrden[ x ] := true; DstList.Invalidate; end; procedure TAdoOrdenDialogo.spDnClick(Sender: TObject); var x: integer; begin if DstList.SelCount > 0 then for x:=0 to DstList.Items.Count-1 do if DstList.Selected[ x ] then FOrden[ x ] := false; DstList.Invalidate; end; procedure TAdoOrdenDialogo.DstListMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); begin Height := DstList.Height; end; procedure TAdoOrdenDialogo.DstListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Offset: integer; begin Offset := FBitUp.width - 8 - 2; with TListBox( Control ).Canvas do begin FillRect( Rect ); TextOut( Rect.left+2, Rect.Top, TListBox( Control ).Items[ Index ]); {if FOrden[ Index ] then Img.Draw( TListBox( Control ).Canvas, Rect.right-16-2, Rect.Top, 1, true ) else Img.Draw( TListBox( Control ).Canvas, Rect.right-16-2, Rect.Top, 3, true )} end; end; procedure TAdoOrdenDialogo.FormCreate(Sender: TObject); begin FBitUp := TBitmap.create; FBitDn := TBitmap.create; { FBitUp.width := 16; FBitDn.width := 16; FBitUp.Height := 16; FBitDn.Height := 16; FBitUp.Assign( spUp.Glyph ); FBitDn.Assign( spDn.Glyph ); FBitUp.Transparent := true; FBitDn.Transparent := true;} Img.GetBitmap( 1, FBitUp ); Img.GetBitmap( 3, FBitDn ); end; procedure TAdoOrdenDialogo.FormClose(Sender: TObject; var Action: TCloseAction); begin { FBitDn.free; FBitUp.free;} end; procedure TAdoOrdenDialogo.HelpBtnClick(Sender: TObject); var Dummy: boolean; begin HH( 1, 1000, dummy); end; end.
unit SpriteLoaders; interface uses Classes, Windows, SysUtils, SpriteImages, ImageLoaders; procedure LoadFrameImage( out anImage : TFrameImage; Stream : TStream ); procedure LoadFrameImageFromFile( out anImage : TFrameImage; const Filename : string ); procedure LoadFrameImageFromResName( out anImage : TFrameImage; Instance : THandle; const ResourceName : string ); procedure LoadFrameImageFromResId( out anImage : TFrameImage; Instance : THandle; ResourceId : Integer ); implementation uses Dibs, ColorTableMgr, GDI, BitBlt, GifLoader{$IFDEF MEMREPORTS}, MemoryReports{$ENDIF}; type TDisposalMethod = (dmNone, dmDoNotDispose, dmRestToBckgrnd, dmRestToPrev); procedure LoadFrameImage( out anImage : TFrameImage; Stream : TStream ); var Images : TImages; i : integer; buffsize : integer; buff1, buff2 : pchar; palbuf : pchar; PalInfo : TPaletteInfo; TransColor : integer; dispmeth : TDisposalMethod; begin Images := GetImageLoader( Stream, nil ); try if Assigned( Images ) then with Images, DibHeader^ do begin //assert( biBitCount = 8, 'Sprites must be 8-bit images in SpriteLoaders.LoadFrameImage!!' ); LoadImages; anImage := TFrameImage.Create( biWidth, abs(biHeight) ); with anImage do begin NewFrames( ImageCount ); getmem( palbuf, DibPaletteSize( DibHeader ) ); Move( DibColors( DibHeader )^, palbuf^, DibPaletteSize( DibHeader ) ); PalInfo := TPaletteInfo.Create; PalInfo.AttachPalette( PRGBPalette(palbuf), biClrUsed ); PalInfo.Owned := true; anImage.PaletteInfo := PalInfo; anImage.OwnsPalette := true; buffsize := anImage.ImageSize; {$IFDEF MEMREPORTS} ReportMemoryAllocation(cSpriteAllocCause, 3*DibPaletteSize( DibHeader ) + sizeof(anImage) + sizeof(PalInfo)); {$ENDIF} getmem( buff1, buffsize ); try getmem( buff2, buffsize ); try TransColor := Image[0].Transparent; fillchar( buff1^, buffsize, TransColor ); for i := 0 to ImageCount - 1 do begin //!!assert( TransparentIndx = Transparent, 'Image was authored with differing transparent colors per frame, which is unsupported by sprite engine!!' ); FrameDelay[i] := Image[i].Delay*10; Image[i].Decode( PixelAddr[ 0, 0, i ], StorageWidth ); if Image[i] is TGifImageData then dispmeth := TDisposalMethod(TGifImageData(Image[i]).Disposal) else dispmeth := dmNone; case dispmeth of dmNone,dmDoNotDispose: begin BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, Image[i].Transparent, StorageWidth, Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth); end; dmRestToBckgrnd: begin BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, TransColor, StorageWidth, Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth); fillchar(buff1^, buffsize, TransColor); end; dmRestToPrev: begin move(buff1^, buff2^, buffsize); BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, TransColor, StorageWidth, Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth); if i > 0 then move(buff2^, buff1^, buffsize); end; end; end; if TransColor = -1 // Assume a transparent color then TranspIndx := anImage.Pixel[0,0,0] else TranspIndx := TransColor; finally freemem(buff2); end; finally freemem( buff1 ); end; end; end else anImage := nil; finally Images.Free; end; end; procedure LoadFrameImageFromFile( out anImage : TFrameImage; const Filename : string ); var Stream : TStream; begin Stream := TFileStream.Create( Filename, fmOpenRead or fmShareDenyWrite ); try LoadFrameImage( anImage, Stream ); finally Stream.Free; end; end; procedure LoadFrameImageFromResName( out anImage : TFrameImage; Instance : THandle; const ResourceName : string ); var Stream : TStream; begin Stream := TResourceStream.Create( Instance, ResourceName, RT_RCDATA ); try LoadFrameImage( anImage, Stream ); finally Stream.Free; end; end; procedure LoadFrameImageFromResId( out anImage : TFrameImage; Instance : THandle; ResourceId : Integer ); var Stream : TStream; begin Stream := TResourceStream.CreateFromID( Instance, ResourceId, RT_RCDATA ); try LoadFrameImage( anImage, Stream ); finally Stream.Free; end; end; end.
PROGRAM d2b; FUNCTION answer(filename:string) : integer; TYPE guide_line = array[1..3] of char; FUNCTION score(guide_l:guide_line) : integer; CONST YOU_ROCK = 'X'; YOU_PAPER = 'Y'; YOU_SCISSORS = 'Z'; YOU_LOSE = 'X'; YOU_DRAW = 'Y'; YOU_WIN = 'Z'; OPPONENT_ROCK = 'A'; OPPONENT_PAPER = 'B'; OPPONENT_SCISSORS = 'C'; VAR your_shape : char; BEGIN score := 0; {0 if you lost, 3 if draw, 6 if you won} {Find out what you need to play to get the desired outcome} CASE guide_l[3] OF YOU_LOSE: BEGIN score += 0; CASE guide_l[1] OF OPPONENT_ROCK: your_shape := YOU_SCISSORS; OPPONENT_PAPER: your_shape := YOU_ROCK; OPPONENT_SCISSORS: your_shape := YOU_PAPER; END; END; YOU_DRAW: BEGIN score += 3; CASE guide_l[1] OF OPPONENT_ROCK: your_shape := YOU_ROCK; OPPONENT_PAPER: your_shape := YOU_PAPER; OPPONENT_SCISSORS: your_shape := YOU_SCISSORS; END; END; YOU_WIN: BEGIN score += 6; CASE guide_l[1] OF OPPONENT_ROCK: your_shape := YOU_PAPER; OPPONENT_PAPER: your_shape := YOU_SCISSORS; OPPONENT_SCISSORS: your_shape := YOU_ROCK; END; END; END; {plus Score of the shape you selected} CASE your_shape OF YOU_ROCK: score += 1; YOU_PAPER: score += 2; YOU_SCISSORS: score += 3; END; END; VAR f: text; guide: ARRAY[1..2500] OF guide_line; i: integer; totscore: integer = 0; BEGIN assign(f, filename); reset(f); i := 1; WHILE not eof(f) DO BEGIN readln(f, guide[i]); i :=+ 1; totscore += score(guide[i]); END; close(f); answer := totscore; END; CONST testfile = 'd2.test.1'; filename = 'd2.input'; VAR a : integer; BEGIN{d2b} assert(answer(testfile) = 12, 'test faal'); a := answer(filename); writeln(''); writeln('answer: ', a); writeln('klaar'); END.
unit MSCacher; interface uses Classes, SysUtils, Windows, SyncObjs, CacheAgent, Collection; const SpoolTimeOut = 10 * 1000; // Ten seconds is enought SpoolPriority = tpLowest; type TMSCacher = class; // The Model Cacher TMSCacher = class public constructor Create; destructor Destroy; override; private fLock : TCriticalSection; public procedure CacheObject(ObjectCache : TObjectCache; BackgroundCache : boolean); procedure CacheObjectLinks(path, links : string); function InvalidateCache(path : string) : boolean; function RemoveCache(path : string) : boolean; private procedure DoCreateObject(const Path : string; List : TStringList; recLinks : boolean); function DoDeleteObject(const Path : string) : boolean; end; function CreateFacLink(aPath, info : string; MaxTries : integer) : boolean; implementation uses CacheCommon, CacheObjects, SpecialChars, CacheLinks;//, Logs; // TMSCacher constructor TMSCacher.Create; begin inherited Create; fLock := TCriticalSection.Create; end; destructor TMSCacher.Destroy; begin fLock.Free; inherited; end; procedure TMSCacher.CacheObject(ObjectCache : TObjectCache; BackgroundCache : boolean); begin if not BackgroundCache then begin ObjectCache.Prepare; case ObjectCache.Action of caCreate : begin fLock.Enter; try DoCreateObject(ObjectCache.Path, ObjectCache.PropertyList, ObjectCache.RecLinks); ObjectCache.PropertyList := nil; finally fLock.Leave; end; end; caDelete : begin fLock.Enter; try DoDeleteObject(ObjectCache.Path); //ObjectCache.PropertyList := nil; // >> Memory Leak found finally fLock.Leave; end; end; end; end; end; procedure TMSCacher.CacheObjectLinks(path, links : string); var Obj : TCachedObject; begin try Obj := TCachedObject.Init(Path); try Obj.Properties[LinkName] := links; Obj.CreateLinks; finally Obj.Free; end; except end; end; function TMSCacher.InvalidateCache(path : string) : boolean; var Obj : TCachedObject; begin try Obj := TCachedObject.Open(Path, false); if not (ioFileDoesntExist in Obj.IOResult) then try Obj.Properties[ppTTL] := NULLTTL; Obj.Flush; finally Obj.Free; end; result := true; except result := false; end; end; function TMSCacher.RemoveCache(path : string) : boolean; begin result := DoDeleteObject(path); end; procedure TMSCacher.DoCreateObject(const Path : string; List : TStringList; recLinks : boolean); var CachedObj : TCachedObject; begin CachedObj := TCachedObject.Create(Path, List); CachedObj.RecLinks := recLinks; try CachedObj.Flush; finally CachedObj.Free; end; end; function TMSCacher.DoDeleteObject(const Path : string) : boolean; var Obj : TCachedObject; begin try Obj := TCachedObject.Open(Path, false); Obj.Delete; result := true; except result := false; end; end; // CreateFacLink function CreateFacLink(aPath, info : string; MaxTries : integer) : boolean; var ActPath : string; FPath : string; begin try ActPath := GetCacheRootPath + aPath; FPath := ExtractFilePath(ActPath); ForceFolder(FPath); result := CacheLinks.CreateLink(ActPath, info, MaxTries); except result := false; end; end; end.
unit Installer2BuildToolFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.FileCtrl, System.IOUtils, {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} CoreClasses, PascalStrings, UnicodeMixedLib, DoStatusIO, MemoryStream64, ZDB2_FileEncoder, ZDB2_Core, CoreCipher, zExpression, ListEngine, TextDataEngine; type TInstaller2BuildToolForm = class(TForm) DirectoryEdit: TLabeledEdit; DirBrowseButton: TButton; buildButton: TButton; ThNumEdit: TLabeledEdit; ChunkEdit: TLabeledEdit; BlockEdit: TLabeledEdit; InfoLabel: TLabel; Memo: TMemo; Timer: TTimer; ProgressBar: TProgressBar; CheckBox_Encrypt: TCheckBox; SoftEdit: TLabeledEdit; procedure TimerTimer(Sender: TObject); procedure DirBrowseButtonClick(Sender: TObject); procedure buildButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private Busy: Boolean; LastState_: SystemString; procedure DoStatus_Backcall(Text_: SystemString; const ID: Integer); procedure ZDB2_File_OnProgress(State_: SystemString; Total, Current1, Current2: Int64); function EncodeDirectory(Directory_, ZDB2File_, Password_: U_String; ThNum_: Integer; chunkSize_: Int64; CM: TSelectCompressionMethod; BlockSize_: Word): Int64; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Installer2BuildToolForm: TInstaller2BuildToolForm; implementation {$R *.dfm} procedure TInstaller2BuildToolForm.TimerTimer(Sender: TObject); begin InfoLabel.Caption := LastState_; CheckThreadSynchronize; end; procedure TInstaller2BuildToolForm.DirBrowseButtonClick(Sender: TObject); var dir_: String; begin dir_ := DirectoryEdit.Text; if SelectDirectory('select source directory.', '/', dir_, [sdNewFolder, sdShowShares, sdNewUI]) then begin DirectoryEdit.Text := dir_; if SoftEdit.Text = '' then SoftEdit.Text := umlGetLastStr(DirectoryEdit.Text, '/\'); end; end; procedure TInstaller2BuildToolForm.buildButtonClick(Sender: TObject); begin if not umlDirectoryExists(DirectoryEdit.Text) then exit; Busy := True; TCompute.RunP_NP(procedure var dir_: U_String; software_: U_String; nArry: U_StringArray; n: U_SystemString; dirName: U_String; zdb2fn: U_String; passwd: U_String; te: THashTextEngine; sour: Int64; begin TCompute.Sync(procedure begin DirectoryEdit.Enabled := False; DirBrowseButton.Enabled := False; buildButton.Enabled := False; SoftEdit.Enabled := False; ThNumEdit.Enabled := False; ChunkEdit.Enabled := False; BlockEdit.Enabled := False; CheckBox_Encrypt.Enabled := False; dir_ := DirectoryEdit.Text; software_ := SoftEdit.Text; end); if software_.L = 0 then software_ := umlGetLastStr(dir_, '/\'); te := THashTextEngine.Create; te.SetDefaultText('Main___', 'Software', software_); te.SetDefaultText('Main___', 'Folder', software_); nArry := umlGetDirListWithFullPath(dir_); for n in nArry do begin if CheckBox_Encrypt.Checked then begin passwd := TPascalString.RandomString(64).DeleteChar(#32'=:[]'); end else passwd := ''; dirName := umlGetLastStr(n, '/\'); if CheckBox_Encrypt.Checked then zdb2fn := dirName + '.POX2' else zdb2fn := dirName + '.OX2'; sour := EncodeDirectory( n, umlCombineFileName(dir_, zdb2fn), passwd, EStrToInt(ThNumEdit.Text, cpuCount), EStrToInt(ChunkEdit.Text, 1024 * 1024), TSelectCompressionMethod.scmZLIB, EStrToInt(BlockEdit.Text, 4096)); DoStatus('finish %s %s -> %s', [zdb2fn.Text, umlSizetoStr(sour).Text, umlSizetoStr(umlGetFileSize(umlCombineFileName(dir_, zdb2fn))).Text]); if CheckBox_Encrypt.Checked then te.SetDefaultText(zdb2fn, 'password', passwd); te.SetDefaultText(zdb2fn, 'Directory', dirName); end; te.SaveToFile(umlCombineFileName(dir_, 'zInstall2.conf')); disposeObject(te); ZDB2_File_OnProgress('...', 100, 0, 0); if umlFileExists(umlCombineFileName(TPath.GetLibraryPath, 'zInstaller2.exe')) then umlCopyFile(umlCombineFileName(TPath.GetLibraryPath, 'zInstaller2.exe'), umlCombineFileName(dir_, 'zInstaller2.exe')); DoStatus('all finish.'); TCompute.Sync(procedure begin DirectoryEdit.Enabled := True; DirBrowseButton.Enabled := True; buildButton.Enabled := True; SoftEdit.Enabled := True; ThNumEdit.Enabled := True; ChunkEdit.Enabled := True; BlockEdit.Enabled := True; CheckBox_Encrypt.Enabled := True; end); Busy := False; end); end; procedure TInstaller2BuildToolForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TInstaller2BuildToolForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not Busy; end; procedure TInstaller2BuildToolForm.DoStatus_Backcall(Text_: SystemString; const ID: Integer); begin Memo.Lines.Add(Text_); end; function TInstaller2BuildToolForm.EncodeDirectory(Directory_, ZDB2File_, Password_: U_String; ThNum_: Integer; chunkSize_: Int64; CM: TSelectCompressionMethod; BlockSize_: Word): Int64; var cipher: TZDB2_Cipher; enc: TZDB2_File_Encoder; begin if CheckBox_Encrypt.Checked then cipher := TZDB2_Cipher.Create(TCipherSecurity.csRijndael, Password_, 1, True, True) else cipher := nil; enc := TZDB2_File_Encoder.CreateFile(cipher, ZDB2File_, ThNum_); enc.OnProgress := ZDB2_File_OnProgress; enc.EncodeFromDirectory(Directory_, True, '\', chunkSize_, CM, BlockSize_); Result := enc.Flush; disposeObject(enc); if CheckBox_Encrypt.Checked then disposeObject(cipher); end; procedure TInstaller2BuildToolForm.ZDB2_File_OnProgress(State_: SystemString; Total, Current1, Current2: Int64); begin TCompute.Sync(procedure begin ProgressBar.Max := 100; ProgressBar.Position := umlPercentageToInt64(Total, Current1); LastState_ := State_; end); end; constructor TInstaller2BuildToolForm.Create(AOwner: TComponent); begin inherited Create(AOwner); AddDoStatusHook(self, DoStatus_Backcall); StatusThreadID := False; ThNumEdit.Text := IntToStr(cpuCount); ChunkEdit.Text := '1024*1024'; BlockEdit.Text := '4*1024'; Busy := False; LastState_ := ''; end; destructor TInstaller2BuildToolForm.Destroy; begin DeleteDoStatusHook(self); inherited Destroy; end; end.
unit l3Clipboard; {* Поток для работы с буфером обмена. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Clipboard - } { Начат: 16.02.2000 11:56 } { $Id: l3Clipboard.pas,v 1.6 2010/03/18 14:15:46 lulin Exp $ } // $Log: l3Clipboard.pas,v $ // Revision 1.6 2010/03/18 14:15:46 lulin // {RequestLink:197951943}. // // Revision 1.5 2010/02/10 19:16:59 lulin // {RequestLink:186352297}. // // Revision 1.4 2001/08/29 07:01:10 law // - split unit: l3Intf -> l3BaseStream, l3BaseDraw, l3InterfacedComponent. // // Revision 1.3 2001/07/26 15:55:03 law // - comments: xHelpGen. // // Revision 1.2 2000/12/15 15:18:59 law // - вставлены директивы Log. // {$I l3Define.inc } interface uses Windows, l3Types, l3Base, l3BaseStream, l3Memory ; type Tl3ClipboardStream = class(Tl3Stream) {* Поток для работы с буфером обмена. } private {internal fields} f_ReadStream : Tl3HMemoryStream; f_WriteStream : Tl3MemoryStream; f_NeedCommit : Bool; f_IsClipboardEmpty : Bool; private {property fields} f_Format : Tl3ClipboardFormat; f_Mode : Tl3FileMode; protected {property methods} procedure pm_SetFormat(Value: Tl3ClipboardFormat); {-} protected {internal methods} procedure AppendFromClipboard; {-} procedure Commit; {-} procedure Release; override; {-} public {public methods} constructor Create(aMode : Tl3FileMode; aFormat : Tl3ClipboardFormat = cf_Text; aHandle : hWnd = 0); reintroduce; {* - создает поток. } function Seek(Offset: Longint; Origin: Word): Longint; override; {-} function Read(var Buffer; Count: Longint): Longint; override; {-} function Write(const Buffer; Count: Longint): Longint; override; {-} public {public properties} property Format: Tl3ClipboardFormat read f_Format write pm_SetFormat; {* - текущий формат с которым работает поток. } property Mode: Tl3FileMode read f_Mode; {* - режим работы потока. } end;{Tl3ClipboardStream} implementation uses SysUtils ; { start class Tl3ClipboardStream } constructor Tl3ClipboardStream.Create(aMode : Tl3FileMode; aFormat : Tl3ClipboardFormat = cf_Text; aHandle : hWnd = 0); {reintroduce;} {-} begin Win32Check(OpenClipboard(aHandle)); inherited Create; f_Mode := aMode; f_Format := aFormat; if (Mode = l3_fmRead) then f_ReadStream := Tl3HMemoryStream.Create(GetClipboardData(Format)) else begin f_WriteStream := Tl3MemoryStream.Create; AppendFromClipboard; end;//Mode = l3_fmRead end; procedure Tl3ClipboardStream.Release; {override;} {-} begin Commit; l3Free(f_ReadStream); l3Free(f_WriteStream); inherited; Win32Check(CloseClipboard); end; procedure Tl3ClipboardStream.pm_SetFormat(Value: Tl3ClipboardFormat); {-} begin if (f_Format <> Value) then begin Commit; f_Format := Value; if (Mode = l3_fmRead) then begin l3Free(f_ReadStream); f_ReadStream := Tl3HMemoryStream.Create(GetClipboardData(Format)) end//Mode = l3_fmRead else AppendFromClipboard; end;//f_Format <> Value end; procedure Tl3ClipboardStream.AppendFromClipboard; {-} var l_OldData : Tl3HMemoryStream; begin if (Mode = l3_fmAppend) AND IsClipboardFormatAvailable(Format) then begin l_OldData := Tl3HMemoryStream.Create(GetClipboardData(Format)); try f_WriteStream.CopyFrom(l_OldData, 0); finally l3Free(l_OldData); end;//try..finally f_IsClipboardEmpty := true; end;//Mode = l3_fmAppend end; procedure Tl3ClipboardStream.Commit; {-} begin if f_NeedCommit then begin f_NeedCommit := false; if not f_IsClipboardEmpty then begin Win32Check(EmptyClipboard); f_IsClipboardEmpty := true; end;//not f_IsClipboardEmpty SetClipboardData(Format, l3System.ReleaseHandle(f_WriteStream.MemoryPool.ReleaseHandle)); f_WriteStream.Seek(0, 0); end;//f_NeedCommit end; function Tl3ClipboardStream.Seek(Offset: Longint; Origin: Word): Longint; {override;} {-} begin if (Mode = l3_fmRead) then Result := f_ReadStream.Seek(Offset, Origin) else Result := f_WriteStream.Seek(Offset, Origin) end; function Tl3ClipboardStream.Read(var Buffer; Count: Longint): Longint; {override;} {-} begin if (Mode = l3_fmRead) then Result := f_ReadStream.Read(Buffer, Count) else Result := f_WriteStream.Read(Buffer, Count) end; function Tl3ClipboardStream.Write(const Buffer; Count: Longint): Longint; {override;} {-} begin if (Mode = l3_fmRead) then raise Exception.Create('Нельзя писать напрямую в Clipboard') {Result := f_ReadStream.Write(Buffer, Count)} else begin f_NeedCommit := true; Result := f_WriteStream.Write(Buffer, Count); end;//Mode = l3_fmRead end; end.
unit DW.Firebase.InstanceId; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses System.SysUtils; type TFirebaseExceptionEvent = procedure(Sender: TObject; const AException: Exception) of object; TFirebaseTokenRefreshEvent = procedure(Sender: TObject; const AToken: string) of object; TFirebaseInstanceId = class; TCustomPlatformFirebaseInstanceId = class(TObject) private FFirebaseInstanceId: TFirebaseInstanceId; protected function Start: Boolean; virtual; abstract; procedure DoException(const AException: Exception); procedure DoTokenRefresh(const AToken: string); function GetToken: string; virtual; abstract; public constructor Create(const AFirebaseInstanceId: TFirebaseInstanceId); virtual; end; TFirebaseInstanceId = class(TObject) private FIsActive: Boolean; FPlatformFirebaseInstanceId: TCustomPlatformFirebaseInstanceId; FOnException: TFirebaseExceptionEvent; FOnTokenRefresh: TFirebaseTokenRefreshEvent; function GetToken: string; protected procedure DoException(const AException: Exception); procedure DoTokenRefresh(const AToken: string); public constructor Create; destructor Destroy; override; function Start: Boolean; property IsActive: Boolean read FIsActive; property Token: string read GetToken; property OnException: TFirebaseExceptionEvent read FOnException write FOnException; property OnTokenRefresh: TFirebaseTokenRefreshEvent read FOnTokenRefresh write FOnTokenRefresh; end; implementation uses {$IF Defined(IOS)} DW.Firebase.InstanceId.iOS; {$ELSEIF Defined(ANDROID)} DW.Firebase.InstanceId.Android; {$ELSE} DW.Firebase.Default; {$ENDIF} { TCustomPlatformFirebaseInstanceId } constructor TCustomPlatformFirebaseInstanceId.Create(const AFirebaseInstanceId: TFirebaseInstanceId); begin inherited Create; FFirebaseInstanceId := AFirebaseInstanceId; end; procedure TCustomPlatformFirebaseInstanceId.DoException(const AException: Exception); begin // end; procedure TCustomPlatformFirebaseInstanceId.DoTokenRefresh(const AToken: string); begin FFirebaseInstanceId.DoTokenRefresh(AToken); end; { TFirebaseInstanceId } constructor TFirebaseInstanceId.Create; begin inherited; FPlatformFirebaseInstanceId := TPlatformFirebaseInstanceId.Create(Self); end; destructor TFirebaseInstanceId.Destroy; begin FPlatformFirebaseInstanceId.Free; inherited; end; procedure TFirebaseInstanceId.DoException(const AException: Exception); begin if Assigned(FOnException) then FOnException(Self, AException); end; procedure TFirebaseInstanceId.DoTokenRefresh(const AToken: string); begin if Assigned(FOnTokenRefresh) then FOnTokenRefresh(Self, AToken); end; function TFirebaseInstanceId.GetToken: string; begin Result := FPlatformFirebaseInstanceId.GetToken; end; function TFirebaseInstanceId.Start: Boolean; begin Result := FIsActive; if not Result then Result := FPlatformFirebaseInstanceId.Start; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSingleDC; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, Windows, {$ELSE} System.Classes, Winapi.Windows, {$ENDIF} clDC, clUtils, clDCUtils, clWinInet, clMultiDC, clResourceState, clHttpRequest, clCryptApi, clInternetConnection, clCertificate, clCertificateStore, clSspiTls, clUriUtils, clWUtils; type TclOnSingleDataItemProceed = procedure (Sender: TObject; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer) of object; TclSingleInternetControl = class(TclCustomInternetControl) private FList: TOwnedCollection; FOnDataItemProceed: TclOnSingleDataItemProceed; FOnError: TclOnError; FOnGetResourceInfo: TclOnGetResourceInfo; FOnStatusChanged: TclOnStatusChanged; FOnUrlParsing: TclOnUrlParsing; FOnChanged: TNotifyEvent; FOnGetCertificate: TclGetCertificateEvent; FOnProcessCompleted: TNotifyEvent; function GetCertificateFlags: TclCertificateVerifyFlags; function GetDataStream: TStream; function GetErrors: TclErrorList; function GetLocalFile: string; function GetPassword: string; function GetPriority: TclProcessPriority; function GetURL: string; function GetUserName_: string; procedure SetCertificateFlags(const Value: TclCertificateVerifyFlags); procedure SetDataStream(const Value: TStream); procedure SetLocalFile(const Value: string); procedure SetPassword(const Value: string); procedure SetPriority(const Value: TclProcessPriority); procedure SetURL(const Value: string); procedure SetUserName(const Value: string); function GetPort_: Integer; procedure SetPort_(const Value: Integer); function GetResourceState: TclResourceStateList; procedure SetKeepConnection(const Value: Boolean); function GetThreadCount: Integer; function GetKeepConnection: Boolean; procedure SetThreadCount(const Value: Integer); function GetInternalResourceInfo: TclResourceInfo; function GetHttpRequest: TclHttpRequest; procedure SetHttpRequest(const Value: TclHttpRequest); function GetResourceConnectionCount: Integer; function GetResourceConnections(Index: Integer): TclInternetConnection; function GetUseHttpRequest: Boolean; procedure SetUseHttpRequest(const Value: Boolean); function GetHttpResponseHeader: TStrings; protected procedure NotifyInternetItems(AComponent: TComponent); override; function GetInternetItem(): TclInternetItem; function GetInternetItemClass(): TclInternetItemClass; virtual; abstract; procedure Changed(Item: TclInternetItem); override; procedure DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); override; procedure DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); override; procedure DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); override; procedure DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); override; procedure DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); override; procedure DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); override; procedure DoProcessCompleted(Item: TclInternetItem); override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure CloseConnection(); procedure Stop; function GetResourceInfo(IsAsynch: Boolean = True): TclResourceInfo; procedure Start(IsAsynch: Boolean = True); procedure DeleteRemoteFile; function GetThreader(Index: Integer): TclCustomThreader; property Errors: TclErrorList read GetErrors; property ResourceInfo: TclResourceInfo read GetInternalResourceInfo; property ResourceState: TclResourceStateList read GetResourceState; property ResourceConnections[Index: Integer]: TclInternetConnection read GetResourceConnections; property ResourceConnectionCount: Integer read GetResourceConnectionCount; property DataStream: TStream read GetDataStream write SetDataStream; property HttpResponseHeader: TStrings read GetHttpResponseHeader; published property ThreadCount: Integer read GetThreadCount write SetThreadCount default DefaultThreadCount; property KeepConnection: Boolean read GetKeepConnection write SetKeepConnection default False; property URL: string read GetURL write SetURL; property LocalFile: string read GetLocalFile write SetLocalFile; property UserName: string read GetUserName_ write SetUserName; property Password: string read GetPassword write SetPassword; property Port: Integer read GetPort_ write SetPort_ default 0; property Priority: TclProcessPriority read GetPriority write SetPriority default ppNormal; property CertificateFlags: TclCertificateVerifyFlags read GetCertificateFlags write SetCertificateFlags default []; property UseHttpRequest: Boolean read GetUseHttpRequest write SetUseHttpRequest default False; property HttpRequest: TclHttpRequest read GetHttpRequest write SetHttpRequest; property OnStatusChanged: TclOnStatusChanged read FOnStatusChanged write FOnStatusChanged; property OnGetResourceInfo: TclOnGetResourceInfo read FOnGetResourceInfo write FOnGetResourceInfo; property OnDataItemProceed: TclOnSingleDataItemProceed read FOnDataItemProceed write FOnDataItemProceed; property OnError: TclOnError read FOnError write FOnError; property OnUrlParsing: TclOnUrlParsing read FOnUrlParsing write FOnUrlParsing; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property OnGetCertificate: TclGetCertificateEvent read FOnGetCertificate write FOnGetCertificate; property OnProcessCompleted: TNotifyEvent read FOnProcessCompleted write FOnProcessCompleted; end; implementation { TclSingleInternetControl } procedure TclSingleInternetControl.Changed(Item: TclInternetItem); begin if Assigned(FOnChanged) then begin FOnChanged(Self); end; end; procedure TclSingleInternetControl.DoDataItemProceed(Item: TclInternetItem; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PclChar; CurrentDataSize: Integer); begin if Assigned(FOnDataItemProceed) then begin FOnDataItemProceed(Self, ResourceInfo, AStateItem, CurrentData, CurrentDataSize); end; inherited DoDataItemProceed(Item, ResourceInfo, AStateItem, CurrentData, CurrentDataSize); end; procedure TclSingleInternetControl.DoError(Item: TclInternetItem; const Error: string; ErrorCode: Integer); begin if Assigned(FOnError) then begin FOnError(Self, Error, ErrorCode); end; end; procedure TclSingleInternetControl.DoGetResourceInfo(Item: TclInternetItem; AResourceInfo: TclResourceInfo); begin if Assigned(FOnGetResourceInfo) then begin FOnGetResourceInfo(Self, AResourceInfo); end; end; procedure TclSingleInternetControl.DoStatusChanged(Item: TclInternetItem; Status: TclProcessStatus); begin if Assigned(FOnStatusChanged) then begin FOnStatusChanged(Self, Status); end; inherited DoStatusChanged(Item, Status); end; procedure TclSingleInternetControl.DoURLParsing(Item: TclInternetItem; var URLComponents: TURLComponents); begin if Assigned(FOnUrlParsing) then begin FOnUrlParsing(Self, URLComponents); end; end; function TclSingleInternetControl.GetResourceInfo(IsAsynch: Boolean): TclResourceInfo; begin Result := GetInternetItem().GetResourceInfo(IsAsynch); end; procedure TclSingleInternetControl.Start(IsAsynch: Boolean); begin GetInternetItem().Start(IsAsynch); end; procedure TclSingleInternetControl.Stop; begin GetInternetItem().Stop(); end; procedure TclSingleInternetControl.DoProcessCompleted(Item: TclInternetItem); begin if Assigned(FOnProcessCompleted) then begin FOnProcessCompleted(Self); end; end; procedure TclSingleInternetControl.DoGetCertificate(Item: TclInternetItem; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin if Assigned(FOnGetCertificate) then begin FOnGetCertificate(Self, ACertificate, AExtraCerts, Handled); end; end; function TclSingleInternetControl.GetCertificateFlags: TclCertificateVerifyFlags; begin Result := GetInternetItem().CertificateFlags; end; function TclSingleInternetControl.GetDataStream: TStream; begin Result := GetInternetItem().DataStream; end; function TclSingleInternetControl.GetErrors: TclErrorList; begin Result := GetInternetItem().Errors; end; function TclSingleInternetControl.GetLocalFile: string; begin Result := GetInternetItem().LocalFile; end; function TclSingleInternetControl.GetPassword: string; begin Result := GetInternetItem().Password; end; function TclSingleInternetControl.GetPriority: TclProcessPriority; begin Result := GetInternetItem().Priority; end; function TclSingleInternetControl.GetURL: string; begin Result := GetInternetItem().URL; end; function TclSingleInternetControl.GetUserName_: string; begin Result := GetInternetItem().UserName; end; procedure TclSingleInternetControl.SetCertificateFlags(const Value: TclCertificateVerifyFlags); begin GetInternetItem().CertificateFlags := Value; end; procedure TclSingleInternetControl.SetDataStream(const Value: TStream); begin GetInternetItem().DataStream := Value; end; procedure TclSingleInternetControl.SetLocalFile(const Value: string); begin GetInternetItem().LocalFile := Value; end; procedure TclSingleInternetControl.SetPassword(const Value: string); begin GetInternetItem().Password := Value; end; procedure TclSingleInternetControl.SetPriority(const Value: TclProcessPriority); begin GetInternetItem().Priority := Value; end; procedure TclSingleInternetControl.SetURL(const Value: string); begin GetInternetItem().URL := Value; end; procedure TclSingleInternetControl.SetUserName(const Value: string); begin GetInternetItem().UserName := Value; end; function TclSingleInternetControl.GetResourceState: TclResourceStateList; begin Result := GetInternetItem().ResourceState; end; procedure TclSingleInternetControl.SetKeepConnection(const Value: Boolean); begin GetInternetItem().KeepConnection := Value; end; function TclSingleInternetControl.GetThreadCount: Integer; begin Result := GetInternetItem().ThreadCount; end; function TclSingleInternetControl.GetKeepConnection: Boolean; begin Result := GetInternetItem().KeepConnection; end; procedure TclSingleInternetControl.SetThreadCount(const Value: Integer); begin GetInternetItem().ThreadCount := Value; end; procedure TclSingleInternetControl.CloseConnection; begin GetInternetItem().CloseConnection(); end; constructor TclSingleInternetControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FList := TOwnedCollection.Create(Self, GetInternetItemClass()); FList.Add(); end; destructor TclSingleInternetControl.Destroy(); begin FList.Free(); inherited Destroy(); end; function TclSingleInternetControl.GetInternetItem(): TclInternetItem; begin Result := (FList.Items[0] as TclInternetItem); end; function TclSingleInternetControl.GetInternalResourceInfo: TclResourceInfo; begin Result := GetInternetItem().ResourceInfo; end; type TclInternetItemAccess = class(TclInternetItem); procedure TclSingleInternetControl.NotifyInternetItems(AComponent: TComponent); begin if (GetInternetItem().HttpRequest = AComponent) then begin TclInternetItemAccess(GetInternetItem()).InternalSetHttpRequest(nil); end; end; function TclSingleInternetControl.GetHttpRequest: TclHttpRequest; begin Result := GetInternetItem().HttpRequest; end; procedure TclSingleInternetControl.SetHttpRequest(const Value: TclHttpRequest); begin GetInternetItem().HttpRequest := Value; end; function TclSingleInternetControl.GetResourceConnectionCount: Integer; begin Result := GetInternetItem().ResourceConnectionCount; end; function TclSingleInternetControl.GetResourceConnections( Index: Integer): TclInternetConnection; begin Result := GetInternetItem().ResourceConnections[Index]; end; function TclSingleInternetControl.GetUseHttpRequest: Boolean; begin Result := GetInternetItem().UseHttpRequest; end; procedure TclSingleInternetControl.SetUseHttpRequest(const Value: Boolean); begin GetInternetItem().UseHttpRequest := Value; end; function TclSingleInternetControl.GetHttpResponseHeader: TStrings; begin Result := GetInternetItem().HttpResponseHeader; end; procedure TclSingleInternetControl.DeleteRemoteFile; begin GetInternetItem().DeleteRemoteFile(); end; function TclSingleInternetControl.GetPort_: Integer; begin Result := GetInternetItem().Port; end; procedure TclSingleInternetControl.SetPort_(const Value: Integer); begin GetInternetItem().Port := Value; end; function TclSingleInternetControl.GetThreader(Index: Integer): TclCustomThreader; begin Result := GetInternetItem().GetThreader(Index); end; end.
unit gMap; //============================================================================= // gUnitAI.pas //============================================================================= // // Handles map generation, point conversions and general world computation // //============================================================================= interface uses SysUtils, SwinGame, sgTypes, gTypes, Math; procedure GenerateMap(var game : GameData); function WorldToScreen(point : Point2D): Point2D; function ScreenToWorld(point : Point2D): Point2D; function ScreenToReal(point : Point2D): Point2D; function RealToWorld(point : Point2D): Point2D; function WorldBuilding(point : Point2D; sprite : Sprite): Point2D; function WorldBuilding(point : Point2D; bitmap : Bitmap): Point2D; function Point(x,y: Integer): Point2D; function Point(x,y: Single): Point2D; function NewPoint(x,y: Single): Point2D; function PointOfInt(x,y: Integer): Point2D; function MapDistance(a,b : Point2D): Double; function PlotIsAvailable(const game : GameData; loc : Point2D): Boolean; function FindNeighbours(var game : GameData; pt : Point2D): TileArray; implementation // Loads a tile into the game world procedure LoadTile(var game : GameData; point : Point2D; t : Integer); begin game.map[Round(point.x), Round(point.y)].tType := game.tileTypes[t]; game.map[Round(point.x), Round(point.y)].bitmap := game.map[Round(point.x), Round(point.y)].tType.bitmap; game.map[Round(point.x), Round(point.y)].loc := point; game.map[Round(point.x), Round(point.y)].hasBuilding := false; end; // Generates the map tiles procedure GenerateMap(var game : GameData); var x,y: Integer; begin DebugMsg('Map: Generating tiles...'); DebugMsg('Map: Width - ' + IntToStr(MAP_WIDTH) + ' tiles'); DebugMsg('Map: Height - ' + IntToStr(MAP_HEIGHT) + ' tiles'); for x := 0 to MAP_WIDTH do begin for y := 0 to MAP_HEIGHT do begin // @todo Dynamic map generation // WriteLn(IntToStr(Length(game.tileTypes))); game.map[x,y].tType := game.tileTypes[1]; game.map[x,y].bitmap := game.map[x,y].tType.bitmap; game.map[x,y].hasBuilding := false; end; end; LoadTile(game, Point(0,5), 3); LoadTile(game, Point(0,10), 3); LoadTile(game, Point(0,15), 3); LoadTile(game, Point(0,20), 3); LoadTile(game, Point(0,25), 3); LoadTile(game, Point(0,30), 3); LoadTile(game, Point(1,5), 3); LoadTile(game, Point(1,10), 3); LoadTile(game, Point(1,15), 3); LoadTile(game, Point(1,20), 3); LoadTile(game, Point(1,25), 3); LoadTile(game, Point(1,30), 3); LoadTile(game, Point(2,5), 3); LoadTile(game, Point(2,10), 3); LoadTile(game, Point(2,15), 3); LoadTile(game, Point(2,20), 3); LoadTile(game, Point(2,25), 3); LoadTile(game, Point(2,30), 3); LoadTile(game, Point(3,5), 3); LoadTile(game, Point(3,10), 3); LoadTile(game, Point(3,15), 3); LoadTile(game, Point(3,20), 3); LoadTile(game, Point(3,25), 3); LoadTile(game, Point(3,30), 3); LoadTile(game, Point(4,5), 3); LoadTile(game, Point(4,10), 3); LoadTile(game, Point(4,15), 3); LoadTile(game, Point(4,20), 3); LoadTile(game, Point(4,25), 3); LoadTile(game, Point(4,30), 3); LoadTile(game, Point(5,0), 4); LoadTile(game, Point(5,1), 4); LoadTile(game, Point(5,2), 4); LoadTile(game, Point(5,3), 4); LoadTile(game, Point(5,4), 4); LoadTile(game, Point(5,5), 3); LoadTile(game, Point(5,5), 4); LoadTile(game, Point(5,6), 4); LoadTile(game, Point(5,7), 4); LoadTile(game, Point(5,8), 4); LoadTile(game, Point(5,9), 4); LoadTile(game, Point(5,10), 3); LoadTile(game, Point(5,10), 4); LoadTile(game, Point(5,11), 4); LoadTile(game, Point(5,12), 4); LoadTile(game, Point(5,13), 4); LoadTile(game, Point(5,14), 4); LoadTile(game, Point(5,15), 3); LoadTile(game, Point(5,15), 4); LoadTile(game, Point(5,16), 4); LoadTile(game, Point(5,17), 4); LoadTile(game, Point(5,18), 4); LoadTile(game, Point(5,19), 4); LoadTile(game, Point(5,20), 3); LoadTile(game, Point(5,20), 4); LoadTile(game, Point(5,21), 4); LoadTile(game, Point(5,22), 4); LoadTile(game, Point(5,23), 4); LoadTile(game, Point(5,24), 4); LoadTile(game, Point(5,25), 3); LoadTile(game, Point(5,25), 4); LoadTile(game, Point(5,26), 4); LoadTile(game, Point(5,27), 4); LoadTile(game, Point(5,28), 4); LoadTile(game, Point(5,29), 4); LoadTile(game, Point(5,30), 3); LoadTile(game, Point(5,30), 4); LoadTile(game, Point(5,31), 4); LoadTile(game, Point(5,32), 4); LoadTile(game, Point(6,5), 3); LoadTile(game, Point(6,10), 3); LoadTile(game, Point(6,15), 3); LoadTile(game, Point(6,20), 3); LoadTile(game, Point(6,25), 3); LoadTile(game, Point(6,30), 3); LoadTile(game, Point(7,5), 3); LoadTile(game, Point(7,10), 3); LoadTile(game, Point(7,15), 3); LoadTile(game, Point(7,20), 3); LoadTile(game, Point(7,25), 3); LoadTile(game, Point(7,30), 3); LoadTile(game, Point(8,5), 3); LoadTile(game, Point(8,10), 3); LoadTile(game, Point(8,15), 3); LoadTile(game, Point(8,20), 3); LoadTile(game, Point(8,25), 3); LoadTile(game, Point(8,30), 3); LoadTile(game, Point(9,5), 3); LoadTile(game, Point(9,10), 3); LoadTile(game, Point(9,15), 3); LoadTile(game, Point(9,20), 3); LoadTile(game, Point(9,25), 3); LoadTile(game, Point(9,30), 3); LoadTile(game, Point(10,0), 4); LoadTile(game, Point(10,1), 4); LoadTile(game, Point(10,2), 4); LoadTile(game, Point(10,3), 4); LoadTile(game, Point(10,4), 4); LoadTile(game, Point(10,5), 3); LoadTile(game, Point(10,5), 4); LoadTile(game, Point(10,6), 4); LoadTile(game, Point(10,7), 4); LoadTile(game, Point(10,8), 4); LoadTile(game, Point(10,9), 4); LoadTile(game, Point(10,10), 3); LoadTile(game, Point(10,10), 4); LoadTile(game, Point(10,11), 4); LoadTile(game, Point(10,12), 4); LoadTile(game, Point(10,13), 4); LoadTile(game, Point(10,14), 4); LoadTile(game, Point(10,15), 3); LoadTile(game, Point(10,15), 4); LoadTile(game, Point(10,16), 4); LoadTile(game, Point(10,17), 4); LoadTile(game, Point(10,18), 4); LoadTile(game, Point(10,19), 4); LoadTile(game, Point(10,20), 3); LoadTile(game, Point(10,20), 4); LoadTile(game, Point(10,21), 4); LoadTile(game, Point(10,22), 4); LoadTile(game, Point(10,23), 4); LoadTile(game, Point(10,24), 4); LoadTile(game, Point(10,25), 3); LoadTile(game, Point(10,25), 4); LoadTile(game, Point(10,26), 4); LoadTile(game, Point(10,27), 4); LoadTile(game, Point(10,28), 4); LoadTile(game, Point(10,29), 4); LoadTile(game, Point(10,30), 3); LoadTile(game, Point(10,30), 4); LoadTile(game, Point(10,31), 4); LoadTile(game, Point(10,32), 4); LoadTile(game, Point(11,5), 3); LoadTile(game, Point(11,10), 3); LoadTile(game, Point(11,11), 2); LoadTile(game, Point(11,12), 2); LoadTile(game, Point(11,13), 2); LoadTile(game, Point(11,14), 2); LoadTile(game, Point(11,15), 3); LoadTile(game, Point(11,15), 2); LoadTile(game, Point(11,16), 2); LoadTile(game, Point(11,17), 2); LoadTile(game, Point(11,18), 2); LoadTile(game, Point(11,19), 2); LoadTile(game, Point(11,20), 3); LoadTile(game, Point(11,25), 3); LoadTile(game, Point(11,30), 3); LoadTile(game, Point(12,5), 3); LoadTile(game, Point(12,10), 3); LoadTile(game, Point(12,11), 2); LoadTile(game, Point(12,12), 2); LoadTile(game, Point(12,13), 2); LoadTile(game, Point(12,14), 2); LoadTile(game, Point(12,15), 3); LoadTile(game, Point(12,15), 2); LoadTile(game, Point(12,16), 2); LoadTile(game, Point(12,17), 2); LoadTile(game, Point(12,18), 2); LoadTile(game, Point(12,19), 2); LoadTile(game, Point(12,20), 3); LoadTile(game, Point(12,25), 3); LoadTile(game, Point(12,30), 3); LoadTile(game, Point(13,5), 3); LoadTile(game, Point(13,10), 3); LoadTile(game, Point(13,11), 2); LoadTile(game, Point(13,12), 2); LoadTile(game, Point(13,13), 2); LoadTile(game, Point(13,14), 2); LoadTile(game, Point(13,15), 3); LoadTile(game, Point(13,15), 2); LoadTile(game, Point(13,16), 2); LoadTile(game, Point(13,17), 2); LoadTile(game, Point(13,18), 2); LoadTile(game, Point(13,19), 2); LoadTile(game, Point(13,20), 3); LoadTile(game, Point(13,25), 3); LoadTile(game, Point(13,30), 3); LoadTile(game, Point(14,5), 3); LoadTile(game, Point(14,10), 3); LoadTile(game, Point(14,11), 2); LoadTile(game, Point(14,12), 2); LoadTile(game, Point(14,13), 2); LoadTile(game, Point(14,14), 2); LoadTile(game, Point(14,15), 3); LoadTile(game, Point(14,15), 2); LoadTile(game, Point(14,16), 2); LoadTile(game, Point(14,17), 2); LoadTile(game, Point(14,18), 2); LoadTile(game, Point(14,19), 2); LoadTile(game, Point(14,20), 3); LoadTile(game, Point(14,25), 3); LoadTile(game, Point(14,30), 3); LoadTile(game, Point(15,0), 4); LoadTile(game, Point(15,1), 4); LoadTile(game, Point(15,2), 4); LoadTile(game, Point(15,3), 4); LoadTile(game, Point(15,4), 4); LoadTile(game, Point(15,5), 3); LoadTile(game, Point(15,5), 4); LoadTile(game, Point(15,6), 4); LoadTile(game, Point(15,7), 4); LoadTile(game, Point(15,8), 4); LoadTile(game, Point(15,9), 4); LoadTile(game, Point(15,10), 3); LoadTile(game, Point(15,10), 4); LoadTile(game, Point(15,11), 4); LoadTile(game, Point(15,11), 2); LoadTile(game, Point(15,12), 4); LoadTile(game, Point(15,12), 2); LoadTile(game, Point(15,13), 4); LoadTile(game, Point(15,13), 2); LoadTile(game, Point(15,14), 4); LoadTile(game, Point(15,14), 2); LoadTile(game, Point(15,15), 3); LoadTile(game, Point(15,15), 4); LoadTile(game, Point(15,15), 2); LoadTile(game, Point(15,16), 4); LoadTile(game, Point(15,16), 2); LoadTile(game, Point(15,17), 4); LoadTile(game, Point(15,17), 2); LoadTile(game, Point(15,18), 4); LoadTile(game, Point(15,18), 2); LoadTile(game, Point(15,19), 4); LoadTile(game, Point(15,19), 2); LoadTile(game, Point(15,20), 3); LoadTile(game, Point(15,20), 4); LoadTile(game, Point(15,21), 4); LoadTile(game, Point(15,22), 4); LoadTile(game, Point(15,23), 4); LoadTile(game, Point(15,24), 4); LoadTile(game, Point(15,25), 3); LoadTile(game, Point(15,25), 4); LoadTile(game, Point(15,26), 4); LoadTile(game, Point(15,27), 4); LoadTile(game, Point(15,28), 4); LoadTile(game, Point(15,29), 4); LoadTile(game, Point(15,30), 3); LoadTile(game, Point(15,30), 4); LoadTile(game, Point(15,31), 4); LoadTile(game, Point(15,32), 4); LoadTile(game, Point(16,5), 3); LoadTile(game, Point(16,10), 3); LoadTile(game, Point(16,11), 2); LoadTile(game, Point(16,12), 2); LoadTile(game, Point(16,13), 2); LoadTile(game, Point(16,14), 2); LoadTile(game, Point(16,15), 3); LoadTile(game, Point(16,15), 2); LoadTile(game, Point(16,16), 2); LoadTile(game, Point(16,17), 2); LoadTile(game, Point(16,18), 2); LoadTile(game, Point(16,19), 2); LoadTile(game, Point(16,20), 3); LoadTile(game, Point(16,25), 3); LoadTile(game, Point(16,30), 3); LoadTile(game, Point(17,5), 3); LoadTile(game, Point(17,10), 3); LoadTile(game, Point(17,11), 2); LoadTile(game, Point(17,12), 2); LoadTile(game, Point(17,13), 2); LoadTile(game, Point(17,14), 2); LoadTile(game, Point(17,15), 3); LoadTile(game, Point(17,15), 2); LoadTile(game, Point(17,16), 2); LoadTile(game, Point(17,17), 2); LoadTile(game, Point(17,18), 2); LoadTile(game, Point(17,19), 2); LoadTile(game, Point(17,20), 3); LoadTile(game, Point(17,25), 3); LoadTile(game, Point(17,30), 3); LoadTile(game, Point(18,5), 3); LoadTile(game, Point(18,10), 3); LoadTile(game, Point(18,11), 2); LoadTile(game, Point(18,12), 2); LoadTile(game, Point(18,13), 2); LoadTile(game, Point(18,14), 2); LoadTile(game, Point(18,15), 3); LoadTile(game, Point(18,15), 2); LoadTile(game, Point(18,16), 2); LoadTile(game, Point(18,17), 2); LoadTile(game, Point(18,18), 2); LoadTile(game, Point(18,19), 2); LoadTile(game, Point(18,20), 3); LoadTile(game, Point(18,25), 3); LoadTile(game, Point(18,30), 3); LoadTile(game, Point(19,5), 3); LoadTile(game, Point(19,10), 3); LoadTile(game, Point(19,11), 2); LoadTile(game, Point(19,12), 2); LoadTile(game, Point(19,13), 2); LoadTile(game, Point(19,14), 2); LoadTile(game, Point(19,15), 3); LoadTile(game, Point(19,15), 2); LoadTile(game, Point(19,16), 2); LoadTile(game, Point(19,17), 2); LoadTile(game, Point(19,18), 2); LoadTile(game, Point(19,19), 2); LoadTile(game, Point(19,20), 3); LoadTile(game, Point(19,25), 3); LoadTile(game, Point(19,30), 3); LoadTile(game, Point(20,0), 4); LoadTile(game, Point(20,1), 4); LoadTile(game, Point(20,2), 4); LoadTile(game, Point(20,3), 4); LoadTile(game, Point(20,4), 4); LoadTile(game, Point(20,5), 3); LoadTile(game, Point(20,5), 4); LoadTile(game, Point(20,6), 4); LoadTile(game, Point(20,7), 4); LoadTile(game, Point(20,8), 4); LoadTile(game, Point(20,9), 4); LoadTile(game, Point(20,10), 3); LoadTile(game, Point(20,10), 4); LoadTile(game, Point(20,11), 4); LoadTile(game, Point(20,12), 4); LoadTile(game, Point(20,13), 4); LoadTile(game, Point(20,14), 4); LoadTile(game, Point(20,15), 3); LoadTile(game, Point(20,15), 4); LoadTile(game, Point(20,16), 4); LoadTile(game, Point(20,17), 4); LoadTile(game, Point(20,18), 4); LoadTile(game, Point(20,19), 4); LoadTile(game, Point(20,20), 3); LoadTile(game, Point(20,20), 4); LoadTile(game, Point(20,21), 4); LoadTile(game, Point(20,22), 4); LoadTile(game, Point(20,23), 4); LoadTile(game, Point(20,24), 4); LoadTile(game, Point(20,25), 3); LoadTile(game, Point(20,25), 4); LoadTile(game, Point(20,26), 4); LoadTile(game, Point(20,27), 4); LoadTile(game, Point(20,28), 4); LoadTile(game, Point(20,29), 4); LoadTile(game, Point(20,30), 3); LoadTile(game, Point(20,30), 4); LoadTile(game, Point(20,31), 4); LoadTile(game, Point(20,32), 4); LoadTile(game, Point(21,5), 3); LoadTile(game, Point(21,10), 3); LoadTile(game, Point(21,15), 3); LoadTile(game, Point(21,20), 3); LoadTile(game, Point(21,25), 3); LoadTile(game, Point(21,30), 3); LoadTile(game, Point(22,5), 3); LoadTile(game, Point(22,10), 3); LoadTile(game, Point(22,15), 3); LoadTile(game, Point(22,20), 3); LoadTile(game, Point(22,25), 3); LoadTile(game, Point(22,30), 3); LoadTile(game, Point(23,5), 3); LoadTile(game, Point(23,10), 3); LoadTile(game, Point(23,15), 3); LoadTile(game, Point(23,20), 3); LoadTile(game, Point(23,25), 3); LoadTile(game, Point(23,30), 3); LoadTile(game, Point(24,5), 3); LoadTile(game, Point(24,10), 3); LoadTile(game, Point(24,15), 3); LoadTile(game, Point(24,20), 3); LoadTile(game, Point(24,25), 3); LoadTile(game, Point(24,30), 3); LoadTile(game, Point(25,0), 4); LoadTile(game, Point(25,1), 4); LoadTile(game, Point(25,2), 4); LoadTile(game, Point(25,3), 4); LoadTile(game, Point(25,4), 4); LoadTile(game, Point(25,5), 3); LoadTile(game, Point(25,5), 4); LoadTile(game, Point(25,6), 4); LoadTile(game, Point(25,7), 4); LoadTile(game, Point(25,8), 4); LoadTile(game, Point(25,9), 4); LoadTile(game, Point(25,10), 3); LoadTile(game, Point(25,10), 4); LoadTile(game, Point(25,11), 4); LoadTile(game, Point(25,12), 4); LoadTile(game, Point(25,13), 4); LoadTile(game, Point(25,14), 4); LoadTile(game, Point(25,15), 3); LoadTile(game, Point(25,15), 4); LoadTile(game, Point(25,16), 4); LoadTile(game, Point(25,17), 4); LoadTile(game, Point(25,18), 4); LoadTile(game, Point(25,19), 4); LoadTile(game, Point(25,20), 3); LoadTile(game, Point(25,20), 4); LoadTile(game, Point(25,21), 4); LoadTile(game, Point(25,22), 4); LoadTile(game, Point(25,23), 4); LoadTile(game, Point(25,24), 4); LoadTile(game, Point(25,25), 3); LoadTile(game, Point(25,25), 4); LoadTile(game, Point(25,26), 4); LoadTile(game, Point(25,27), 4); LoadTile(game, Point(25,28), 4); LoadTile(game, Point(25,29), 4); LoadTile(game, Point(25,30), 3); LoadTile(game, Point(25,30), 4); LoadTile(game, Point(25,31), 4); LoadTile(game, Point(25,32), 4); LoadTile(game, Point(26,5), 3); LoadTile(game, Point(26,10), 3); LoadTile(game, Point(26,15), 3); LoadTile(game, Point(26,20), 3); LoadTile(game, Point(26,25), 3); LoadTile(game, Point(26,30), 3); LoadTile(game, Point(27,5), 3); LoadTile(game, Point(27,10), 3); LoadTile(game, Point(27,15), 3); LoadTile(game, Point(27,20), 3); LoadTile(game, Point(27,25), 3); LoadTile(game, Point(27,30), 3); LoadTile(game, Point(28,5), 3); LoadTile(game, Point(28,10), 3); LoadTile(game, Point(28,15), 3); LoadTile(game, Point(28,20), 3); LoadTile(game, Point(28,25), 3); LoadTile(game, Point(28,30), 3); LoadTile(game, Point(29,5), 3); LoadTile(game, Point(29,10), 3); LoadTile(game, Point(29,15), 3); LoadTile(game, Point(29,20), 3); LoadTile(game, Point(29,25), 3); LoadTile(game, Point(29,30), 3); LoadTile(game, Point(30,0), 4); LoadTile(game, Point(30,1), 4); LoadTile(game, Point(30,2), 4); LoadTile(game, Point(30,3), 4); LoadTile(game, Point(30,4), 4); LoadTile(game, Point(30,5), 3); LoadTile(game, Point(30,5), 4); LoadTile(game, Point(30,6), 4); LoadTile(game, Point(30,7), 4); LoadTile(game, Point(30,8), 4); LoadTile(game, Point(30,9), 4); LoadTile(game, Point(30,10), 3); LoadTile(game, Point(30,10), 4); LoadTile(game, Point(30,11), 4); LoadTile(game, Point(30,12), 4); LoadTile(game, Point(30,13), 4); LoadTile(game, Point(30,14), 4); LoadTile(game, Point(30,15), 3); LoadTile(game, Point(30,15), 4); LoadTile(game, Point(30,16), 4); LoadTile(game, Point(30,17), 4); LoadTile(game, Point(30,18), 4); LoadTile(game, Point(30,19), 4); LoadTile(game, Point(30,20), 3); LoadTile(game, Point(30,20), 4); LoadTile(game, Point(30,21), 4); LoadTile(game, Point(30,22), 4); LoadTile(game, Point(30,23), 4); LoadTile(game, Point(30,24), 4); LoadTile(game, Point(30,25), 3); LoadTile(game, Point(30,25), 4); LoadTile(game, Point(30,26), 4); LoadTile(game, Point(30,27), 4); LoadTile(game, Point(30,28), 4); LoadTile(game, Point(30,29), 4); LoadTile(game, Point(30,30), 3); LoadTile(game, Point(30,30), 4); LoadTile(game, Point(30,31), 4); LoadTile(game, Point(30,32), 4); LoadTile(game, Point(31,5), 3); LoadTile(game, Point(31,10), 3); LoadTile(game, Point(31,15), 3); LoadTile(game, Point(31,20), 3); LoadTile(game, Point(31,25), 3); LoadTile(game, Point(31,30), 3); LoadTile(game, Point(32,5), 3); LoadTile(game, Point(32,10), 3); LoadTile(game, Point(32,15), 3); LoadTile(game, Point(32,20), 3); LoadTile(game, Point(32,25), 3); LoadTile(game, Point(32,30), 3); for x := 0 to MAP_WIDTH do begin for y := 0 to MAP_HEIGHT do begin // @todo Dynamic map generation // WriteLn(IntToStr(Length(game.tileTypes))); // game.map[x,y].tType := game.tileTypes[1]; // game.map[x,y].bitmap := game.map[x,y].tType.bitmap; // if (x = 6) and (y = 5) then // begin // game.map[x,y].bitmap := BitmapNamed('HQBuilding'); // end; // if (y mod 5 = 0) and (y > 0) then // begin // game.map[x,y].tType := game.tileTypes[3]; // game.map[x,y].bitmap := game.map[x,y].tType.bitmap; // WriteLn('LoadTile(game, Point('+IntToStr(x)+','+IntToStr(y)+'), '+IntToStr(3)+');'); // end; // if (x mod 5 = 0) and (x > 0) then // begin // game.map[x,y].tType := game.tileTypes[4]; // game.map[x,y].bitmap := game.map[x,y].tType.bitmap; // WriteLn('LoadTile(game, Point('+IntToStr(x)+','+IntToStr(y)+'), '+IntToStr(4)+');'); // end; // if (x > 10) and (y > 10) and (x < 20) and (y < 20) then // begin // game.map[x,y].tType := game.tileTypes[2]; // game.map[x,y].bitmap := game.map[x,y].tType.bitmap; // WriteLn('LoadTile(game, Point('+IntToStr(x)+','+IntToStr(y)+'), '+IntToStr(2)+');'); // continue; // end; if (x mod 5 = 0) and (x >0) and (y mod 5 = 0) and (y > 0) and not ((x = 15) and (y= 15)) then begin // game.map[x,y].tType := game.tileTypes[4]; game.map[x,y].bitmap := BitmapNamed('TileRoadIntersection'); end; if (Random(1000) > 950) then begin // game.map[x,y].tType := game.tileTypes[2]; // game.map[x,y].bitmap := BitmapNamed('GenericBuilding01'); end; end; end; DebugMsg('Map: Generating tiles... done.'); end; // Convert a map x,y to a screen x,y function WorldToScreen(point : Point2D): Point2D; begin // point.y := point.y + 1; result.x := Round((point.x * TILE_WIDTH / 2) + (point.y * TILE_WIDTH / 2)); result.y := Round((point.y * TILE_HEIGHT / 2) - (point.x * TILE_HEIGHT / 2)); end; // Convert a screen x,y to a map x,y function ScreenToWorld(point : Point2D): Point2D; begin // Since we can move the camera, we need to remap the 2d screen // point to the absolute position of the mouse point.x := point.x - ((point.x - CameraX()) - point.x); point.y := point.y - ((point.y - CameraY()) - point.y); // Calculate the world x,y coords, will return the tile the // point is in result.x := Round((point.x / TILE_WIDTH) - ((point.y - (TILE_HEIGHT / 2)) / 32) - 0.5); result.y := Round((point.x / TILE_WIDTH) + ((point.y - (TILE_HEIGHT / 2)) / 32) - 0.5); end; function ScreenToReal(point : Point2D): Point2D; begin result.x := point.x - ((point.x - CameraX()) - point.x); result.y := point.y - ((point.y - CameraY()) - point.y); end; function RealToScreen(point : Point2D) : Integer; begin end; function RealToWorld(point : Point2D): Point2D; begin result.x := Round((point.x / TILE_WIDTH) - ((point.y - (TILE_HEIGHT / 2)) / 32) - 0.5); result.y := Round((point.x / TILE_WIDTH) + ((point.y - (TILE_HEIGHT / 2)) / 32) - 0.5); end; // Get the origin point of a building, accounting for the building height function WorldBuilding(point : Point2D; sprite : Sprite): Point2D; var tempX, tempY: Single; temp : Point2D; begin point.y := point.y + 2; temp := WorldToScreen(point); result.x := temp.x - SpriteWidth(sprite); result.y := temp.y - SpriteHeight(sprite); if SpriteWidth(sprite) = 128 then begin result.x := result.x + 32; end; end; // Get the origin point of a building, accounting for the building height function WorldBuilding(point : Point2D; bitmap : Bitmap): Point2D; var tempX, tempY: Single; temp : Point2D; begin point.y := point.y + 2; temp := WorldToScreen(point); result.x := temp.x - BitmapWidth(bitmap); result.y := temp.y - BitmapHeight(bitmap); end; // Make a Point2D value using 2 integers function Point(x,y: Integer): Point2D; begin result.x := x; result.y := y; end; // Make a Point2D value using 2 singles function Point(x,y: Single): Point2D; begin result.x := x; result.y := y; end; // Make a Point2D value using 2 singles function NewPoint(x,y: Single): Point2D; begin result.x := x; result.y := y; end; // Make a Point2D value using 2 integers function PointOfInt(x,y: Integer): Point2D; begin result.x := x; result.y := y; end; // Manhattan distance between two points on map function MapDistance(a,b : Point2D): Double; begin result := Abs(b.x - a.x) + Abs(b.y - a.y); end; // Get neighbouring tile for a certain tile function FindNeighbours(var game : GameData; pt : Point2D): TileArray; var neighbours: TileArray; currMapTile : Point2D; begin currMapTile := pt; if (currMapTile.x - 1 > 0) and (currMapTile.y < MAP_HEIGHT) then begin SetLength(neighbours, Length(neighbours) + 1); neighbours[High(neighbours)] := game.map[Round(currMapTile.x) - 1, Round(currMapTile.y)]; neighbours[High(neighbours)].loc := PointOfInt(Round(currMapTile.x) - 1, Round(currMapTile.y)); end; if (currMapTile.x >= 0) and (currMapTile.y + 1 < MAP_HEIGHT) then begin SetLength(neighbours, Length(neighbours) + 1); neighbours[High(neighbours)] := game.map[Round(currMapTile.x), Round(currMapTile.y) + 1]; neighbours[High(neighbours)].loc := PointOfInt(Round(currMapTile.x), Round(currMapTile.y) + 1); end; if (currMapTile.x >= 0) and (currMapTile.y - 1 > 0) then begin SetLength(neighbours, Length(neighbours) + 1); neighbours[High(neighbours)] := game.map[Round(currMapTile.x), Round(currMapTile.y) - 1]; neighbours[High(neighbours)].loc := PointOfInt(Round(currMapTile.x), Round(currMapTile.y) - 1); end; if (currMapTile.x + 1 < MAP_WIDTH) and (currMapTile.y < MAP_HEIGHT) then begin SetLength(neighbours, Length(neighbours) + 1); neighbours[High(neighbours)] := game.map[Round(currMapTile.x) + 1, Round(currMapTile.y)]; neighbours[High(neighbours)].loc := PointOfInt(Round(currMapTile.x) + 1, Round(currMapTile.y)); end; result := neighbours; end; // Check if the tile is valid for zoning function PlotIsPlaceable(const game : GameData; loc : Point2D): Boolean; begin if (loc.x >= 0) and (loc.y >= 0 ) and (game.map[Round(loc.x),Round(loc.y)].tType.terrainType = TERRAIN_NORMAL) then exit (true); exit (false); end; // Check if the tile doesn't have any buildings on it function PlotIsAvailable(const game : GameData; loc : Point2D): Boolean; var i: Integer; avail : Boolean; begin avail := true; for i := 0 to High(game.buildings) do begin if VectorsEqual(game.buildings[i].loc, loc) then begin avail := false; end; end; if avail then begin if not PlotIsPlaceable(game, loc) then exit (false); end; exit (avail); end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> } { with help from: http://wiki.freepascal.org/Example_of_multi-threaded_application:_array_of_threads https://www.getlazarus.org/forums/viewtopic.php?t=52 } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, StdCtrls, threadunit; type { TForm1 } TForm1 = class(TForm) btnStartThread: TButton; btnStartUnit: TButton; btnStartBoth: TButton; Memo1: TMemo; procedure btnStartBothClick(Sender: TObject); procedure btnStartUnitClick(Sender: TObject); procedure btnStartThreadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure StopThreads; public Threads: array of TThreadUnit; nThreads: integer; end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btnStartThreadClick(Sender: TObject); var i: integer; begin nThreads:=8; SetLength(Threads,nThreads); for i:=0 to nThreads-1 do begin; Threads[i]:=TThreadUnit.Create(True); Threads[i].Name:='T'+i.ToString; Threads[i].Start; end; end; procedure TForm1.btnStartUnitClick(Sender: TObject); var i: integer; begin for i:=1 to 10 do begin Sleep(500); Application.ProcessMessages; Memo1.Append('Unit1 count: '+i.ToString); end; Memo1.Append('Unit1 done.'); StopThreads; end; procedure TForm1.btnStartBothClick(Sender: TObject); begin btnStartThreadClick(nil); btnStartUnitClick(nil); end; procedure TForm1.StopThreads; var i: integer; begin for i:=Low(Threads) to High(Threads) do begin if Assigned(Threads[i]) then begin Threads[i].Terminate; Threads[i].WaitFor; FreeAndNil(Threads[i]); end; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin StopThreads; end; end.
unit deList; {* Данные списка. } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Search\deList.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdeList" MUID: (47F33E9E03C8) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin)} uses l3IntfUses , l3ProtoObject , PrimPrimListInterfaces , DynamicDocListUnit , bsTypes , l3TreeInterfaces , FiltersUnit ; type TdeList = class(Tl3ProtoObject, IdeList) {* Данные списка. } private f_List: IDynList; f_NodeForPositioning: Il3SimpleNode; f_AllDocumentsFiltered: Boolean; f_NeedApplyPermanentFilters: Boolean; f_IsChanged: Boolean; f_ActiveFilters: IFiltersFromQuery; f_TimeMachineOff: Boolean; f_WhatDoingIfOneDoc: TbsWhatDoingIfOneDoc; f_SearchInfo: IdeSearchInfo; protected function pm_GetList: IDynList; function pm_GetTimeMachineOff: Boolean; function pm_GetWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc; function pm_GetNodeForPositioning: Il3SimpleNode; function pm_GetSearchInfo: IdeSearchInfo; function pm_GetAllDocumentsFiltered: Boolean; function pm_GetNeedApplyPermanentFilters: Boolean; function pm_GetIsChanged: Boolean; function pm_GetActiveFilters: IFiltersFromQuery; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(const aList: IDynList; aTimeMachineOff: Boolean; aWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc; const aNodeForPositioning: Il3SimpleNode; const aSearchInfo: IdeSearchInfo; aAllDocumentsFiltered: Boolean; aNeedApplyPermanentFilters: Boolean; aIsChanged: Boolean); reintroduce; class function Make(const aList: IDynList; aTimeMachineOff: Boolean = True; aWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc = bsTypes.wdAlwaysOpen; const aNodeForPositioning: Il3SimpleNode = nil; const aSearchInfo: IdeSearchInfo = nil; aAllDocumentsFiltered: Boolean = False; aNeedApplyPermanentFilters: Boolean = True; aIsChanged: Boolean = False): IdeList; reintroduce; protected property TimeMachineOff: Boolean read f_TimeMachineOff; property WhatDoingIfOneDoc: TbsWhatDoingIfOneDoc read f_WhatDoingIfOneDoc; property SearchInfo: IdeSearchInfo read f_SearchInfo; end;//TdeList {$IfEnd} // NOT Defined(Admin) implementation {$If NOT Defined(Admin)} uses l3ImplUses //#UC START# *47F33E9E03C8impl_uses* , DataAdapter //#UC END# *47F33E9E03C8impl_uses* ; constructor TdeList.Create(const aList: IDynList; aTimeMachineOff: Boolean; aWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc; const aNodeForPositioning: Il3SimpleNode; const aSearchInfo: IdeSearchInfo; aAllDocumentsFiltered: Boolean; aNeedApplyPermanentFilters: Boolean; aIsChanged: Boolean); //#UC START# *4B1F76940201_47F33E9E03C8_var* //#UC END# *4B1F76940201_47F33E9E03C8_var* begin //#UC START# *4B1F76940201_47F33E9E03C8_impl* inherited Create; f_List := aList; f_TimeMachineOff := aTimeMachineOff; f_WhatDoingIfOneDoc := aWhatDoingIfOneDoc; f_NodeForPositioning := aNodeForPositioning; f_SearchInfo := aSearchInfo; f_AllDocumentsFiltered := aAllDocumentsFiltered; f_NeedApplyPermanentFilters := aNeedApplyPermanentFilters; f_IsChanged := aIsChanged; f_ActiveFilters := DefDataAdapter.NativeAdapter.MakeFiltersFromQuery; //#UC END# *4B1F76940201_47F33E9E03C8_impl* end;//TdeList.Create class function TdeList.Make(const aList: IDynList; aTimeMachineOff: Boolean = True; aWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc = bsTypes.wdAlwaysOpen; const aNodeForPositioning: Il3SimpleNode = nil; const aSearchInfo: IdeSearchInfo = nil; aAllDocumentsFiltered: Boolean = False; aNeedApplyPermanentFilters: Boolean = True; aIsChanged: Boolean = False): IdeList; var l_Inst : TdeList; begin l_Inst := Create(aList, aTimeMachineOff, aWhatDoingIfOneDoc, aNodeForPositioning, aSearchInfo, aAllDocumentsFiltered, aNeedApplyPermanentFilters, aIsChanged); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TdeList.Make function TdeList.pm_GetList: IDynList; //#UC START# *4B1D0FB101BA_47F33E9E03C8get_var* //#UC END# *4B1D0FB101BA_47F33E9E03C8get_var* begin //#UC START# *4B1D0FB101BA_47F33E9E03C8get_impl* Result := f_List; //#UC END# *4B1D0FB101BA_47F33E9E03C8get_impl* end;//TdeList.pm_GetList function TdeList.pm_GetTimeMachineOff: Boolean; //#UC START# *4B1D0FCD01D2_47F33E9E03C8get_var* //#UC END# *4B1D0FCD01D2_47F33E9E03C8get_var* begin //#UC START# *4B1D0FCD01D2_47F33E9E03C8get_impl* Result := f_TimeMachineOff; //#UC END# *4B1D0FCD01D2_47F33E9E03C8get_impl* end;//TdeList.pm_GetTimeMachineOff function TdeList.pm_GetWhatDoingIfOneDoc: TbsWhatDoingIfOneDoc; //#UC START# *4B1D100202D0_47F33E9E03C8get_var* //#UC END# *4B1D100202D0_47F33E9E03C8get_var* begin //#UC START# *4B1D100202D0_47F33E9E03C8get_impl* Result := f_WhatDoingIfOneDoc; //#UC END# *4B1D100202D0_47F33E9E03C8get_impl* end;//TdeList.pm_GetWhatDoingIfOneDoc function TdeList.pm_GetNodeForPositioning: Il3SimpleNode; //#UC START# *4B1D102C004A_47F33E9E03C8get_var* //#UC END# *4B1D102C004A_47F33E9E03C8get_var* begin //#UC START# *4B1D102C004A_47F33E9E03C8get_impl* Result := f_NodeForPositioning; //#UC END# *4B1D102C004A_47F33E9E03C8get_impl* end;//TdeList.pm_GetNodeForPositioning function TdeList.pm_GetSearchInfo: IdeSearchInfo; //#UC START# *4B1D104E02FA_47F33E9E03C8get_var* //#UC END# *4B1D104E02FA_47F33E9E03C8get_var* begin //#UC START# *4B1D104E02FA_47F33E9E03C8get_impl* Result := f_SearchInfo; //#UC END# *4B1D104E02FA_47F33E9E03C8get_impl* end;//TdeList.pm_GetSearchInfo function TdeList.pm_GetAllDocumentsFiltered: Boolean; //#UC START# *560BC82C0143_47F33E9E03C8get_var* //#UC END# *560BC82C0143_47F33E9E03C8get_var* begin //#UC START# *560BC82C0143_47F33E9E03C8get_impl* Result := f_AllDocumentsFiltered; //#UC END# *560BC82C0143_47F33E9E03C8get_impl* end;//TdeList.pm_GetAllDocumentsFiltered function TdeList.pm_GetNeedApplyPermanentFilters: Boolean; //#UC START# *562485D00025_47F33E9E03C8get_var* //#UC END# *562485D00025_47F33E9E03C8get_var* begin //#UC START# *562485D00025_47F33E9E03C8get_impl* Result := f_NeedApplyPermanentFilters; //#UC END# *562485D00025_47F33E9E03C8get_impl* end;//TdeList.pm_GetNeedApplyPermanentFilters function TdeList.pm_GetIsChanged: Boolean; //#UC START# *569DDAE500DD_47F33E9E03C8get_var* //#UC END# *569DDAE500DD_47F33E9E03C8get_var* begin //#UC START# *569DDAE500DD_47F33E9E03C8get_impl* Result := f_IsChanged; //#UC END# *569DDAE500DD_47F33E9E03C8get_impl* end;//TdeList.pm_GetIsChanged function TdeList.pm_GetActiveFilters: IFiltersFromQuery; //#UC START# *57EE27F30169_47F33E9E03C8get_var* //#UC END# *57EE27F30169_47F33E9E03C8get_var* begin //#UC START# *57EE27F30169_47F33E9E03C8get_impl* Result := f_ActiveFilters; //#UC END# *57EE27F30169_47F33E9E03C8get_impl* end;//TdeList.pm_GetActiveFilters procedure TdeList.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_47F33E9E03C8_var* //#UC END# *479731C50290_47F33E9E03C8_var* begin //#UC START# *479731C50290_47F33E9E03C8_impl* f_SearchInfo := nil; inherited; //#UC END# *479731C50290_47F33E9E03C8_impl* end;//TdeList.Cleanup procedure TdeList.ClearFields; begin f_List := nil; f_NodeForPositioning := nil; f_SearchInfo := nil; inherited; end;//TdeList.ClearFields {$IfEnd} // NOT Defined(Admin) end.
unit App; { Based on Simple_Texture2D.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TSimpleTexture2DApp = class(TApplication) private FProgram: TGLProgram; FAttrPosition: TGLVertexAttrib; FAttrTexCoord: TGLVertexAttrib; FUniSampler: TGLUniform; FTexture: TGLTexture; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Texture; { TSimpleTexture2DApp } procedure TSimpleTexture2DApp.Initialize; var VertexShader, FragmentShader: TGLShader; begin { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'attribute vec4 a_position;'#10+ 'attribute vec2 a_texCoord;'#10+ 'varying vec2 v_texCoord;'#10+ 'void main()'#10+ '{'#10+ ' gl_Position = a_position;'#10+ ' v_texCoord = a_texCoord;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'varying vec2 v_texCoord;'#10+ 'uniform sampler2D s_texture;'#10+ 'void main()'#10+ '{'#10+ ' gl_FragColor = texture2D(s_texture, v_texCoord);'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attributes } FAttrPosition.Init(FProgram, 'a_position'); FAttrTexCoord.Init(FProgram, 'a_texCoord'); { Initialize uniform } FUniSampler.Init(FProgram, 's_texture'); { Load the texture } FTexture := CreateSimpleTexture2D; { Set clear color to black } gl.ClearColor(0, 0, 0, 0); end; procedure TSimpleTexture2DApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TSimpleTexture2DApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); type TVertex = record Pos: TVector3; TexCoord: TVector2; end; const VERTICES: array [0..3] of TVertex = ( (Pos: (X: -0.5; Y: 0.5; Z: 0.0); TexCoord: (X: 0.0; Y: 0.0)), (Pos: (X: -0.5; Y: -0.5; Z: 0.0); TexCoord: (X: 0.0; Y: 1.0)), (Pos: (X: 0.5; Y: -0.5; Z: 0.0); TexCoord: (X: 1.0; Y: 1.0)), (Pos: (X: 0.5; Y: 0.5; Z: 0.0); TexCoord: (X: 1.0; Y: 0.0))); INDICES: array [0..5] of UInt16 = ( 0, 1, 2, 0, 2, 3); begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Set the data for the vertex attributes } FAttrPosition.SetData(TGLDataType.Float, 3, @VERTICES[0].Pos, SizeOf(TVertex)); FAttrPosition.Enable; FAttrTexCoord.SetData(TGLDataType.Float, 2, @VERTICES[0].TexCoord, SizeOf(TVertex)); FAttrTexCoord.Enable; { Bind the texture } FTexture.BindToTextureUnit(0); { Set the texture sampler to texture unit to 0 } FUniSampler.SetValue(0); { Draw the quad } gl.DrawElements(TGLPrimitiveType.Triangles, INDICES); end; procedure TSimpleTexture2DApp.Shutdown; begin { Release resources } FTexture.Delete; FProgram.Delete; end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCDT.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} {*************************************************************} {*** ***} {*** This unit is provided for backward compatibility only ***} {*** Applications should use the STDate unit instead ***} {*** ***} {*************************************************************} unit OvcDT; {-General date and time routines} interface uses OvcData, STDate; function CurrentDate : TOvcDate; {-returns today's date as a Julian date} function CurrentTime : TOvcTime; {-return the current time in seconds since midnight} function DateTimeToOvcDate(DT : TDateTime) : TOvcDate; {-Convert a Delphi date/time value into an Orpheus date} function DateTimeToOvcTime(DT : TDateTime) : TOvcTime; {-Convert a Delphi date/time value into an Orpheus time} procedure DateToDMY(Julian : TOvcDate; var Day, Month, Year : Integer); {-convert from a Julian date to day, month, year} function DayOfWeek(Julian : TOvcDate) : TDayType; {-return the day of the week for a Julian date} function DayOfWeekDMY(Day, Month, Year : Integer) : TDayType; {-return the day of the week for the day, month, year} function DaysInMonth(Month, Year : Integer) : Integer; {-return the number of days in the specified month of a given year} function DecTime(T : TOvcTime; Hours, Minutes, Seconds : Byte) : TOvcTime; {-subtract the specified hours, minutes, and seconds from a given time of day} function DMYToDate(Day, Month, Year : Integer) : TOvcDate; {-convert from day, month, year to a Julian date} function HMSToTime(Hours, Minutes, Seconds : Byte) : TOvcTime; {-convert hours, minutes, seconds to a time variable} function IncDate(Julian : TOvcDate; Days, Months, Years : Integer) : TOvcDate; {-add (or subtract) the number of days, months, and years to a date} function IncDateTrunc(Julian : TOvcDate; Months, Years : Integer) : TOvcDate; {-add (or subtract) the specified number of months and years to a date} function IncTime(T : TOvcTime; Hours, Minutes, Seconds : Byte) : TOvcTime; {-add the specified hours, minutes, and seconds to a given time of day} function IsLeapYear(Year : Integer) : Boolean; {-return True if Year is a leap year} function OvcDateToDateTime(D : TOvcDate) : TDateTime; {-Convert an Orpheus date into a Delphi date/time value} function OvcTimeToDateTime(T : TOvcTime) : TDateTime; {-Convert an Orpheus time into a Delphi date/time value} procedure TimeToHMS(T : TOvcTime; var Hours, Minutes, Seconds : Byte); {-convert a time variable to hours, minutes, seconds} function ValidDate(Day, Month, Year : Integer) : Boolean; {-verify that day, month, year is a valid date} function ValidTime(Hours, Minutes, Seconds : Integer) : Boolean; {-return True if Hours:Minutes:Seconds is a valid time} implementation {$IFDEF TRIALRUN} uses OrTrial; {$I ORTRIALF.INC} {$ENDIF} function CurrentDate : TOvcDate; {-returns today's date as a julian} begin Result := STDate.CurrentDate; end; function CurrentTime : TOvcTime; {-returns current time in seconds since midnight} begin Result := STDate.CurrentTime; end; function DMYtoDate(Day, Month, Year : Integer) : TOvcDate; {-convert from day, month, year to a julian date} begin Result := STDate.DMYToStDate(Day, Month, Year, 1900); end; function DateTimeToOvcDate(DT : TDateTime) : TOvcDate; {-Convert a Delphi date/time value into an Orpheus date} begin Result := STDate.DateTimeToStDate(DT); end; function DateTimeToOvcTime(DT : TDateTime) : TOvcTime; {-Convert a Delphi date/time value into an Orpheus time} begin Result := STDate.DateTimeToStTime(DT); end; procedure DateToDMY(Julian : TOvcDate; var Day, Month, Year : Integer); {-convert from a julian date to month, day, year} begin STDate.StDateToDMY(Julian,Day,Month,Year); end; function DayOfWeek(Julian : TOvcDate) : TDayType; {-return the day of the week for the date. Returns TDayType(7) if Julian = BadDate.} begin Result := STDate.DayOfWeek(Julian); end; function DayOfWeekDMY(Day, Month, Year : Integer) : TDayType; {-return the day of the week for the day, month, year} begin Result := STDate.DayOfWeek(STDate.DMYtoStDate(Day, Month, Year, 1900)); end; function DaysInMonth(Month, Year : Integer) : Integer; {-return the number of days in the specified month of a given year} begin Result := STDate.DaysInMonth(Month, Year, 1900); end; function DecTime(T : TOvcTime; Hours, Minutes, Seconds : Byte) : TOvcTime; {-subtract the specified hours,minutes,seconds from T and return the result} begin Result := STDate.DecTime(T,Hours,Minutes,Seconds); end; function HMStoTime(Hours, Minutes, Seconds : Byte) : TOvcTime; {-convert Hours, Minutes, Seconds to a Time variable} begin Result := STDate.HMSToStTime(Hours,Minutes,Seconds); end; function IncDate(Julian : TOvcDate; Days, Months, Years : Integer) : TOvcDate; {-add (or subtract) the number of months, days, and years to a date. Months and years are added before days. No overflow/underflow checks are made} begin Result := STDate.IncDate(Julian,Days,Months,Years); end; function IncDateTrunc(Julian : TOvcDate; Months, Years : Integer) : TOvcDate; {-add (or subtract) the specified number of months and years to a date} begin Result := STDate.IncDateTrunc(Julian,Months,Years); end; function IncTime(T : TOvcTime; Hours, Minutes, Seconds : Byte) : TOvcTime; {-add the specified hours,minutes,seconds to T and return the result} begin Result := STDate.IncTime(T,Hours,Minutes,Seconds); end; function IsLeapYear(Year : Integer) : Boolean; {-return True if Year is a leap year} begin Result := STDate.IsLeapYear(Year); end; function OvcDateToDateTime(D : TOvcDate) : TDateTime; {-Convert an Orpheus date into a Delphi date/time value} begin Result := STDate.StDateToDateTime(D); end; function OvcTimeToDateTime(T : TOvcTime) : TDateTime; {-Convert an Orpheus time into a Delphi date/time value} begin Result := STDate.StTimeToDateTime(T); end; procedure SetDefaultYearAndMonth; {-initialize DefaultYear and DefaultMonth} begin DefaultMonth := STDate.DefaultMonth; DefaultYear := STDate.DefaultYear; end; procedure TimeToHMS(T : TOvcTime; var Hours, Minutes, Seconds : Byte); {-convert a Time variable to Hours, Minutes, Seconds} begin STDate.StTimeToHMS(T,Hours,Minutes,Seconds); end; function ValidDate(Day, Month, Year : Integer) : Boolean; {-verify that day, month, year is a valid date} begin Result := STDate.ValidDate(Day, Month, Year, 1900); end; function ValidTime(Hours, Minutes, Seconds : Integer) : Boolean; {-return true if Hours:Minutes:Seconds is a valid time} begin Result := STDate.ValidTime(Hours,Minutes,Seconds); end; initialization {initialize DefaultYear and DefaultMonth} SetDefaultYearAndMonth; end.
unit glrSound; interface uses Windows, Bass; type {Класс для проигрывания музыки} TpdSoundSystem = class private FEnabled: Boolean; FMusic: HSTREAM; FSoundVolume: Single; FMusicVolume: Single; procedure SetEnabled(const aEnabled: Boolean); procedure SetMusicVolume(const Value: Single); procedure SetSoundVolume(const Value: Single); public constructor Create(aHandle: THandle); virtual; destructor Destroy(); override; function LoadSample(const aFile: String): HSAMPLE; procedure PlaySample(const aSample: HSAMPLE); procedure FreeSample(const aSample: HSAMPLE); function LoadMusic(const aFile: String; aLoop: Boolean = True): HSTREAM; procedure PlayMusic(const aMusic: HSTREAM); procedure PauseMusic(); procedure FreeMusic(const aMusic: HSTREAM); procedure SetMusicFade(const aMusic: HSTREAM; const aTime: LongWord); property Enabled: Boolean read FEnabled write SetEnabled; property SoundVolume: Single read FSoundVolume write SetSoundVolume; property MusicVolume: Single read FMusicVolume write SetMusicVolume; end; implementation uses glrMath; { TpdSoundSystem } constructor TpdSoundSystem.Create(aHandle: THandle); begin inherited Create(); if (HIWORD(BASS_GetVersion) = BASSVERSION) then begin BASS_Init(-1, 44100, 0, aHandle, nil); BASS_SetConfig(BASS_CONFIG_BUFFER, 4000); //Размер буфера (максимум 5000) end; FEnabled := True; FMusic := 0; FSoundVolume := 1.0; FMusicVolume := 1.0; end; destructor TpdSoundSystem.Destroy; begin BASS_StreamFree(FMusic); BASS_Free(); inherited; end; procedure TpdSoundSystem.FreeMusic(const aMusic: HSTREAM); begin BASS_StreamFree(aMusic); end; procedure TpdSoundSystem.FreeSample(const aSample: HSAMPLE); begin BASS_SampleFree(aSample); end; function TpdSoundSystem.LoadMusic(const aFile: String; aLoop: Boolean = True): HSTREAM; var flags: LongWord; begin if aLoop then flags := BASS_SAMPLE_LOOP else flags := 0; Result := BASS_StreamCreateFile(False, PWideChar(aFile), 0, 0, flags{$IFDEF UNICODE} or BASS_UNICODE {$ENDIF}); end; function TpdSoundSystem.LoadSample(const aFile: String): HSAMPLE; begin Result := BASS_SampleLoad(False, PWideChar(aFile), 0, 0, 3, BASS_SAMPLE_OVER_POS{$IFDEF UNICODE} or BASS_UNICODE {$ENDIF}); BASS_SampleGetChannel(Result, false); end; procedure TpdSoundSystem.PlayMusic(const aMusic: HSTREAM); begin if (FMusic <> 0) then begin BASS_ChannelStop(FMusic); FMusic := aMusic; BASS_ChannelPlay(FMusic, True); BASS_ChannelSlideAttribute(FMusic, BASS_ATTRIB_VOL, FMusicVolume, 1000); end else begin FMusic := aMusic; BASS_ChannelPlay(FMusic, True); BASS_ChannelSetAttribute(FMusic, BASS_ATTRIB_VOL, FMusicVolume); end; end; procedure TpdSoundSystem.PlaySample(const aSample: HSAMPLE); var channel: HCHANNEL; begin channel := BASS_SampleGetChannel(aSample, False); if channel <> 0 then begin BASS_ChannelPlay(channel, true); BASS_ChannelSetAttribute(channel, BASS_ATTRIB_VOL, FSoundVolume); end; end; procedure TpdSoundSystem.SetEnabled(const aEnabled: Boolean); begin if FEnabled <> aEnabled then begin FEnabled := aEnabled; if FEnabled then begin BASS_Start(); if BASS_ChannelIsActive(FMusic) <> BASS_ACTIVE_PLAYING then begin BASS_ChannelPlay(FMusic, True); BASS_ChannelSlideAttribute(FMusic, BASS_ATTRIB_VOL, FMusicVolume, 1000); end; // PlayMusic(FMusic); end else begin BASS_Pause(); // PauseMusic(); end; end; end; procedure TpdSoundSystem.SetMusicFade(const aMusic: HSTREAM; const aTime: LongWord); begin BASS_ChannelSlideAttribute(aMusic, BASS_ATTRIB_VOL, 0.0, aTime); end; procedure TpdSoundSystem.SetMusicVolume(const Value: Single); begin FMusicVolume := Clamp(Value, 0, 1); BASS_ChannelSetAttribute(FMusic, BASS_ATTRIB_VOL, FMusicVolume); end; procedure TpdSoundSystem.SetSoundVolume(const Value: Single); begin FSoundVolume := Clamp(Value, 0, 1); end; procedure TpdSoundSystem.PauseMusic; begin BASS_ChannelPause(FMusic); end; end.
unit libavformat; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface Uses ffmpeg_types, libavutil, libavcodec; {$I ffmpeg.inc} {$REGION 'formats.h'} (* * * A list of supported formats for one end of a filter link. This is used * during the format negotiation process to try to pick the best format to * use to minimize the number of necessary conversions. Each filter gives a * list of the formats supported by each input and output pad. The list * given for each pad need not be distinct - they may be references to the * same list of formats, as is often the case when a filter supports multiple * formats, but will always output the same format as it is given in input. * * In this way, a list of possible input formats and a list of possible * output formats are associated with each link. When a set of formats is * negotiated over a link, the input and output lists are merged to form a * new list containing only the common elements of each list. In the case * that there were no common elements, a format conversion is necessary. * Otherwise, the lists are merged, and all other links which reference * either of the format lists involved in the merge are also affected. * * For example, consider the filter chain: * filter (a) --> (b) filter (b) --> (c) filter * * where the letters in parenthesis indicate a list of formats supported on * the input or output of the link. Suppose the lists are as follows: * (a) = {A, B} * (b) = {A, B, C} * (c) = {B, C} * * First, the first link's lists are merged, yielding: * filter (a) --> (a) filter (a) --> (c) filter * * Notice that format list (b) now refers to the same list as filter list (a). * Next, the lists for the second link are merged, yielding: * filter (a) --> (a) filter (a) --> (a) filter * * where (a) = {B}. * * Unfortunately, when the format lists at the two ends of a link are merged, * we must ensure that all links which reference either pre-merge format list * get updated as well. Therefore, we have the format list structure store a * pointer to each of the pointers to itself. *) type pAVFilterFormats = ^AVFilterFormats; ppAVFilterFormats = ^pAVFilterFormats; pppAVFilterFormats = ^ppAVFilterFormats; AVFilterFormats = record nb_formats: unsigned; /// < number of formats formats: pint; /// < list of media formats refcount: unsigned; /// < number of references to this list refs: pppAVFilterFormats; /// < references to this list end; (* * * A list of supported channel layouts. * * The list works the same as AVFilterFormats, except for the following * differences: * - A list with all_layouts = 1 means all channel layouts with a known * disposition; nb_channel_layouts must then be 0. * - A list with all_counts = 1 means all channel counts, with a known or * unknown disposition; nb_channel_layouts must then be 0 and all_layouts 1. * - The list must not contain a layout with a known disposition and a * channel count with unknown disposition with the same number of channels * (e.g. AV_CH_LAYOUT_STEREO and FF_COUNT2LAYOUT(2). *) pAVFilterChannelLayouts = ^AVFilterChannelLayouts; ppAVFilterChannelLayouts = ^pAVFilterChannelLayouts; pppAVFilterChannelLayouts = ^ppAVFilterChannelLayouts; AVFilterChannelLayouts = record channel_layouts: puint64_t; /// < list of channel layouts nb_channel_layouts: int; /// < number of channel layouts all_layouts: AnsiChar; /// < accept any known channel layout all_counts: AnsiChar; /// < accept any channel layout or count refcount: unsigned; /// < number of references to this list refs: pppAVFilterChannelLayouts; /// < references to this list end; {$ENDREGION} {$REGION 'avformat.h'} (* * * @defgroup libavf libavformat * I/O and Muxing/Demuxing Library * * Libavformat (lavf) is a library for dealing with various media container * formats. Its main two purposes are demuxing - i.e. splitting a media file * into component streams, and the reverse process of muxing - writing supplied * data in a specified container format. It also has an @ref lavf_io * "I/O module" which supports a number of protocols for accessing the data (e.g. * file, tcp, http and others). * Unless you are absolutely sure you won't use libavformat's network * capabilities, you should also call avformat_network_init(). * * A supported input format is described by an AVInputFormat struct, conversely * an output format is described by AVOutputFormat. You can iterate over all * input/output formats using the av_demuxer_iterate / av_muxer_iterate() functions. * The protocols layer is not part of the public API, so you can only get the names * of supported protocols with the avio_enum_protocols() function. * * Main lavf structure used for both muxing and demuxing is AVFormatContext, * which exports all information about the file being read or written. As with * most Libavformat structures, its size is not part of public ABI, so it cannot be * allocated on stack or directly with av_malloc(). To create an * AVFormatContext, use avformat_alloc_context() (some functions, like * avformat_open_input() might do that for you). * * Most importantly an AVFormatContext contains: * @li the @ref AVFormatContext.iformat "input" or @ref AVFormatContext.oformat * "output" format. It is either autodetected or set by user for input; * always set by user for output. * @li an @ref AVFormatContext.streams "array" of AVStreams, which describe all * elementary streams stored in the file. AVStreams are typically referred to * using their index in this array. * @li an @ref AVFormatContext.pb "I/O context". It is either opened by lavf or * set by user for input, always set by user for output (unless you are dealing * with an AVFMT_NOFILE format). * * @section lavf_options Passing options to (de)muxers * It is possible to configure lavf muxers and demuxers using the @ref avoptions * mechanism. Generic (format-independent) libavformat options are provided by * AVFormatContext, they can be examined from a user program by calling * av_opt_next() / av_opt_find() on an allocated AVFormatContext (or its AVClass * from avformat_get_class()). Private (format-specific) options are provided by * AVFormatContext.priv_data if and only if AVInputFormat.priv_class / * AVOutputFormat.priv_class of the corresponding format struct is non-NULL. * Further options may be provided by the @ref AVFormatContext.pb "I/O context", * if its AVClass is non-NULL, and the protocols layer. See the discussion on * nesting in @ref avoptions documentation to learn how to access those. * * @section urls * URL strings in libavformat are made of a scheme/protocol, a ':', and a * scheme specific string. URLs without a scheme and ':' used for local files * are supported but deprecated. "file:" should be used for local files. * * It is important that the scheme string is not taken from untrusted * sources without checks. * * Note that some schemes/protocols are quite powerful, allowing access to * both local and remote files, parts of them, concatenations of them, local * audio and video devices and so on. * * @{ * * @defgroup lavf_decoding Demuxing * @{ * Demuxers read a media file and split it into chunks of data (@em packets). A * @ref AVPacket "packet" contains one or more encoded frames which belongs to a * single elementary stream. In the lavf API this process is represented by the * avformat_open_input() function for opening a file, av_read_frame() for * reading a single packet and finally avformat_close_input(), which does the * cleanup. * * @section lavf_decoding_open Opening a media file * The minimum information required to open a file is its URL, which * is passed to avformat_open_input(), as in the following code: * @code * const char *url = "file:in.mp3"; * AVFormatContext *s = NULL; * int ret = avformat_open_input(&s, url, NULL, NULL); * if (ret < 0) * abort(); * @endcode * The above code attempts to allocate an AVFormatContext, open the * specified file (autodetecting the format) and read the header, exporting the * information stored there into s. Some formats do not have a header or do not * store enough information there, so it is recommended that you call the * avformat_find_stream_info() function which tries to read and decode a few * frames to find missing information. * * In some cases you might want to preallocate an AVFormatContext yourself with * avformat_alloc_context() and do some tweaking on it before passing it to * avformat_open_input(). One such case is when you want to use custom functions * for reading input data instead of lavf internal I/O layer. * To do that, create your own AVIOContext with avio_alloc_context(), passing * your reading callbacks to it. Then set the @em pb field of your * AVFormatContext to newly created AVIOContext. * * Since the format of the opened file is in general not known until after * avformat_open_input() has returned, it is not possible to set demuxer private * options on a preallocated context. Instead, the options should be passed to * avformat_open_input() wrapped in an AVDictionary: * @code * AVDictionary *options = NULL; * av_dict_set(&options, "video_size", "640x480", 0); * av_dict_set(&options, "pixel_format", "rgb24", 0); * * if (avformat_open_input(&s, url, NULL, &options) < 0) * abort(); * av_dict_free(&options); * @endcode * This code passes the private options 'video_size' and 'pixel_format' to the * demuxer. They would be necessary for e.g. the rawvideo demuxer, since it * cannot know how to interpret raw video data otherwise. If the format turns * out to be something different than raw video, those options will not be * recognized by the demuxer and therefore will not be applied. Such unrecognized * options are then returned in the options dictionary (recognized options are * consumed). The calling program can handle such unrecognized options as it * wishes, e.g. * @code * AVDictionaryEntry *e; * if (e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX)) { * fprintf(stderr, "Option %s not recognized by the demuxer.\n", e->key); * abort(); * } * @endcode * * After you have finished reading the file, you must close it with * avformat_close_input(). It will free everything associated with the file. * * @section lavf_decoding_read Reading from an opened file * Reading data from an opened AVFormatContext is done by repeatedly calling * av_read_frame() on it. Each call, if successful, will return an AVPacket * containing encoded data for one AVStream, identified by * AVPacket.stream_index. This packet may be passed straight into the libavcodec * decoding functions avcodec_send_packet() or avcodec_decode_subtitle2() if the * caller wishes to decode the data. * * AVPacket.pts, AVPacket.dts and AVPacket.duration timing information will be * set if known. They may also be unset (i.e. AV_NOPTS_VALUE for * pts/dts, 0 for duration) if the stream does not provide them. The timing * information will be in AVStream.time_base units, i.e. it has to be * multiplied by the timebase to convert them to seconds. * * If AVPacket.buf is set on the returned packet, then the packet is * allocated dynamically and the user may keep it indefinitely. * Otherwise, if AVPacket.buf is NULL, the packet data is backed by a * static storage somewhere inside the demuxer and the packet is only valid * until the next av_read_frame() call or closing the file. If the caller * requires a longer lifetime, av_packet_make_refcounted() will ensure that * the data is reference counted, copying the data if necessary. * In both cases, the packet must be freed with av_packet_unref() when it is no * longer needed. * * @section lavf_decoding_seek Seeking * @} * * @defgroup lavf_encoding Muxing * @{ * Muxers take encoded data in the form of @ref AVPacket "AVPackets" and write * it into files or other output bytestreams in the specified container format. * * The main API functions for muxing are avformat_write_header() for writing the * file header, av_write_frame() / av_interleaved_write_frame() for writing the * packets and av_write_trailer() for finalizing the file. * * At the beginning of the muxing process, the caller must first call * avformat_alloc_context() to create a muxing context. The caller then sets up * the muxer by filling the various fields in this context: * * - The @ref AVFormatContext.oformat "oformat" field must be set to select the * muxer that will be used. * - Unless the format is of the AVFMT_NOFILE type, the @ref AVFormatContext.pb * "pb" field must be set to an opened IO context, either returned from * avio_open2() or a custom one. * - Unless the format is of the AVFMT_NOSTREAMS type, at least one stream must * be created with the avformat_new_stream() function. The caller should fill * the @ref AVStream.codecpar "stream codec parameters" information, such as the * codec @ref AVCodecParameters.codec_type "type", @ref AVCodecParameters.codec_id * "id" and other parameters (e.g. width / height, the pixel or sample format, * etc.) as known. The @ref AVStream.time_base "stream timebase" should * be set to the timebase that the caller desires to use for this stream (note * that the timebase actually used by the muxer can be different, as will be * described later). * - It is advised to manually initialize only the relevant fields in * AVCodecParameters, rather than using @ref avcodec_parameters_copy() during * remuxing: there is no guarantee that the codec context values remain valid * for both input and output format contexts. * - The caller may fill in additional information, such as @ref * AVFormatContext.metadata "global" or @ref AVStream.metadata "per-stream" * metadata, @ref AVFormatContext.chapters "chapters", @ref * AVFormatContext.programs "programs", etc. as described in the * AVFormatContext documentation. Whether such information will actually be * stored in the output depends on what the container format and the muxer * support. * * When the muxing context is fully set up, the caller must call * avformat_write_header() to initialize the muxer internals and write the file * header. Whether anything actually is written to the IO context at this step * depends on the muxer, but this function must always be called. Any muxer * private options must be passed in the options parameter to this function. * * The data is then sent to the muxer by repeatedly calling av_write_frame() or * av_interleaved_write_frame() (consult those functions' documentation for * discussion on the difference between them; only one of them may be used with * a single muxing context, they should not be mixed). Do note that the timing * information on the packets sent to the muxer must be in the corresponding * AVStream's timebase. That timebase is set by the muxer (in the * avformat_write_header() step) and may be different from the timebase * requested by the caller. * * Once all the data has been written, the caller must call av_write_trailer() * to flush any buffered packets and finalize the output file, then close the IO * context (if any) and finally free the muxing context with * avformat_free_context(). * @} * * @defgroup lavf_io I/O Read/Write * @{ * @section lavf_io_dirlist Directory listing * The directory listing API makes it possible to list files on remote servers. * * Some of possible use cases: * - an "open file" dialog to choose files from a remote location, * - a recursive media finder providing a player with an ability to play all * files from a given directory. * * @subsection lavf_io_dirlist_open Opening a directory * At first, a directory needs to be opened by calling avio_open_dir() * supplied with a URL and, optionally, ::AVDictionary containing * protocol-specific parameters. The function returns zero or positive * integer and allocates AVIODirContext on success. * * @code * AVIODirContext *ctx = NULL; * if (avio_open_dir(&ctx, "smb://example.com/some_dir", NULL) < 0) { * fprintf(stderr, "Cannot open directory.\n"); * abort(); * } * @endcode * * This code tries to open a sample directory using smb protocol without * any additional parameters. * * @subsection lavf_io_dirlist_read Reading entries * Each directory's entry (i.e. file, another directory, anything else * within ::AVIODirEntryType) is represented by AVIODirEntry. * Reading consecutive entries from an opened AVIODirContext is done by * repeatedly calling avio_read_dir() on it. Each call returns zero or * positive integer if successful. Reading can be stopped right after the * NULL entry has been read -- it means there are no entries left to be * read. The following code reads all entries from a directory associated * with ctx and prints their names to standard output. * @code * AVIODirEntry *entry = NULL; * for (;;) { * if (avio_read_dir(ctx, &entry) < 0) { * fprintf(stderr, "Cannot list directory.\n"); * abort(); * } * if (!entry) * break; * printf("%s\n", entry->name); * avio_free_directory_entry(&entry); * } * @endcode * @} * * @defgroup lavf_codec Demuxers * @{ * @defgroup lavf_codec_native Native Demuxers * @{ * @} * @defgroup lavf_codec_wrappers External library wrappers * @{ * @} * @} * @defgroup lavf_protos I/O Protocols * @{ * @} * @defgroup lavf_internal Internal * @{ * @} * @} *) // #include <time.h> // #include <stdio.h> (* FILE *) // #include "libavcodec/avcodec.h" // #include "libavutil/dict.h" // #include "libavutil/log.h" // #include "avio.h" // #include "libavformat/version.h" {$REGION 'avio.h'} const (* * * Seeking works like for a local file. *) AVIO_SEEKABLE_NORMAL = (1 shl 0); (* * * Seeking by timestamp with avio_seek_time() is possible. *) AVIO_SEEKABLE_TIME = (1 shl 1); type (* * * Callback for checking whether to abort blocking functions. * AVERROR_EXIT is returned in this case by the interrupted * function. During blocking operations, callback is called with * opaque as parameter. If the callback returns 1, the * blocking operation will be aborted. * * No members can be added to this struct without a major bump, if * new elements have been added after this struct in AVFormatContext * or AVIOContext. *) pAVIOInterruptCB = ^AVIOInterruptCB; AVIOInterruptCB = record // int (*callback)(void*); callback: function(p: pointer): int; cdecl; opaque: pointer; end; (* * * Directory entry types. *) AVIODirEntryType = ( // AVIO_ENTRY_UNKNOWN, AVIO_ENTRY_BLOCK_DEVICE, AVIO_ENTRY_CHARACTER_DEVICE, AVIO_ENTRY_DIRECTORY, AVIO_ENTRY_NAMED_PIPE, AVIO_ENTRY_SYMBOLIC_LINK, AVIO_ENTRY_SOCKET, AVIO_ENTRY_FILE, AVIO_ENTRY_SERVER, AVIO_ENTRY_SHARE, AVIO_ENTRY_WORKGROUP); (* * * Describes single entry of the directory. * * Only name and type fields are guaranteed be set. * Rest of fields are protocol or/and platform dependent and might be unknown. *) pAVIODirEntry = ^AVIODirEntry; AVIODirEntry = record name: PAnsiChar; (* *< Filename *) _type: int; (* *< Type of the entry *) utf8: int; (* *< Set to 1 when name is encoded with UTF-8, 0 otherwise. Name can be encoded with UTF-8 even though 0 is set. *) size: int64_t; (* *< File size in bytes, -1 if unknown. *) modification_timestamp: int64_t; (* *< Time of last modification in microseconds since unix epoch, -1 if unknown. *) access_timestamp: int64_t; (* *< Time of last access in microseconds since unix epoch, -1 if unknown. *) status_change_timestamp: int64_t; (* *< Time of last status change in microseconds since unix epoch, -1 if unknown. *) user_id: int64_t; (* *< User ID of owner, -1 if unknown. *) group_id: int64_t; (* *< Group ID of owner, -1 if unknown. *) filemode: int64_t; (* *< Unix file mode, -1 if unknown. *) end; pURLContext = ^URLContext; URLContext = record end; pAVIODirContext = ^AVIODirContext; AVIODirContext = record url_context: pURLContext; end; (* * * Different data types that can be returned via the AVIO * write_data_type callback. *) AVIODataMarkerType = ( (* * * Header data; this needs to be present for the stream to be decodeable. *) AVIO_DATA_MARKER_HEADER, (* * * A point in the output bytestream where a decoder can start decoding * (i.e. a keyframe). A demuxer/decoder given the data flagged with * AVIO_DATA_MARKER_HEADER, followed by any AVIO_DATA_MARKER_SYNC_POINT, * should give decodeable results. *) AVIO_DATA_MARKER_SYNC_POINT, (* * * A point in the output bytestream where a demuxer can start parsing * (for non self synchronizing bytestream formats). That is, any * non-keyframe packet start point. *) AVIO_DATA_MARKER_BOUNDARY_POINT, (* * * This is any, unlabelled data. It can either be a muxer not marking * any positions at all, it can be an actual boundary/sync point * that the muxer chooses not to mark, or a later part of a packet/fragment * that is cut into multiple write callbacks due to limited IO buffer size. *) AVIO_DATA_MARKER_UNKNOWN, (* * * Trailer data, which doesn't contain actual content, but only for * finalizing the output file. *) AVIO_DATA_MARKER_TRAILER, (* * * A point in the output bytestream where the underlying AVIOContext might * flush the buffer depending on latency or buffering requirements. Typically * means the end of a packet. *) AVIO_DATA_MARKER_FLUSH_POINT); (* * * Bytestream IO Context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVIOContext) must not be used outside libav*. * * @note None of the function pointers in AVIOContext should be called * directly, they should only be set by the client application * when implementing custom I/O. Normally these are set to the * function pointers specified in avio_alloc_context() *) pAVIOContext = ^AVIOContext; AVIOContext = record (* * * A class for private options. * * If this AVIOContext is created by avio_open2(), av_class is set and * passes the options down to protocols. * * If this AVIOContext is manually allocated, then av_class may be set by * the caller. * * warning -- this field can be NULL, be sure to not pass this AVIOContext * to any av_opt_* functions in that case. *) av_class: pAVClass; (* * The following shows the relationship between buffer, buf_ptr, * buf_ptr_max, buf_end, buf_size, and pos, when reading and when writing * (since AVIOContext is used for both): * ********************************************************************************** * READING ********************************************************************************** * * | buffer_size | * |---------------------------------------| * | | * * buffer buf_ptr buf_end * +---------------+-----------------------+ * |/ / / / / / / /|/ / / / / / /| | * read buffer: |/ / consumed / | to be read /| | * |/ / / / / / / /|/ / / / / / /| | * +---------------+-----------------------+ * * pos * +-------------------------------------------+-----------------+ * input file: | | | * +-------------------------------------------+-----------------+ * * ********************************************************************************** * WRITING ********************************************************************************** * * | buffer_size | * |--------------------------------------| * | | * * buf_ptr_max * buffer (buf_ptr) buf_end * +-----------------------+--------------+ * |/ / / / / / / / / / / /| | * write buffer: | / / to be flushed / / | | * |/ / / / / / / / / / / /| | * +-----------------------+--------------+ * buf_ptr can be in this * due to a backward seek * * pos * +-------------+----------------------------------------------+ * output file: | | | * +-------------+----------------------------------------------+ * *) buffer: punsignedchar; (* *< Start of the buffer. *) buffer_size: int; (* *< Maximum buffer size *) buf_ptr: punsignedchar; (* *< Current position in the buffer *) buf_end: punsignedchar; (* *< End of the data, may be less than buffer+buffer_size if the read function returned less data than requested, e.g. for streams where no more data has been received yet. *) opaque: pointer; (* *< A private pointer, passed to the read/write/seek/... functions. *) // int (*read_packet)(void *opaque, uint8_t *buf, int buf_size); read_packet: function(opaque: pointer; buf: puint8_t; buf_size: int): int; cdecl; // int (*write_packet)(void *opaque, uint8_t *buf, int buf_size); write_packet: function(opaque: pointer; buf: puint8_t; buf_size: int): int; cdecl; // int64_t (*seek)(void *opaque, int64_t offset, int whence); seek: function(opaque: pointer; offset: int64_t; whence: int): int64_t; cdecl; pos: int64_t; (* *< position in the file of the current buffer *) eof_reached: int; (* *< true if was unable to read due to error or eof *) write_flag: int; (* *< true if open for writing *) max_packet_size: int; checksum: unsigned_long; checksum_ptr: punsignedchar; // unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size); update_checksum: function(checksum: unsigned_long; const buf: puint8_t; size: unsigned_int): unsigned_long; cdecl; error: int; (* *< contains the error code or 0 if no error happened *) (* * * Pause or resume playback for network streaming protocols - e.g. MMS. *) // int (*read_pause)(void *opaque, int pause); read_pause: function(opaque: pointer; pause: int): int; cdecl; (* * * Seek to a given timestamp in stream with the specified stream_index. * Needed for some network streaming protocols which don't support seeking * to byte position. *) // int64_t (*read_seek)(void *opaque, int stream_index, int64_t timestamp, int flags); read_seek: function(opaque: pointer; stream_index: int; timestamp: int64_t; flags: int): int64_t; cdecl; (* * * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable. *) seekable: int; (* * * max filesize, used to limit allocations * This field is internal to libavformat and access from outside is not allowed. *) maxsize: int64_t; (* * * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. *) direct: int; (* * * Bytes read statistic * This field is internal to libavformat and access from outside is not allowed. *) bytes_read: int64_t; (* * * seek statistic * This field is internal to libavformat and access from outside is not allowed. *) seek_count: int; (* * * writeout statistic * This field is internal to libavformat and access from outside is not allowed. *) writeout_count: int; (* * * Original buffer size * used internally after probing and ensure seekback to reset the buffer size * This field is internal to libavformat and access from outside is not allowed. *) orig_buffer_size: int; (* * * Threshold to favor readahead over seek. * This is current internal only, do not use from outside. *) short_seek_threshold: int; (* * * ',' separated list of allowed protocols. *) protocol_whitelist: PAnsiChar; (* * * ',' separated list of disallowed protocols. *) protocol_blacklist: PAnsiChar; (* * * A callback that is used instead of write_packet. *) // int (*write_data_type)(void *opaque, uint8_t *buf, int buf_size, enum AVIODataMarkerType type, int64_t time); write_data_type: function(opaque: pointer; buf: puint8_t; buf_size: int; _type: AVIODataMarkerType; time: int64_t): int; cdecl; (* * * If set, don't call write_data_type separately for AVIO_DATA_MARKER_BOUNDARY_POINT, * but ignore them and treat them as AVIO_DATA_MARKER_UNKNOWN (to avoid needlessly * small chunks of data returned from the callback). *) ignore_boundary_point: int; (* * * Internal, not meant to be used from outside of AVIOContext. *) current_type: AVIODataMarkerType; last_time: int64_t; (* * * A callback that is used instead of short_seek_threshold. * This is current internal only, do not use from outside. *) // int (*short_seek_get)(void *opaque); short_seek_get: function(opaque: pointer): int; cdecl; written: int64_t; (* * * Maximum reached position before a backward seek in the write buffer, * used keeping track of already written data for a later flush. *) buf_ptr_max: punsigned_char; (* * * Try to buffer at least this amount of data before flushing it *) min_packet_size: int; end; (* * * Return the name of the protocol that will handle the passed URL. * * NULL is returned if no protocol could be found for the given URL. * * @return Name of the protocol or NULL. *) // const char *avio_find_protocol_name(const char *url); function avio_find_protocol_name(const url: PAnsiChar): PAnsiChar; cdecl; external avformat_dll; (* * * Return AVIO_FLAG_* access flags corresponding to the access permissions * of the resource in url, or a negative value corresponding to an * AVERROR code in case of failure. The returned access flags are * masked by the value in flags. * * @note This function is intrinsically unsafe, in the sense that the * checked resource may change its existence or permission status from * one call to another. Thus you should not trust the returned value, * unless you are sure that no other processes are accessing the * checked resource. *) // int avio_check(const char *url, int flags); function avio_check(const url: PAnsiChar; flags: int): int; cdecl; external avformat_dll; (* * * Move or rename a resource. * * @note url_src and url_dst should share the same protocol and authority. * * @param url_src url to resource to be moved * @param url_dst new url to resource if the operation succeeded * @return >=0 on success or negative on error. *) // int avpriv_io_move(const char *url_src, const char *url_dst); function avpriv_io_move(const url_src: PAnsiChar; const url_dst: PAnsiChar): int; cdecl; external avformat_dll; (* * * Delete a resource. * * @param url resource to be deleted. * @return >=0 on success or negative on error. *) // int avpriv_io_delete(const char *url); function avpriv_io_delete(const url: PAnsiChar): int; cdecl; external avformat_dll; (* * * Open directory for reading. * * @param s directory read context. Pointer to a NULL pointer must be passed. * @param url directory to be listed. * @param options A dictionary filled with protocol-private options. On return * this parameter will be destroyed and replaced with a dictionary * containing options that were not found. May be NULL. * @return >=0 on success or negative on error. *) // int avio_open_dir(AVIODirContext **s, const char *url, AVDictionary **options); function avio_open_dir(var s: pAVIODirContext; const url: PAnsiChar; options: ppAVDictionary): int; cdecl; external avformat_dll; (* * * Get next directory entry. * * Returned entry must be freed with avio_free_directory_entry(). In particular * it may outlive AVIODirContext. * * @param s directory read context. * @param[out] next next entry or NULL when no more entries. * @return >=0 on success or negative on error. End of list is not considered an * error. *) // int avio_read_dir(AVIODirContext *s, AVIODirEntry **next); function avio_read_dir(s: pAVIODirContext; var next: pAVIODirEntry): int; cdecl; external avformat_dll; (* * * Close directory. * * @note Entries created using avio_read_dir() are not deleted and must be * freeded with avio_free_directory_entry(). * * @param s directory read context. * @return >=0 on success or negative on error. *) // int avio_close_dir(AVIODirContext **s); function avio_close_dir(var s: pAVIODirContext): int; cdecl; external avformat_dll; (* * * Free entry allocated by avio_read_dir(). * * @param entry entry to be freed. *) // void avio_free_directory_entry(AVIODirEntry **entry); procedure avio_free_directory_entry(var entry: pAVIODirEntry); cdecl; external avformat_dll; (* * * Allocate and initialize an AVIOContext for buffered I/O. It must be later * freed with avio_context_free(). * * @param buffer Memory block for input/output operations via AVIOContext. * The buffer must be allocated with av_malloc() and friends. * It may be freed and replaced with a new buffer by libavformat. * AVIOContext.buffer holds the buffer currently in use, * which must be later freed with av_free(). * @param buffer_size The buffer size is very important for performance. * For protocols with fixed blocksize it should be set to this blocksize. * For others a typical size is a cache page, e.g. 4kb. * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise. * @param opaque An opaque pointer to user-specific data. * @param read_packet A function for refilling the buffer, may be NULL. * For stream protocols, must never return 0 but rather * a proper AVERROR code. * @param write_packet A function for writing the buffer contents, may be NULL. * The function may not change the input buffers content. * @param seek A function for seeking to specified byte position, may be NULL. * * @return Allocated AVIOContext or NULL on failure. *) // AVIOContext *avio_alloc_context( // unsigned char *buffer, // int buffer_size, // int write_flag, // void *opaque, // int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), // int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), // int64_t (*seek)(void *opaque, int64_t offset, int whence)); type // int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), Tavio_alloc_context_read_packet = function(opaque: pointer; buf: puint8_t; buf_size: int): int; cdecl; // int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), Tavio_alloc_context_write_packet = Tavio_alloc_context_read_packet; // int64_t (*seek)(void *opaque, int64_t offset, int whence) Tavio_alloc_context_seek = function(opaque: pointer; offset: int64_t; whence: int): int64_t; cdecl; function avio_alloc_context(buffer: punsigned_char; buffer_size: int; write_flag: int; opaque: pointer; read_packet: Tavio_alloc_context_read_packet; write_packet: Tavio_alloc_context_write_packet; seek: Tavio_alloc_context_seek): pAVIOContext; cdecl; external avformat_dll; (* * * Free the supplied IO context and everything associated with it. * * @param s Double pointer to the IO context. This function will write NULL * into s. *) // void avio_context_free(AVIOContext **s); procedure avio_context_free(var s: pAVIOContext); cdecl; external avformat_dll; // void avio_w8(AVIOContext *s, int b); procedure avio_w8(s: pAVIOContext; b: int); cdecl; external avformat_dll; // void avio_write(AVIOContext *s, const unsigned char *buf, int size); procedure avio_write(s: pAVIOContext; const buf: punsigned_char; size: int); cdecl; external avformat_dll; // void avio_wl64(AVIOContext *s, uint64_t val); procedure avio_wl64(s: pAVIOContext; val: uint64_t); cdecl; external avformat_dll; // void avio_wb64(AVIOContext *s, uint64_t val); procedure avio_wb64(s: pAVIOContext; val: uint64_t); cdecl; external avformat_dll; // void avio_wl32(AVIOContext *s, unsigned int val); procedure avio_wl32(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; // void avio_wb32(AVIOContext *s, unsigned int val); procedure avio_wb32(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; // void avio_wl24(AVIOContext *s, unsigned int val); procedure avio_wl24(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; // void avio_wb24(AVIOContext *s, unsigned int val); procedure avio_wb24(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; // void avio_wl16(AVIOContext *s, unsigned int val); procedure avio_wl16(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; // void avio_wb16(AVIOContext *s, unsigned int val); procedure avio_wb16(s: pAVIOContext; val: unsigned_int); cdecl; external avformat_dll; (* * * Write a NULL-terminated string. * @return number of bytes written. *) // int avio_put_str(AVIOContext *s, const char *str); function avio_put_str(s: pAVIOContext; const str: PAnsiChar): int; cdecl; external avformat_dll; (* * * Convert an UTF-8 string to UTF-16LE and write it. * @param s the AVIOContext * @param str NULL-terminated UTF-8 string * * @return number of bytes written. *) // int avio_put_str16le(AVIOContext *s, const char *str); function avio_put_str16le(s: pAVIOContext; const str: PAnsiChar): int; cdecl; external avformat_dll; (* * * Convert an UTF-8 string to UTF-16BE and write it. * @param s the AVIOContext * @param str NULL-terminated UTF-8 string * * @return number of bytes written. *) // int avio_put_str16be(AVIOContext *s, const char *str); function avio_put_str16be(s: pAVIOContext; const str: PAnsiChar): int; cdecl; external avformat_dll; (* * * Mark the written bytestream as a specific type. * * Zero-length ranges are omitted from the output. * * @param time the stream time the current bytestream pos corresponds to * (in AV_TIME_BASE units), or AV_NOPTS_VALUE if unknown or not * applicable * @param type the kind of data written starting at the current pos *) // void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type); procedure avio_write_marker(s: pAVIOContext; time: int64_t; _type: AVIODataMarkerType); cdecl; external avformat_dll; const (* * * ORing this as the "whence" parameter to a seek function causes it to * return the filesize without seeking anywhere. Supporting this is optional. * If it is not supported then the seek function will return <0. *) AVSEEK_SIZE = $10000; (* * * Passing this flag as the "whence" parameter to a seek function causes it to * seek by any means (like reopening and linear reading) or other normally unreasonable * means that can be extremely slow. * This may be ignored by the seek code. *) AVSEEK_FORCE = $20000; (* * * fseek() equivalent for AVIOContext. * @return new position or AVERROR. *) // int64_t avio_seek(AVIOContext *s, int64_t offset, int whence); function avio_seek(s: pAVIOContext; offset: int64_t; whence: int): int64_t; cdecl; external avformat_dll; (* * * Skip given number of bytes forward * @return new position or AVERROR. *) // int64_t avio_skip(AVIOContext *s, int64_t offset); function avio_skip(s: pAVIOContext; offset: int64_t): int64_t; cdecl; external avformat_dll; (* * * ftell() equivalent for AVIOContext. * @return position or AVERROR. *) // static av_always_inline int64_t avio_tell(AVIOContext *s) // { // return avio_seek(s, 0, SEEK_CUR); // } function avio_tell(s: pAVIOContext): int64_t; inline; (* * * Get the filesize. * @return filesize or AVERROR *) // int64_t avio_size(AVIOContext *s); function avio_size(s: pAVIOContext): int64_t; cdecl; external avformat_dll; (* * * Similar to feof() but also returns nonzero on read errors. * @return non zero if and only if at end of file or a read error happened when reading. *) // int avio_feof(AVIOContext *s); function avio_feof(s: pAVIOContext): int; cdecl; external avformat_dll; (* * Writes a formatted string to the context. * @return number of bytes written, < 0 on error. *) // int avio_printf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3); (* * * Write a NULL terminated array of strings to the context. * Usually you don't need to use this function directly but its macro wrapper, * avio_print. *) // void avio_print_string_array(AVIOContext *s, const char *strings[]); procedure avio_print_string_array(s: pAVIOContext; const strings: pAnsiCharArray); cdecl; external avformat_dll; (* * Write strings (const char* ) to the context. * This is a convenience macro around avio_print_string_array and it * automatically creates the string array from the variable argument list. * For simple string concatenations this function is more performant than using * avio_printf since it does not need a temporary buffer. *) // #define avio_print(s, ...) avio_print_string_array(s, (const char*[]){__VA_ARGS__, NULL}) (* * * Force flushing of buffered data. * * For write streams, force the buffered data to be immediately written to the output, * without to wait to fill the internal buffer. * * For read streams, discard all currently buffered data, and advance the * reported file position to that of the underlying stream. This does not * read new data, and does not perform any seeks. *) // void avio_flush(AVIOContext *s); procedure avio_flush(s: pAVIOContext); cdecl; external avformat_dll; (* * * Read size bytes from AVIOContext into buf. * @return number of bytes read or AVERROR *) // int avio_read(AVIOContext *s, unsigned char *buf, int size); function avio_read(s: pAVIOContext; buf: punsigned_char; size: int): int; cdecl; external avformat_dll; (* * * Read size bytes from AVIOContext into buf. Unlike avio_read(), this is allowed * to read fewer bytes than requested. The missing bytes can be read in the next * call. This always tries to read at least 1 byte. * Useful to reduce latency in certain cases. * @return number of bytes read or AVERROR *) // int avio_read_partial(AVIOContext *s, unsigned char *buf, int size); function avio_read_partial(s: pAVIOContext; buf: punsigned_char; size: int): int; cdecl; external avformat_dll; (* * * @name Functions for reading from AVIOContext * @{ * * @note return 0 if EOF, so you cannot use it if EOF handling is * necessary *) // int avio_r8 (AVIOContext *s); function avio_r8(s: pAVIOContext): int; cdecl; external avformat_dll; // unsigned int avio_rl16(AVIOContext *s); function avio_rl16(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // unsigned int avio_rl24(AVIOContext *s); function avio_rl24(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // unsigned int avio_rl32(AVIOContext *s); function avio_rl32(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // uint64_t avio_rl64(AVIOContext *s); function avio_rl64(s: pAVIOContext): uint64_t; cdecl; external avformat_dll; // unsigned int avio_rb16(AVIOContext *s); function avio_rb16(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // unsigned int avio_rb24(AVIOContext *s); function avio_rb24(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // unsigned int avio_rb32(AVIOContext *s); function avio_rb32(s: pAVIOContext): unsigned_int; cdecl; external avformat_dll; // uint64_t avio_rb64(AVIOContext *s); function avio_rb64(s: pAVIOContext): uint64_t; cdecl; external avformat_dll; (* * * @} *) (* * * Read a string from pb into buf. The reading will terminate when either * a NULL character was encountered, maxlen bytes have been read, or nothing * more can be read from pb. The result is guaranteed to be NULL-terminated, it * will be truncated if buf is too small. * Note that the string is not interpreted or validated in any way, it * might get truncated in the middle of a sequence for multi-byte encodings. * * @return number of bytes read (is always <= maxlen). * If reading ends on EOF or error, the return value will be one more than * bytes actually read. *) // int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen); function avio_get_str(pb: pAVIOContext; maxlen: int; buf: PAnsiChar; buflen: int): int; cdecl; external avformat_dll; (* * * Read a UTF-16 string from pb and convert it to UTF-8. * The reading will terminate when either a null or invalid character was * encountered or maxlen bytes have been read. * @return number of bytes read (is always <= maxlen) *) // int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen); function avio_get_str16le(pb: pAVIOContext; maxlen: int; buf: PAnsiChar; buflen: int): int; cdecl; external avformat_dll; // int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen); function avio_get_str16be(pb: pAVIOContext; maxlen: int; buf: PAnsiChar; buflen: int): int; cdecl; external avformat_dll; const (* * * @name URL open modes * The flags argument to avio_open must be one of the following * constants, optionally ORed with other flags. * *) AVIO_FLAG_READ = 1; (* *< read-only *) AVIO_FLAG_WRITE = 2; (* *< write-only *) AVIO_FLAG_READ_WRITE = (AVIO_FLAG_READ or AVIO_FLAG_WRITE); (* *< read-write pseudo flag *) (* * * Use non-blocking mode. * If this flag is set, operations on the context will return * AVERROR(EAGAIN) if they can not be performed immediately. * If this flag is not set, operations on the context will never return * AVERROR(EAGAIN). * Note that this flag does not affect the opening/connecting of the * context. Connecting a protocol will always block if necessary (e.g. on * network protocols) but never hang (e.g. on busy devices). * Warning: non-blocking protocols is work-in-progress; this flag may be * silently ignored. *) AVIO_FLAG_NONBLOCK = 8; (* * * Use direct mode. * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. *) AVIO_FLAG_DIRECT = $8000; (* * * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure *) // int avio_open(AVIOContext **s, const char *url, int flags); function avio_open(var s: pAVIOContext; const url: PAnsiChar; flags: int): int; cdecl; external avformat_dll; (* * * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @param int_cb an interrupt callback to be used at the protocols level * @param options A dictionary filled with protocol-private options. On return * this parameter will be destroyed and replaced with a dict containing options * that were not found. May be NULL. * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure *) // int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); function avio_open2(var s: pAVIOContext; const url: PAnsiChar; flags: int; const int_cb: pAVIOInterruptCB; var options: pAVDictionary): int; cdecl; external avformat_dll; (* * * Close the resource accessed by the AVIOContext s and free it. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_closep *) // int avio_close(AVIOContext *s); function avio_close(s: pAVIOContext): int; cdecl; external avformat_dll; (* * * Close the resource accessed by the AVIOContext *s, free it * and set the pointer pointing to it to NULL. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_close *) // int avio_closep(AVIOContext **s); function avio_closep(var s: pAVIOContext): int; cdecl; external avformat_dll; (* * * Open a write only memory stream. * * @param s new IO context * @return zero if no error. *) // int avio_open_dyn_buf(AVIOContext **s); function avio_open_dyn_buf(var s: pAVIOContext): int; cdecl; external avformat_dll; (* * * Return the written size and a pointer to the buffer. * The AVIOContext stream is left intact. * The buffer must NOT be freed. * No padding is added to the buffer. * * @param s IO context * @param pbuffer pointer to a byte buffer * @return the length of the byte buffer *) // int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer); function avio_get_dyn_buf(s: pAVIOContext; var pbuffer: puint8_t): int; cdecl; external avformat_dll; (* * * Return the written size and a pointer to the buffer. The buffer * must be freed with av_free(). * Padding of AV_INPUT_BUFFER_PADDING_SIZE is added to the buffer. * * @param s IO context * @param pbuffer pointer to a byte buffer * @return the length of the byte buffer *) // int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer); function avio_close_dyn_buf(s: pAVIOContext; var pbuffer: puint8_t): int; cdecl; external avformat_dll; (* * * Iterate through names of available protocols. * * @param opaque A private pointer representing current protocol. * It must be a pointer to NULL on first iteration and will * be updated by successive calls to avio_enum_protocols. * @param output If set to 1, iterate over output protocols, * otherwise over input protocols. * * @return A static string containing the name of current protocol or NULL *) // const char *avio_enum_protocols(void **opaque, int output); function avio_enum_protocols(var opaque: pointer; output: int): PAnsiChar; cdecl; external avformat_dll; (* * * Pause and resume playing - only meaningful if using a network streaming * protocol (e.g. MMS). * * @param h IO context from which to call the read_pause function pointer * @param pause 1 for pause, 0 for resume *) // int avio_pause(AVIOContext *h, int pause); function avio_pause(h: pAVIOContext; pause: int): int; cdecl; external avformat_dll; (* * * Seek to a given timestamp relative to some component stream. * Only meaningful if using a network streaming protocol (e.g. MMS.). * * @param h IO context from which to call the seek function pointers * @param stream_index The stream index that the timestamp is relative to. * If stream_index is (-1) the timestamp should be in AV_TIME_BASE * units from the beginning of the presentation. * If a stream_index >= 0 is used and the protocol does not support * seeking based on component streams, the call will fail. * @param timestamp timestamp in AVStream.time_base units * or if there is no stream specified then in AV_TIME_BASE units. * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE * and AVSEEK_FLAG_ANY. The protocol may silently ignore * AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will * fail if used and not supported. * @return >= 0 on success * @see AVInputFormat::read_seek *) // int64_t avio_seek_time(AVIOContext *h, int stream_index, int64_t timestamp, int flags); function avio_seek_time(h: pAVIOContext; stream_index: int; timestamp: int64_t; flags: int): int64_t; cdecl; external avformat_dll; (* * * Read contents of h into print buffer, up to max_size bytes, or up to EOF. * * @return 0 for success (max_size bytes read or EOF reached), negative error * code otherwise *) // int avio_read_to_bprint(AVIOContext *h, struct AVBPrint *pb, size_t max_size); function avio_read_to_bprint(h: pAVIOContext; pb: pAVBPrint; max_size: size_t): int; cdecl; external avformat_dll; (* * * Accept and allocate a client context on a server context. * @param s the server context * @param c the client context, must be unallocated * @return >= 0 on success or a negative value corresponding * to an AVERROR on failure *) // int avio_accept(AVIOContext *s, AVIOContext **c); function avio_accept(s: pAVIOContext; var c: pAVIOContext): int; cdecl; external avformat_dll; (* * * Perform one step of the protocol handshake to accept a new client. * This function must be called on a client returned by avio_accept() before * using it as a read/write context. * It is separate from avio_accept() because it may block. * A step of the handshake is defined by places where the application may * decide to change the proceedings. * For example, on a protocol with a request header and a reply header, each * one can constitute a step because the application may use the parameters * from the request to change parameters in the reply; or each individual * chunk of the request can constitute a step. * If the handshake is already finished, avio_handshake() does nothing and * returns 0 immediately. * * @param c the client context to perform the handshake on * @return 0 on a complete and successful handshake * > 0 if the handshake progressed, but is not complete * < 0 for an AVERROR code *) // int avio_handshake(AVIOContext *c); function avio_handshake(c: pAVIOContext): int; cdecl; external avformat_dll; {$ENDREGION} const // AVFormatContext -> int flags; AVFMT_FLAG_GENPTS = $0001; // < Generate missing pts even if it requires parsing future frames. AVFMT_FLAG_IGNIDX = $0002; // < Ignore index. AVFMT_FLAG_NONBLOCK = $0004; // < Do not block when reading packets from input. AVFMT_FLAG_IGNDTS = $0008; // < Ignore DTS on frames that contain both DTS & PTS AVFMT_FLAG_NOFILLIN = $0010; // < Do not infer any values from other values, just return what is stored in the container AVFMT_FLAG_NOPARSE = $0020; // < Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled AVFMT_FLAG_NOBUFFER = $0040; // < Do not buffer frames when possible AVFMT_FLAG_CUSTOM_IO = $0080; // < The caller has supplied a custom AVIOContext, don't avio_close() it. AVFMT_FLAG_DISCARD_CORRUPT = $0100; // < Discard frames marked corrupted AVFMT_FLAG_FLUSH_PACKETS = $0200; // < Flush the AVIOContext every packet. (* * * When muxing, try to avoid writing any random/volatile data to the output. * This includes any random IDs, real-time timestamps/dates, muxer version, etc. * * This flag is mainly intended for testing. *) AVFMT_FLAG_BITEXACT = $0400; {$IFDEF FF_API_LAVF_MP4A_LATM} // < Enable RTP MP4A-LATM payload AVFMT_FLAG_MP4A_LATM = $8000; /// < Deprecated, does nothing. {$ENDIF} AVFMT_FLAG_SORT_DTS = $10000; // < try to interleave outputted packets by dts (using this flag can slow demuxing down) AVFMT_FLAG_PRIV_OPT = $20000; // < Enable use of private options by delaying codec open (this could be made default once all code is converted) {$IFDEF FF_API_LAVF_KEEPSIDE_FLAG} AVFMT_FLAG_KEEP_SIDE_DATA = $40000; // < Deprecated, does nothing. {$ENDIF} AVFMT_FLAG_FAST_SEEK = $80000; // < Enable fast, but inaccurate seeks for some formats AVFMT_FLAG_SHORTEST = $100000; // < Stop muxing when the shortest stream stops. AVFMT_FLAG_AUTO_BSF = $200000; // < Add bitstream filters as requested by the muxer // AVFormatContext ->int debug; FF_FDEBUG_TS = $0001; // AVFormatContext ->int event_flags; AVFMT_EVENT_FLAG_METADATA_UPDATED = $0001; // < The call resulted in updated metadata. // AVFormatContext ->int avoid_negative_ts; AVFMT_AVOID_NEG_TS_AUTO = -1; // < Enabled when required by target format AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE = 1; // < Shift timestamps so they are non negative AVFMT_AVOID_NEG_TS_MAKE_ZERO = 2; // < Shift timestamps so that they start at 0 // AVProgram AV_PROGRAM_RUNNING = 1; // AVFMTCTX_NOHEADER = $0001; (* *< signal that no header is present (streams are added dynamically) *) AVFMTCTX_UNSEEKABLE = $0002; (* *< signal that the stream is definitely not seekable, and attempts to call the seek function will fail. For some network protocols (e.g. HLS), this can change dynamically at runtime. *) const AVPROBE_SCORE_EXTENSION = 50; // < score for file extension AVPROBE_SCORE_MIME = 75; // < score for file mime type AVPROBE_SCORE_MAX = 100; // < maximum score AVPROBE_PADDING_SIZE = 32; // < extra allocated bytes at the end of the probe buffer AVPROBE_SCORE_RETRY = (AVPROBE_SCORE_MAX div 4); AVPROBE_SCORE_STREAM_RETRY = (AVPROBE_SCORE_MAX div 4 - 1); // Demuxer will use avio_open, no opened file should be provided by the caller. AVFMT_NOFILE = $0001; AVFMT_NEEDNUMBER = $0002; (* *< Needs '%d' in filename. *) AVFMT_SHOW_IDS = $0008; (* *< Show format stream IDs numbers. *) AVFMT_GLOBALHEADER = $0040; (* *< Format wants global header. *) AVFMT_NOTIMESTAMPS = $0080; (* *< Format does not need / have any timestamps. *) AVFMT_GENERIC_INDEX = $0100; (* *< Use generic index building code. *) AVFMT_TS_DISCONT = $0200; (* *< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps *) AVFMT_VARIABLE_FPS = $0400; (* *< Format allows variable fps. *) AVFMT_NODIMENSIONS = $0800; (* *< Format does not need width/height *) AVFMT_NOSTREAMS = $1000; (* *< Format does not require any streams *) AVFMT_NOBINSEARCH = $2000; (* *< Format does not allow to fall back on binary search via read_timestamp *) AVFMT_NOGENSEARCH = $4000; (* *< Format does not allow to fall back on generic search *) AVFMT_NO_BYTE_SEEK = $8000; (* *< Format does not allow seeking by bytes *) AVFMT_ALLOW_FLUSH = $10000; (* *< Format allows flushing. If not set, the muxer will not receive a NULL packet in the write_packet function. *) AVFMT_TS_NONSTRICT = $20000; (* *< Format does not require strictly increasing timestamps, but they must still be monotonic *) AVFMT_TS_NEGATIVE = $40000; (* *< Format allows muxing negative timestamps. If not set the timestamp will be shifted in av_write_frame and av_interleaved_write_frame so they start from 0. The user or muxer can override this through AVFormatContext.avoid_negative_ts *) AVFMT_SEEK_TO_PTS = $4000000; (* *< Seeking is based on PTS *) AVINDEX_KEYFRAME = $0001; AVINDEX_DISCARD_FRAME = $0002; AV_DISPOSITION_DEFAULT = $0001; AV_DISPOSITION_DUB = $0002; AV_DISPOSITION_ORIGINAL = $0004; AV_DISPOSITION_COMMENT = $0008; AV_DISPOSITION_LYRICS = $0010; AV_DISPOSITION_KARAOKE = $0020; (* * * Track should be used during playback by default. * Useful for subtitle track that should be displayed * even when user did not explicitly ask for subtitles. *) AV_DISPOSITION_FORCED = $0040; AV_DISPOSITION_HEARING_IMPAIRED = $0080; (* *< stream for hearing impaired audiences *) AV_DISPOSITION_VISUAL_IMPAIRED = $0100; (* *< stream for visual impaired audiences *) AV_DISPOSITION_CLEAN_EFFECTS = $0200; (* *< stream without voice *) (* * * The stream is stored in the file as an attached picture/"cover art" (e.g. * APIC frame in ID3v2). The first (usually only) packet associated with it * will be returned among the first few packets read from the file unless * seeking takes place. It can also be accessed at any time in * AVStream.attached_pic. *) AV_DISPOSITION_ATTACHED_PIC = $0400; (* * * The stream is sparse, and contains thumbnail images, often corresponding * to chapter markers. Only ever used with AV_DISPOSITION_ATTACHED_PIC. *) AV_DISPOSITION_TIMED_THUMBNAILS = $0800; (* * * To specify text track kind (different from subtitles default). *) AV_DISPOSITION_CAPTIONS = $10000; AV_DISPOSITION_DESCRIPTIONS = $20000; AV_DISPOSITION_METADATA = $40000; AV_DISPOSITION_DEPENDENT = $80000; // < dependent audio stream (mix_type=0 in mpegts) AV_DISPOSITION_STILL_IMAGE = $100000; /// < still images in video stream (still_picture_flag=1 in mpegts) (* * * Options for behavior on timestamp wrap detection. *) AV_PTS_WRAP_IGNORE = 0; // < ignore the wrap AV_PTS_WRAP_ADD_OFFSET = 1; // < add the format specific offset on wrap detection AV_PTS_WRAP_SUB_OFFSET = -1; // < subtract the format specific offset on wrap detection AVSTREAM_EVENT_FLAG_METADATA_UPDATED = $0001; // < The call resulted in updated metadata. (* **************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * Internal note: be aware that physically removing these fields * will break ABI. Replace removed fields with dummy fields, and * add new fields to AVStreamInternal. ***************************************************************** *) MAX_STD_TIMEBASES = (30 * 12 + 30 + 3 + 6); MAX_REORDER_DELAY = 16; type pAVFormatContext = ^AVFormatContext; ppAVFormatContext = ^pAVFormatContext; pAVFormatInternal = ^AVFormatInternal; pAVInputFormat = ^AVInputFormat; pAVCodecTag = ^AVCodecTag; ppAVCodecTag = ^pAVCodecTag; pAVProbeData = ^AVProbeData; pAVDeviceInfoList = ^AVDeviceInfoList; pAVDeviceCapabilitiesQuery = ^AVDeviceCapabilitiesQuery; pAVOutputFormat = ^AVOutputFormat; pAVChapter = ^AVChapter; ppAVChapter = ^pAVChapter; pAVStream = ^AVStream; ppAVStream = ^pAVStream; pAVProgram = ^AVProgram; ppAVProgram = ^pAVProgram; AVChapter = record id: int; // < unique ID to identify the chapter time_base: AVRational; // < time base in which the start/end timestamps are specified start, _end: int64_t; // < chapter start/end time in time_base units metadata: pAVDictionary; end; (* * * Callback used by devices to communicate with application. *) // typedef int (*av_format_control_message)(struct AVFormatContext *s, int type, // void *data, size_t data_size); Tav_format_control_message = function(s: pAVFormatContext; _type: int; data: pointer; data_size: size_t): int; cdecl; // typedef int (*AVOpenCallback)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, // const AVIOInterruptCB *int_cb, AVDictionary **options); TAVOpenCallback = function(s: pAVFormatContext; var pb: pAVIOContext; const url: PAnsiChar; flags: int; const int_cb: pAVIOInterruptCB; var options: pAVDictionary): int; cdecl; (* * * The duration of a video can be estimated through various ways, and this enum can be used * to know how the duration was estimated. *) AVDurationEstimationMethod = ( // AVFMT_DURATION_FROM_PTS, // < Duration accurately estimated from PTSes AVFMT_DURATION_FROM_STREAM, // < Duration estimated from a stream with a known duration AVFMT_DURATION_FROM_BITRATE // < Duration estimated from bitrate (less accurate) ); AVFormatInternal = record end; AVInputFormat = record (* * * A comma separated list of short names for the format. New names * may be appended with a minor bump. *) name: PAnsiChar; (* * * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. *) long_name: PAnsiChar; (* * * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS, * AVFMT_NOTIMESTAMPS, AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH, * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS. *) flags: int; (* * * If extensions are defined, then no probe is done. You should * usually not use extension format guessing because it is not * reliable enough *) extensions: PAnsiChar; codec_tag: ppAVCodecTag; priv_class: pAVClass; // < AVClass for the private context (* * * Comma-separated list of mime types. * It is used check for matching mime types while probing. * @see av_probe_input_format2 *) mime_type: PAnsiChar; (* **************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** *) next: pAVInputFormat; (* * * Raw demuxers store their codec ID here. *) raw_codec_id: int; (* * * Size of private data so that it can be allocated in the wrapper. *) priv_data_size: int; (* * * Tell if a given file has a chance of being parsed as this format. * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes * big so you do not have to check for that unless you need more. *) // int (*read_probe)(AVProbeData *); read_probe: function(const p: pAVProbeData): int; cdecl; (* * * Read the format header and initialize the AVFormatContext * structure. Return 0 if OK. 'avformat_new_stream' should be * called to create new streams. *) // int (*read_header)(struct AVFormatContext *); read_header: function(p: pAVFormatContext): int; cdecl; (* * * Read one packet and put it in 'pkt'. pts and flags are also * set. 'avformat_new_stream' can be called only if the flag * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a * background thread). * @return 0 on success, < 0 on error. * When returning an error, pkt must not have been allocated * or must be freed before returning *) // int (*read_packet)(struct AVFormatContext *, AVPacket *pkt); read_packet: function(p: pAVFormatContext; pkt: pAVPacket): int; cdecl; (* * * Close the stream. The AVFormatContext and AVStreams are not * freed by this function *) // int (*read_close)(struct AVFormatContext *); read_close: function(p: pAVFormatContext): int; cdecl; (* * * Seek to a given timestamp relative to the frames in * stream component stream_index. * @param stream_index Must not be -1. * @param flags Selects which direction should be preferred if no exact * match is available. * @return >= 0 on success (but not necessarily the new offset) *) // int (*read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags); read_seek: function(p: pAVFormatContext; stream_index: int; timestamp: int64_t; flags: int): int; cdecl; (* * * Get the next timestamp in stream[stream_index].time_base units. * @return the timestamp or AV_NOPTS_VALUE if an error occurred *) // int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit); read_timestamp: function(s: pAVFormatContext; stream_index: int; var pos: int64_t; pos_limit: int64_t): int64_t; cdecl; (* * * Start/resume playing - only meaningful if using a network-based format * (RTSP). *) // int (*read_play)(struct AVFormatContext *); read_play: function(p: pAVFormatContext): int; cdecl; (* * * Pause playing - only meaningful if using a network-based format * (RTSP). *) // int (*read_pause)(struct AVFormatContext *); read_pause: function(p: pAVFormatContext): int; cdecl; (* * * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. *) // int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); read_seek2: function(s: pAVFormatContext; stream_index: int; min_ts: int64_t; ts: int64_t; max_ts: int64_t; flags: int): int; cdecl; (* * * Returns device list with it properties. * @see avdevice_list_devices() for more details. *) // int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); get_device_list: function(s: pAVFormatContext; device_list: pAVDeviceInfoList): int; cdecl; (* * * Initialize device capabilities submodule. * @see avdevice_capabilities_create() for more details. *) // int (*create_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); create_device_capabilities: function(s: pAVFormatContext; caps: pAVDeviceCapabilitiesQuery): int; cdecl; (* * * Free device capabilities submodule. * @see avdevice_capabilities_free() for more details. *) // int (*free_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); free_device_capabilities: function(s: pAVFormatContext; caps: pAVDeviceCapabilitiesQuery): int; cdecl; end; (* * * Format I/O context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVFormatContext) must not be used outside libav*, use * avformat_alloc_context() to create an AVFormatContext. * * Fields can be accessed through AVOptions (av_opt* ), * the name string used matches the associated command line parameter name and * can be found in libavformat/options_table.h. * The AVOption/command line parameter names differ in some cases from the C * structure field names for historic reasons or brevity. *) AVFormatContext = record (* * * A class for logging and @ref avoptions. Set by avformat_alloc_context(). * Exports (de)muxer private options if they exist. *) av_class: pAVClass; (* * * The input container format. * * Demuxing only, set by avformat_open_input(). *) iformat: pAVInputFormat; (* * * The output container format. * * Muxing only, must be set by the caller before avformat_write_header(). *) oformat: pAVOutputFormat; (* * * Format private data. This is an AVOptions-enabled struct * if and only if iformat/oformat.priv_class is not NULL. * * - muxing: set by avformat_write_header() * - demuxing: set by avformat_open_input() *) priv_data: pointer; (* * * I/O context. * * - demuxing: either set by the user before avformat_open_input() (then * the user must close it manually) or set by avformat_open_input(). * - muxing: set by the user before avformat_write_header(). The caller must * take care of closing / freeing the IO context. * * Do NOT set this field if AVFMT_NOFILE flag is set in * iformat/oformat.flags. In such a case, the (de)muxer will handle * I/O in some other way and this field will be NULL. *) pb: pAVIOContext; (* stream info *) (* * * Flags signalling stream properties. A combination of AVFMTCTX_*. * Set by libavformat. *) ctx_flags: int; (* * * Number of elements in AVFormatContext.streams. * * Set by avformat_new_stream(), must not be modified by any other code. *) nb_streams: unsigned_int; (* * * A list of all streams in the file. New streams are created with * avformat_new_stream(). * * - demuxing: streams are created by libavformat in avformat_open_input(). * If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also * appear in av_read_frame(). * - muxing: streams are created by the user before avformat_write_header(). * * Freed by libavformat in avformat_free_context(). *) streams: ppAVStream; {$IFDEF FF_API_FORMAT_FILENAME} (* * * input or output filename * * - demuxing: set by avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() * * @deprecated Use url instead. *) // attribute_deprecated filename: array [0 .. 1024 - 1] of AnsiChar; {$ENDIF} (* * * input or output URL. Unlike the old filename field, this field has no * length restriction. * * - demuxing: set by avformat_open_input(), initialized to an empty * string if url parameter was NULL in avformat_open_input(). * - muxing: may be set by the caller before calling avformat_write_header() * (or avformat_init_output() if that is called first) to a string * which is freeable by av_free(). Set to an empty string if it * was NULL in avformat_init_output(). * * Freed by libavformat in avformat_free_context(). *) url: PAnsiChar; (* * * Position of the first frame of the component, in * AV_TIME_BASE fractional seconds. NEVER set this value directly: * It is deduced from the AVStream values. * * Demuxing only, set by libavformat. *) start_time: int64_t; (* * * Duration of the stream, in AV_TIME_BASE fractional * seconds. Only set this value if you know none of the individual stream * durations and also do not set any of them. This is deduced from the * AVStream values if not set. * * Demuxing only, set by libavformat. *) duration: int64_t; (* * * Total stream bitrate in bit/s, 0 if not * available. Never set it directly if the file_size and the * duration are known as FFmpeg can compute it automatically. *) bit_rate: int64_t; packet_size: unsigned_int; max_delay: int; (* * * Flags modifying the (de)muxer behaviour. A combination of AVFMT_FLAG_*. * Set by the user before avformat_open_input() / avformat_write_header(). *) flags: int; (* * * Maximum size of the data read from input for determining * the input container format. * Demuxing only, set by the caller before avformat_open_input(). *) robesize: int64_t; (* * * Maximum duration (in AV_TIME_BASE units) of the data read * from input in avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). * Can be set to 0 to let avformat choose using a heuristic. *) ax_analyze_duration: int64_t; key: puint8_t; keylen: int; nb_programs: unsigned_int; programs: ppAVProgram; (* * * Forced video codec_id. * Demuxing: Set by user. *) video_codec_id: AVCodecID; (* * * Forced audio codec_id. * Demuxing: Set by user. *) audio_codec_id: AVCodecID; (* * * Forced subtitle codec_id. * Demuxing: Set by user. *) subtitle_codec_id: AVCodecID; (* * * Maximum amount of memory in bytes to use for the index of each stream. * If the index exceeds this size, entries will be discarded as * needed to maintain a smaller size. This can lead to slower or less * accurate seeking (depends on demuxer). * Demuxers for which a full in-memory index is mandatory will ignore * this. * - muxing: unused * - demuxing: set by user *) max_index_size: unsigned_int; (* * * Maximum amount of memory in bytes to use for buffering frames * obtained from realtime capture devices. *) max_picture_buffer: unsigned_int; (* * * Number of chapters in AVChapter array. * When muxing, chapters are normally written in the file header, * so nb_chapters should normally be initialized before write_header * is called. Some muxers (e.g. mov and mkv) can also write chapters * in the trailer. To write chapters in the trailer, nb_chapters * must be zero when write_header is called and non-zero when * write_trailer is called. * - muxing: set by user * - demuxing: set by libavformat *) nb_chapters: unsigned_int; chapters: ppAVChapter; (* * * Metadata that applies to the whole file. * * - demuxing: set by libavformat in avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() * * Freed by libavformat in avformat_free_context(). *) metadata: pAVDictionary; (* * * Start time of the stream in real world time, in microseconds * since the Unix epoch (00:00 1st January 1970). That is, pts=0 in the * stream was captured at this real world time. * - muxing: Set by the caller before avformat_write_header(). If set to * either 0 or AV_NOPTS_VALUE, then the current wall-time will * be used. * - demuxing: Set by libavformat. AV_NOPTS_VALUE if unknown. Note that * the value may become known after some number of frames * have been received. *) start_time_realtime: int64_t; (* * * The number of frames used for determining the framerate in * avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). *) fps_probe_size: int; (* * * Error recognition; higher values will detect more errors but may * misdetect some more or less valid parts as errors. * Demuxing only, set by the caller before avformat_open_input(). *) error_recognition: int; (* * * Custom interrupt callbacks for the I/O layer. * * demuxing: set by the user before avformat_open_input(). * muxing: set by the user before avformat_write_header() * (mainly useful for AVFMT_NOFILE formats). The callback * should also be passed to avio_open2() if it's used to * open the file. *) interrupt_callback: AVIOInterruptCB; (* * * Flags to enable debugging. *) debug: int; (* * * Maximum buffering duration for interleaving. * * To ensure all the streams are interleaved correctly, * av_interleaved_write_frame() will wait until it has at least one packet * for each stream before actually writing any packets to the output file. * When some streams are "sparse" (i.e. there are large gaps between * successive packets), this can result in excessive buffering. * * This field specifies the maximum difference between the timestamps of the * first and the last packet in the muxing queue, above which libavformat * will output a packet regardless of whether it has queued a packet for all * the streams. * * Muxing only, set by the caller before avformat_write_header(). *) max_interleave_delta: int64_t; (* * * Allow non-standard and experimental extension * @see AVCodecContext.strict_std_compliance *) strict_std_compliance: int; (* * * Flags for the user to detect events happening on the file. Flags must * be cleared by the user once the event has been handled. * A combination of AVFMT_EVENT_FLAG_*. *) event_flags: int; (* * * Maximum number of packets to read while waiting for the first timestamp. * Decoding only. *) max_ts_probe: int; (* * * Avoid negative timestamps during muxing. * Any value of the AVFMT_AVOID_NEG_TS_* constants. * Note, this only works when using av_interleaved_write_frame. (interleave_packet_per_dts is in use) * - muxing: Set by user * - demuxing: unused *) avoid_negative_ts: int; (* * * Transport stream id. * This will be moved into demuxer private options. Thus no API/ABI compatibility *) ts_id: int; (* * * Audio preload in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused *) audio_preload: int; (* * * Max chunk time in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused *) max_chunk_duration: int; (* * * Max chunk size in bytes * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused *) max_chunk_size: int; (* * * forces the use of wallclock timestamps as pts/dts of packets * This has undefined results in the presence of B frames. * - encoding: unused * - decoding: Set by user *) use_wallclock_as_timestamps: int; (* * * avio flags, used to force AVIO_FLAG_DIRECT. * - encoding: unused * - decoding: Set by user *) avio_flags: int; (* * * The duration field can be estimated through various ways, and this field can be used * to know how the duration was estimated. * - encoding: unused * - decoding: Read by user *) duration_estimation_method: AVDurationEstimationMethod; (* * * Skip initial bytes when opening stream * - encoding: unused * - decoding: Set by user *) skip_initial_bytes: int64_t; (* * * Correct single timestamp overflows * - encoding: unused * - decoding: Set by user *) correct_ts_overflow: unsigned_int; (* * * Force seeking to any (also non key) frames. * - encoding: unused * - decoding: Set by user *) seek2any: int; (* * * Flush the I/O context after each packet. * - encoding: Set by user * - decoding: unused *) flush_packets: int; (* * * format probing score. * The maximal score is AVPROBE_SCORE_MAX, its set when the demuxer probes * the format. * - encoding: unused * - decoding: set by avformat, read by user *) probe_score: int; (* * * number of bytes to read maximally to identify format. * - encoding: unused * - decoding: set by user *) format_probesize: int; (* * * ',' separated list of allowed decoders. * If NULL then all are allowed * - encoding: unused * - decoding: set by user *) codec_whitelist: PAnsiChar; (* * * ',' separated list of allowed demuxers. * If NULL then all are allowed * - encoding: unused * - decoding: set by user *) format_whitelist: PAnsiChar; (* * * An opaque field for libavformat internal usage. * Must not be accessed in any way by callers. *) internal: pAVFormatInternal; (* * * IO repositioned flag. * This is set by avformat when the underlaying IO context read pointer * is repositioned, for example when doing byte based seeking. * Demuxers can use the flag to detect such changes. *) io_repositioned: int; (* * * Forced video codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user *) video_codec: pAVCodec; (* * * Forced audio codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user *) audio_codec: pAVCodec; (* * * Forced subtitle codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user *) subtitle_codec: pAVCodec; (* * * Forced data codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user *) data_codec: pAVCodec; (* * * Number of bytes to be written as padding in a metadata header. * Demuxing: Unused. * Muxing: Set by user via av_format_set_metadata_header_padding. *) metadata_header_padding: int; (* * * User data. * This is a place for some private data of the user. *) opaque: pointer; (* * * Callback used by devices to communicate with application. *) control_message_cb: Tav_format_control_message; (* * * Output timestamp offset, in microseconds. * Muxing: set by user *) output_ts_offset: int64_t; (* * * dump format separator. * can be ", " or "\n " or anything else * - muxing: Set by user. * - demuxing: Set by user. *) dump_separator: puint8_t; (* * * Forced Data codec_id. * Demuxing: Set by user. *) data_codec_id: AVCodecID; {$IFDEF FF_API_OLD_OPEN_CALLBACKS} (* * * Called to open further IO contexts when needed for demuxing. * * This can be set by the user application to perform security checks on * the URLs before opening them. * The function should behave like avio_open2(), AVFormatContext is provided * as contextual information and to reach AVFormatContext.opaque. * * If NULL then some simple checks are used together with avio_open2(). * * Must not be accessed directly from outside avformat. * @See av_format_set_open_cb() * * Demuxing: Set by user. * * @deprecated Use io_open and io_close. *) // attribute_deprecated // int (*open_cb)(struct AVFormatContext *s, AVIOContext **p, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); open_cb: function(s: pAVFormatContext; var p: pAVIOContext; const url: PAnsiChar; flags: int; const int_cb: pAVIOInterruptCB; var options: pAVDictionary) : int; cdecl; {$ENDIF} (* * * ',' separated list of allowed protocols. * - encoding: unused * - decoding: set by user *) protocol_whitelist: PAnsiChar; (* * * A callback for opening new IO streams. * * Whenever a muxer or a demuxer needs to open an IO stream (typically from * avformat_open_input() for demuxers, but for certain formats can happen at * other times as well), it will call this callback to obtain an IO context. * * @param s the format context * @param pb on success, the newly opened IO context should be returned here * @param url the url to open * @param flags a combination of AVIO_FLAG_* * @param options a dictionary of additional options, with the same * semantics as in avio_open2() * @return 0 on success, a negative AVERROR code on failure * * @note Certain muxers and demuxers do nesting, i.e. they open one or more * additional internal format contexts. Thus the AVFormatContext pointer * passed to this callback may be different from the one facing the caller. * It will, however, have the same 'opaque' field. *) // int (*io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options); io_open: function(s: pAVFormatContext; var pb: pAVIOContext; const url: PAnsiChar; flags: int; var options: pAVDictionary): int; cdecl; (* * * A callback for closing the streams opened with AVFormatContext.io_open(). *) // void (*io_close)(struct AVFormatContext *s, AVIOContext *pb); io_close: procedure(s: pAVFormatContext; pb: pAVIOContext); cdecl; (* * * ',' separated list of disallowed protocols. * - encoding: unused * - decoding: set by user *) protocol_blacklist: PAnsiChar; (* * * The maximum number of streams. * - encoding: unused * - decoding: set by user *) max_streams: int; (* * Skip duration calcuation in estimate_timings_from_pts. * - encoding: unused * - decoding: set by user *) skip_estimate_duration_from_pts: int; end; (* input/output formats *) AVCodecTag = record end; (* * * This structure contains the data a format has to probe a file. *) AVProbeData = record filename: PAnsiChar; buf: punsigned_char; (* *< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. *) buf_size: int; (* *< Size of buf except extra allocated bytes *) mime_type: PAnsiChar; (* *< mime_type, when known. *) end; AVDeviceInfoList = record end; AVDeviceCapabilitiesQuery = record end; AVOutputFormat = record name: PAnsiChar; (* * * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. *) long_name: PAnsiChar; mime_type: PAnsiChar; extensions: PAnsiChar; (* *< comma-separated filename extensions *) (* output support *) audio_codec: AVCodecID; (* *< default audio codec *) video_codec: AVCodecID; (* *< default video codec *) subtitle_codec: AVCodecID; (* *< default subtitle codec *) (* * * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, * AVFMT_TS_NONSTRICT, AVFMT_TS_NEGATIVE *) flags: int; (* * * List of supported codec_id-codec_tag pairs, ordered by "better * choice first". The arrays are all terminated by AV_CODEC_ID_NONE. *) codec_tag: ppAVCodecTag; priv_class: pAVClass; // < AVClass for the private context (* **************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** *) next: pAVOutputFormat; (* * * size of private data so that it can be allocated in the wrapper *) priv_data_size: int; // int (*write_header)(struct AVFormatContext *); write_header: function(p: pAVFormatContext): int; cdecl; (* * * Write a packet. If AVFMT_ALLOW_FLUSH is set in flags, * pkt can be NULL in order to flush data buffered in the muxer. * When flushing, return 0 if there still is more data to flush, * or 1 if everything was flushed and there is no more buffered * data. *) // int (*write_packet)(struct AVFormatContext *, AVPacket *pkt); write_packet: function(fc: pAVFormatContext; pkt: pAVPacket): int; cdecl; // int (*write_trailer)(struct AVFormatContext *); write_trailer: function(p: pAVFormatContext): int; cdecl; (* * * Currently only used to set pixel format if not YUV420P. *) // int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush); interleave_packet: function(p: pAVFormatContext; _out: pAVPacket; _in: pAVPacket; flush: int): int; cdecl; (* * * Test if the given codec can be stored in this container. * * @return 1 if the codec is supported, 0 if it is not. * A negative number if unknown. * MKTAG('A', 'P', 'I', 'C') if the codec is only supported as AV_DISPOSITION_ATTACHED_PIC *) // int (*query_codec)(enum AVCodecID id, int std_compliance); query_codec: function(id: AVCodecID; std_compliance: int): int; cdecl; // void (*get_output_timestamp)(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall); get_output_timestamp: procedure(s: pAVFormatContext; stream: int; var dts: int64_t; var wall: int64_t); cdecl; (* * * Allows sending messages from application to device. *) // int (*control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size); control_message: function(s: pAVFormatContext; _type: int; data: pointer; data_size: size_t): int; cdecl; (* * * Write an uncoded AVFrame. * * See av_write_uncoded_frame() for details. * * The library will free *frame afterwards, but the muxer can prevent it * by setting the pointer to NULL. *) // int (*write_uncoded_frame)(struct AVFormatContext *, int stream_index, AVFrame **frame, unsigned flags); write_uncoded_frame: function(p: pAVFormatContext; stream_index: int; var frame: pAVFrame; flags: unsigned): int; cdecl; (* * * Returns device list with it properties. * @see avdevice_list_devices() for more details. *) // int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); get_device_list: function(s: pAVFormatContext; device_list: pAVDeviceInfoList): int; cdecl; (* * * Initialize device capabilities submodule. * @see avdevice_capabilities_create() for more details. *) // int (*create_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); create_device_capabilities: function(s: pAVFormatContext; caps: pAVDeviceCapabilitiesQuery): int; cdecl; (* * * Free device capabilities submodule. * @see avdevice_capabilities_free() for more details. *) // int (*free_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); free_device_capabilities: function(s: pAVFormatContext; caps: pAVDeviceCapabilitiesQuery): int; cdecl; data_codec: AVCodecID; (* *< default data codec *) (* * * Initialize format. May allocate data here, and set any AVFormatContext or * AVStream parameters that need to be set before packets are sent. * This method must not write output. * * Return 0 if streams were fully configured, 1 if not, negative AVERROR on failure * * Any allocations made here must be freed in deinit(). *) // int (*init)(struct AVFormatContext *); init: function(p: pAVFormatContext): int; cdecl; (* * * Deinitialize format. If present, this is called whenever the muxer is being * destroyed, regardless of whether or not the header has been written. * * If a trailer is being written, this is called after write_trailer(). * * This is called if init() fails as well. *) // void (*deinit)(struct AVFormatContext *); deinit: procedure(p: pAVFormatContext); cdecl; (* * * Set up any necessary bitstream filtering and extract any extra data needed * for the global header. * Return 0 if more packets from this stream must be checked; 1 if not. *) // int (*check_bitstream)(struct AVFormatContext *, const AVPacket *pkt); check_bitstream: function(p: pAVFormatContext; const pkt: pAVPacket): int; cdecl; end; AVStreamParseType = ( // AVSTREAM_PARSE_NONE, AVSTREAM_PARSE_FULL, (* *< full parsing and repack *) AVSTREAM_PARSE_HEADERS, (* *< Only parse headers, do not repack. *) AVSTREAM_PARSE_TIMESTAMPS, (* *< full parsing and interpolation of timestamps for frames not starting on a packet boundary *) AVSTREAM_PARSE_FULL_ONCE, (* *< full parsing and repack of the first frame only, only implemented for H.264 currently *) AVSTREAM_PARSE_FULL_RAW (* *< full parsing and repack with timestamp and position generation by parser for raw this assumes that each packet in the file contains no demuxer level headers and just codec level data, otherwise position generation would fail *) ); pAVIndexEntry = ^AVIndexEntry; AVIndexEntry = record pos: int64_t; timestamp: int64_t; (* *< * Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are available * when seeking to this entry. That means preferable PTS on keyframe based formats. * But demuxers can choose to store a different timestamp, if it is more convenient for the implementation or nothing better * is known *) (* * * Flag is used to indicate which frame should be discarded after decoding. *) // int flags:2; // int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs. 32 bytes due to possible 8-byte alignment). flag_size: int32; min_distance: int; (* *< Minimum distance between this and the previous keyframe, used to avoid unneeded searching. *) end; pAVStreamInternal = ^AVStreamInternal; AVStreamInternal = record end; Tduration_error = array [0 .. 1, 0 .. MAX_STD_TIMEBASES] of Double; pduration_error = ^Tduration_error; pAVStream_info = ^AVStream_info; AVStream_info = record last_dts: int64_t; duration_gcd: int64_t; duration_count: int; rfps_duration_sum: int64_t; duration_error: pduration_error; codec_info_duration: int64_t; codec_info_duration_fields: int64_t; frame_delay_evidence: int; (* * * 0 -> decoder has not been searched for yet. * >0 -> decoder found * <0 -> decoder with codec_id == -found_decoder has not been found *) found_decoder: int; last_duration: int64_t; (* * * Those are used for average framerate estimation. *) fps_first_dts: int64_t; fps_first_dts_idx: int; fps_last_dts: int64_t; fps_last_dts_idx: int; end; Tpts_buffer_int64_t = array [0 .. MAX_REORDER_DELAY] of int64_t; Tpts_reorder_error_count_uint8_t = array [0 .. MAX_REORDER_DELAY] of uint8_t; pAVPacketList = ^AVPacketList; AVPacketList = record pkt: AVPacket; next: pAVPacketList; end; (* * * Stream structure. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVStream) must not be used outside libav*. *) AVStream = record index: int; (* *< stream index in AVFormatContext *) (* * * Format-specific stream ID. * decoding: set by libavformat * encoding: set by the user, replaced by libavformat if left unset *) id: int; {$IFDEF FF_API_LAVF_AVCTX} (* * * @deprecated use the codecpar struct instead *) // attribute_deprecated codec: pAVCodecContext; {$ENDIF} priv_data: pointer; (* * * This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. * * decoding: set by libavformat * encoding: May be set by the caller before avformat_write_header() to * provide a hint to the muxer about the desired timebase. In * avformat_write_header(), the muxer will overwrite this field * with the timebase that will actually be used for the timestamps * written into the file (which may or may not be related to the * user-provided one, depending on the format). *) time_base: AVRational; (* * * Decoding: pts of the first frame of the stream in presentation order, in stream time base. * Only set this if you are absolutely 100% sure that the value you set * it to really is the pts of the first frame. * This may be undefined (AV_NOPTS_VALUE). * @note The ASF header does NOT contain a correct start_time the ASF * demuxer must NOT set this. *) start_time: int64_t; (* * * Decoding: duration of the stream, in stream time base. * If a source file does not specify a duration, but does specify * a bitrate, this value will be estimated from bitrate and file size. * * Encoding: May be set by the caller before avformat_write_header() to * provide a hint to the muxer about the estimated duration. *) duration: int64_t; nb_frames: int64_t; // < number of frames in this stream if known or 0 disposition: int; (* *< AV_DISPOSITION_* bit field *) discard: AVDiscard; // < Selects which packets can be discarded at will and do not need to be demuxed. (* * * sample aspect ratio (0 if unknown) * - encoding: Set by user. * - decoding: Set by libavformat. *) sample_aspect_ratio: AVRational; metadata: pAVDictionary; (* * * Average framerate * * - demuxing: May be set by libavformat when creating the stream or in * avformat_find_stream_info(). * - muxing: May be set by the caller before avformat_write_header(). *) avg_frame_rate: AVRational; (* * * For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet * will contain the attached picture. * * decoding: set by libavformat, must not be modified by the caller. * encoding: unused *) attached_pic: AVPacket; (* * * An array of side data that applies to the whole stream (i.e. the * container does not allow it to change between packets). * * There may be no overlap between the side data in this array and side data * in the packets. I.e. a given side data is either exported by the muxer * (demuxing) / set by the caller (muxing) in this array, then it never * appears in the packets, or the side data is exported / sent through * the packets (always in the first packet where the value becomes known or * changes), then it does not appear in this array. * * - demuxing: Set by libavformat when the stream is created. * - muxing: May be set by the caller before avformat_write_header(). * * Freed by libavformat in avformat_free_context(). * * @see av_format_inject_global_side_data() *) side_data: pAVPacketSideData; (* * * The number of elements in the AVStream.side_data array. *) nb_side_data: int; (* * * Flags for the user to detect events happening on the stream. Flags must * be cleared by the user once the event has been handled. * A combination of AVSTREAM_EVENT_FLAG_*. *) event_flags: int; (* * * Real base framerate of the stream. * This is the lowest framerate with which all timestamps can be * represented accurately (it is the least common multiple of all * framerates in the stream). Note, this value is just a guess! * For example, if the time base is 1/90000 and all frames have either * approximately 3600 or 1800 timer ticks, then r_frame_rate will be 50/1. *) r_frame_rate: AVRational; {$IFDEF FF_API_LAVF_FFSERVER} (* * * String containing pairs of key and values describing recommended encoder configuration. * Pairs are separated by ','. * Keys are separated from values by '='. * * @deprecated unused *) // attribute_deprecated recommended_encoder_configuration: PAnsiChar; {$ENDIF} (* * * Codec parameters associated with this stream. Allocated and freed by * libavformat in avformat_new_stream() and avformat_free_context() * respectively. * * - demuxing: filled by libavformat on stream creation or in * avformat_find_stream_info() * - muxing: filled by the caller before avformat_write_header() *) codecpar: pAVCodecParameters; (* * * Stream information used internally by avformat_find_stream_info() *) info: pAVStream_info; pts_wrap_bits: int; (* *< number of bits in pts (used for wrapping control) *) // Timestamp generation support: (* * * Timestamp corresponding to the last dts sync point. * * Initialized when AVCodecParserContext.dts_sync_point >= 0 and * a DTS is received from the underlying container. Otherwise set to * AV_NOPTS_VALUE by default. *) first_dts: int64_t; cur_dts: int64_t; last_IP_pts: int64_t; last_IP_duration: int; (* * * Number of packets to buffer for codec probing *) probe_packets: int; (* * * Number of frames that have been demuxed during avformat_find_stream_info() *) codec_info_nb_frames: int; (* av_read_frame() support *) need_parsing: AVStreamParseType; parser: pAVCodecParserContext; (* * * last packet in packet_buffer for this stream when muxing. *) last_in_packet_buffer: pAVPacketList; probe_data: AVProbeData; pts_buffer: Tpts_buffer_int64_t; index_entries: pAVIndexEntry; (* *< Only used if the format does not support seeking natively. *) nb_index_entries: int; index_entries_allocated_size: unsigned_int; (* * * Stream Identifier * This is the MPEG-TS stream identifier +1 * 0 means unknown *) stream_identifier: int; (* * Details of the MPEG-TS program which created this stream. *) program_num: int; pmt_version: int; pmt_stream_idx: int; interleaver_chunk_size: int64_t; interleaver_chunk_duration: int64_t; (* * * stream probing state * -1 -> probing finished * 0 -> no probing requested * rest -> perform probing with request_probe being the minimum score to accept. * NOT PART OF PUBLIC API *) request_probe: int; (* * * Indicates that everything up to the next keyframe * should be discarded. *) skip_to_keyframe: int; (* * * Number of samples to skip at the start of the frame decoded from the next packet. *) skip_samples: int; (* * * If not 0, the number of samples that should be skipped from the start of * the stream (the samples are removed from packets with pts==0, which also * assumes negative timestamps do not happen). * Intended for use with formats such as mp3 with ad-hoc gapless audio * support. *) start_skip_samples: int64_t; (* * * If not 0, the first audio sample that should be discarded from the stream. * This is broken by design (needs global sample count), but can't be * avoided for broken by design formats such as mp3 with ad-hoc gapless * audio support. *) first_discard_sample: int64_t; (* * * The sample after last sample that is intended to be discarded after * first_discard_sample. Works on frame boundaries only. Used to prevent * early EOF if the gapless info is broken (considered concatenated mp3s). *) last_discard_sample: int64_t; (* * * Number of internally decoded frames, used internally in libavformat, do not access * its lifetime differs from info which is why it is not in that structure. *) nb_decoded_frames: int; (* * * Timestamp offset added to timestamps before muxing * NOT PART OF PUBLIC API *) mux_ts_offset: int64_t; (* * * Internal data to check for wrapping of the time stamp *) pts_wrap_reference: int64_t; (* * * Options for behavior, when a wrap is detected. * * Defined by AV_PTS_WRAP_ values. * * If correction is enabled, there are two possibilities: * If the first time stamp is near the wrap point, the wrap offset * will be subtracted, which will create negative time stamps. * Otherwise the offset will be added. *) pts_wrap_behavior: int; (* * * Internal data to prevent doing update_initial_durations() twice *) update_initial_durations_done: int; (* * * Internal data to generate dts from pts *) pts_reorder_error: Tpts_buffer_int64_t; pts_reorder_error_count: Tpts_reorder_error_count_uint8_t; (* * * Internal data to analyze DTS and detect faulty mpeg streams *) last_dts_for_order_check: int64_t; dts_ordered: uint8_t; dts_misordered: uint8_t; (* * * Internal data to inject global side data *) inject_global_side_data: int; (* * * display aspect ratio (0 if unknown) * - encoding: unused * - decoding: Set by libavformat to calculate sample_aspect_ratio internally *) display_aspect_ratio: AVRational; (* * * An opaque field for libavformat internal usage. * Must not be accessed in any way by callers. *) internal: pAVStreamInternal; end; (* * * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVProgram) must not be used outside libav*. *) AVProgram = record id: int; flags: int; discard: AVDiscard; // < selects which program to discard and which to feed to the caller stream_index: punsigned_int; nb_stream_indexes: unsigned_int; metadata: pAVDictionary; program_num: int; pmt_pid: int; pcr_pid: int; pmt_version: int; (* **************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** *) start_time: int64_t; end_time: int64_t; pts_wrap_reference: int64_t; // < reference dts for wrap detection pts_wrap_behavior: int; // < behavior on wrap detection end; (* * * @defgroup metadata_api Public Metadata API * @{ * @ingroup libavf * The metadata API allows libavformat to export metadata tags to a client * application when demuxing. Conversely it allows a client application to * set metadata when muxing. * * Metadata is exported or set as pairs of key/value strings in the 'metadata' * fields of the AVFormatContext, AVStream, AVChapter and AVProgram structs * using the @ref lavu_dict "AVDictionary" API. Like all strings in FFmpeg, * metadata is assumed to be UTF-8 encoded Unicode. Note that metadata * exported by demuxers isn't checked to be valid UTF-8 in most cases. * * Important concepts to keep in mind: * - Keys are unique; there can never be 2 tags with the same key. This is * also meant semantically, i.e., a demuxer should not knowingly produce * several keys that are literally different but semantically identical. * E.g., key=Author5, key=Author6. In this example, all authors must be * placed in the same tag. * - Metadata is flat, not hierarchical; there are no subtags. If you * want to store, e.g., the email address of the child of producer Alice * and actor Bob, that could have key=alice_and_bobs_childs_email_address. * - Several modifiers can be applied to the tag name. This is done by * appending a dash character ('-') and the modifier name in the order * they appear in the list below -- e.g. foo-eng-sort, not foo-sort-eng. * - language -- a tag whose value is localized for a particular language * is appended with the ISO 639-2/B 3-letter language code. * For example: Author-ger=Michael, Author-eng=Mike * The original/default language is in the unqualified "Author" tag. * A demuxer should set a default if it sets any translated tag. * - sorting -- a modified version of a tag that should be used for * sorting will have '-sort' appended. E.g. artist="The Beatles", * artist-sort="Beatles, The". * - Some protocols and demuxers support metadata updates. After a successful * call to av_read_packet(), AVFormatContext.event_flags or AVStream.event_flags * will be updated to indicate if metadata changed. In order to detect metadata * changes on a stream, you need to loop through all streams in the AVFormatContext * and check their individual event_flags. * * - Demuxers attempt to export metadata in a generic format, however tags * with no generic equivalents are left as they are stored in the container. * Follows a list of generic tag names: * @verbatim album -- name of the set this work belongs to album_artist -- main creator of the set/album, if different from artist. e.g. "Various Artists" for compilation albums. artist -- main creator of the work comment -- any additional description of the file. composer -- who composed the work, if different from artist. copyright -- name of copyright holder. creation_time-- date when the file was created, preferably in ISO 8601. date -- date when the work was created, preferably in ISO 8601. disc -- number of a subset, e.g. disc in a multi-disc collection. encoder -- name/settings of the software/hardware that produced the file. encoded_by -- person/group who created the file. filename -- original name of the file. genre -- <self-evident>. language -- main language in which the work is performed, preferably in ISO 639-2 format. Multiple languages can be specified by separating them with commas. performer -- artist who performed the work, if different from artist. E.g for "Also sprach Zarathustra", artist would be "Richard Strauss" and performer "London Philharmonic Orchestra". publisher -- name of the label/publisher. service_name -- name of the service in broadcasting (channel name). service_provider -- name of the service provider in broadcasting. title -- name of the work. track -- number of this work in the set, can be in form current/total. variant_bitrate -- the total bitrate of the bitrate variant that the current stream is part of @endverbatim * * Look in the examples section for an application example how to use the Metadata API. * * @} *) (* packet functions *) (* * * Allocate and read the payload of a packet and initialize its * fields with default values. * * @param s associated IO context * @param pkt packet * @param size desired payload size * @return >0 (read size) if OK, AVERROR_xxx otherwise *) // int av_get_packet(AVIOContext *s, AVPacket *pkt, int size); function av_get_packet(s: pAVIOContext; pkt: pAVPacket; size: int): int; cdecl; external avformat_dll; (* * * Read data and append it to the current content of the AVPacket. * If pkt->size is 0 this is identical to av_get_packet. * Note that this uses av_grow_packet and thus involves a realloc * which is inefficient. Thus this function should only be used * when there is no reasonable way to know (an upper bound of) * the final size. * * @param s associated IO context * @param pkt packet * @param size amount of data to read * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data * will not be lost even if an error occurs. *) // int av_append_packet(AVIOContext *s, AVPacket *pkt, int size); function av_append_packet(s: pAVIOContext; pkt: pAVPacket; size: int): int; cdecl; external avformat_dll; (* *********************************************** *) {$IFDEF FF_API_FORMAT_GET_SET} (* * * Accessors for some AVStream fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. *) // attribute_deprecated // AVRational av_stream_get_r_frame_rate(const AVStream *s); function av_stream_get_r_frame_rate(const s: pAVStream): AVRational; cdecl; external avformat_dll; // attribute_deprecated // void av_stream_set_r_frame_rate(AVStream *s, AVRational r); procedure av_stream_set_r_frame_rate(s: pAVStream; r: AVRational); cdecl; external avformat_dll; {$IFDEF FF_API_LAVF_FFSERVER} // attribute_deprecated // char* av_stream_get_recommended_encoder_configuration(const AVStream *s); function av_stream_get_recommended_encoder_configuration(const s: pAVStream): PAnsiChar; cdecl; external avformat_dll; // attribute_deprecated // void av_stream_set_recommended_encoder_configuration(AVStream *s, char *configuration); procedure av_stream_set_recommended_encoder_configuration(s: pAVStream; configuration: PAnsiChar); cdecl; external avformat_dll; {$ENDIF} {$ENDIF} // struct AVCodecParserContext *av_stream_get_parser(const AVStream *s); function av_stream_get_parser(const s: pAVStream): pAVCodecParserContext; cdecl; external avformat_dll; (* * * Returns the pts of the last muxed packet + its duration * * the retuned value is undefined when used with a demuxer. *) // int64_t av_stream_get_end_pts(const AVStream *st); function av_stream_get_end_pts(const st: pAVStream): int64_t; cdecl; external avformat_dll; {$IFDEF FF_API_FORMAT_GET_SET} (* * * Accessors for some AVFormatContext fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. *) // attribute_deprecated // int av_format_get_probe_score(const AVFormatContext *s); function av_format_get_probe_score(const s: pAVFormatContext): int; cdecl; external avformat_dll; // attribute_deprecated // AVCodec * av_format_get_video_codec(const AVFormatContext *s); function av_format_get_video_codec(const s: pAVFormatContext): pAVCodec; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_video_codec(AVFormatContext *s, AVCodec *c); procedure av_format_set_video_codec(s: pAVFormatContext; c: pAVCodec); cdecl; external avformat_dll; // attribute_deprecated // AVCodec * av_format_get_audio_codec(const AVFormatContext *s); function av_format_get_audio_codec(const s: pAVFormatContext): pAVCodec; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_audio_codec(AVFormatContext *s, AVCodec *c); procedure av_format_set_audio_codec(s: pAVFormatContext; c: pAVCodec); cdecl; external avformat_dll; // attribute_deprecated // AVCodec *av_format_get_subtitle_codec(const AVFormatContext *s); function av_format_get_subtitle_codec(const s: pAVFormatContext): pAVCodec; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_subtitle_codec(AVFormatContext *s, AVCodec *c); procedure av_format_set_subtitle_codec(s: pAVFormatContext; c: pAVCodec); cdecl; external avformat_dll; // attribute_deprecated // AVCodec *av_format_get_data_codec(const AVFormatContext *s); function av_format_get_data_codec(const s: pAVFormatContext): pAVCodec; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_data_codec(AVFormatContext *s, AVCodec *c); procedure av_format_set_data_codec(s: pAVFormatContext; c: pAVCodec); cdecl; external avformat_dll; // attribute_deprecated // int av_format_get_metadata_header_padding(const AVFormatContext *s); function av_format_get_metadata_header_padding(const s: pAVFormatContext): int; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_metadata_header_padding(AVFormatContext *s, int c); procedure av_format_set_metadata_header_padding(s: pAVFormatContext; c: int); cdecl; external avformat_dll; // attribute_deprecated // void *av_format_get_opaque(const AVFormatContext *s); function av_format_get_opaque(const s: pAVFormatContext): pointer; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_opaque(AVFormatContext *s, void *opaque); procedure av_format_set_opaque(s: pAVFormatContext; opaque: pointer); cdecl; external avformat_dll; // attribute_deprecated // av_format_control_message av_format_get_control_message_cb(const AVFormatContext *s); function av_format_get_control_message_cb(const s: pAVFormatContext): Tav_format_control_message; cdecl; external avformat_dll; // attribute_deprecated // void av_format_set_control_message_cb(AVFormatContext *s, av_format_control_message callback); procedure av_format_set_control_message_cb(s: pAVFormatContext; callback: Tav_format_control_message); cdecl; external avformat_dll; {$IFDEF FF_API_OLD_OPEN_CALLBACKS} // attribute_deprecated AVOpenCallback av_format_get_open_cb(const AVFormatContext *s); function av_format_get_open_cb(const s: pAVFormatContext): TAVOpenCallback; cdecl; external avformat_dll; // attribute_deprecated void av_format_set_open_cb(AVFormatContext *s, AVOpenCallback callback); procedure av_format_set_open_cb(s: pAVFormatContext; callback: TAVOpenCallback); cdecl; external avformat_dll; {$ENDIF} {$ENDIF} (* * * This function will cause global side data to be injected in the next packet * of each stream as well as after any subsequent seek. *) // void av_format_inject_global_side_data(AVFormatContext *s); procedure av_format_inject_global_side_data(s: pAVFormatContext); cdecl; external avformat_dll; (* * * Returns the method used to set ctx->duration. * * @return AVFMT_DURATION_FROM_PTS, AVFMT_DURATION_FROM_STREAM, or AVFMT_DURATION_FROM_BITRATE. *) // enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method(const AVFormatContext* ctx); function av_fmt_ctx_get_duration_estimation_method(const ctx: pAVFormatContext): AVDurationEstimationMethod; cdecl; external avformat_dll; (* * * @defgroup lavf_core Core functions * @ingroup libavf * * Functions for querying libavformat capabilities, allocating core structures, * etc. * @{ *) (* * * Return the LIBAVFORMAT_VERSION_INT constant. *) // unsigned avformat_version(void); function avformat_version(): unsigned; cdecl; external avformat_dll; (* * * Return the libavformat build-time configuration. *) // const char *avformat_configuration(void); function avformat_configuration(): PAnsiChar; cdecl; external avformat_dll; (* * * Return the libavformat license. *) // const char *avformat_license(void); function avformat_license(): PAnsiChar; cdecl; external avformat_dll; {$IFDEF FF_API_NEXT} (* * * Initialize libavformat and register all the muxers, demuxers and * protocols. If you do not call this function, then you can select * exactly which formats you want to support. * * @see av_register_input_format() * @see av_register_output_format() *) // attribute_deprecated void av_register_all(void); procedure av_register_all(); cdecl; external avformat_dll; // attribute_deprecated void av_register_input_format(AVInputFormat *format); procedure av_register_input_format(format: pAVInputFormat); cdecl; external avformat_dll; // attribute_deprecated void av_register_output_format(AVOutputFormat *format); procedure av_register_output_format(format: pAVOutputFormat); cdecl; external avformat_dll; {$ENDIF} (* * * Do global initialization of network libraries. This is optional, * and not recommended anymore. * * This functions only exists to work around thread-safety issues * with older GnuTLS or OpenSSL libraries. If libavformat is linked * to newer versions of those libraries, or if you do not use them, * calling this function is unnecessary. Otherwise, you need to call * this function before any other threads using them are started. * * This function will be deprecated once support for older GnuTLS and * OpenSSL libraries is removed, and this function has no purpose * anymore. *) // int avformat_network_init(void); function avformat_network_init(): int; cdecl; external avformat_dll; (* * * Undo the initialization done by avformat_network_init. Call it only * once for each time you called avformat_network_init. *) // int avformat_network_deinit(void); function avformat_network_deinit(): int; cdecl; external avformat_dll; {$IFDEF FF_API_NEXT} (* * * If f is NULL, returns the first registered input format, * if f is non-NULL, returns the next registered input format after f * or NULL if f is the last one. *) // attribute_deprecated // AVInputFormat *av_iformat_next(const AVInputFormat *f); function av_iformat_next(const f: pAVInputFormat): pAVInputFormat; cdecl; external avformat_dll; (* * * If f is NULL, returns the first registered output format, * if f is non-NULL, returns the next registered output format after f * or NULL if f is the last one. *) // attribute_deprecated // AVOutputFormat *av_oformat_next(const AVOutputFormat *f); function av_oformat_next(const f: pAVOutputFormat): pAVOutputFormat; cdecl; external avformat_dll; {$ENDIF} (* * * Iterate over all registered muxers. * * @param opaque a pointer where libavformat will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered muxer or NULL when the iteration is * finished *) // const AVOutputFormat *av_muxer_iterate(void **opaque); function av_muxer_iterate(var opaque: pointer): pAVOutputFormat; cdecl; external avformat_dll; (* * * Iterate over all registered demuxers. * * @param opaque a pointer where libavformat will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered demuxer or NULL when the iteration is * finished *) // const AVInputFormat *av_demuxer_iterate(void **opaque); function av_demuxer_iterate(var opaque: pointer): pAVInputFormat; cdecl; external avformat_dll; (* * * Allocate an AVFormatContext. * avformat_free_context() can be used to free the context and everything * allocated by the framework within it. *) // AVFormatContext *avformat_alloc_context(void); function avformat_alloc_context(): pAVFormatContext; cdecl; external avformat_dll; (* * * Free an AVFormatContext and all its streams. * @param s context to free *) // void avformat_free_context(AVFormatContext *s); procedure avformat_free_context(s: pAVFormatContext); cdecl; external avformat_dll; (* * * Get the AVClass for AVFormatContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). *) // const AVClass *avformat_get_class(void); function avformat_get_class(): pAVClass; cdecl; external avformat_dll; (* * * Add a new stream to a media file. * * When demuxing, it is called by the demuxer in read_header(). If the * flag AVFMTCTX_NOHEADER is set in s.ctx_flags, then it may also * be called in read_packet(). * * When muxing, should be called by the user before avformat_write_header(). * * User is required to call avcodec_close() and avformat_free_context() to * clean up the allocation by avformat_new_stream(). * * @param s media file handle * @param c If non-NULL, the AVCodecContext corresponding to the new stream * will be initialized to use this codec. This is needed for e.g. codec-specific * defaults to be set, so codec should be provided if it is known. * * @return newly created stream or NULL on error. *) // AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c); function avformat_new_stream(s: pAVFormatContext; const c: pAVCodec): pAVStream; cdecl; external avformat_dll; (* * * Wrap an existing array as stream side data. * * @param st stream * @param type side information type * @param data the side data array. It must be allocated with the av_malloc() * family of functions. The ownership of the data is transferred to * st. * @param size side information size * @return zero on success, a negative AVERROR code on failure. On failure, * the stream is unchanged and the data remains owned by the caller. *) // int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type, // uint8_t *data, size_t size); function av_stream_add_side_data(st: pAVStream; _type: AVPacketSideDataType; data: puint8_t; size: size_t): int; cdecl; external avformat_dll; (* * * Allocate new information from stream. * * @param stream stream * @param type desired side information type * @param size side information size * @return pointer to fresh allocated data or NULL otherwise *) // uint8_t *av_stream_new_side_data(AVStream *stream, // enum AVPacketSideDataType type, int size); function av_stream_new_side_data(stream: pAVStream; _type: AVPacketSideDataType; size: int): puint8_t; cdecl; external avformat_dll; (* * * Get side information from stream. * * @param stream stream * @param type desired side information type * @param size pointer for side information size to store (optional) * @return pointer to data if present or NULL otherwise *) // uint8_t *av_stream_get_side_data(const AVStream *stream, // enum AVPacketSideDataType type, int *size); function av_stream_get_side_data(const stream: pAVStream; _type: AVPacketSideDataType; var size: int): puint8_t; cdecl; external avformat_dll; // AVProgram *av_new_program(AVFormatContext *s, int id); function av_new_program(s: pAVFormatContext; id: int): pAVProgram; cdecl; external avformat_dll; (* * * Allocate an AVFormatContext for an output format. * avformat_free_context() can be used to free the context and * everything allocated by the framework within it. * * @param *ctx is set to the created format context, or to NULL in * case of failure * @param oformat format to use for allocating the context, if NULL * format_name and filename are used instead * @param format_name the name of output format to use for allocating the * context, if NULL filename is used instead * @param filename the name of the filename to use for allocating the * context, may be NULL * @return >= 0 in case of success, a negative AVERROR code in case of * failure *) // int avformat_alloc_output_context2(AVFormatContext **ctx, AVOutputFormat *oformat, // const char *format_name, const char *filename); function avformat_alloc_output_context2(var ctx: pAVFormatContext; oformat: pAVOutputFormat; const format_name: PAnsiChar; const filename: PAnsiChar): int; cdecl; external avformat_dll; (* * * @addtogroup lavf_decoding * @{ *) (* * * Find AVInputFormat based on the short name of the input format. *) // AVInputFormat *av_find_input_format(const char *short_name); function av_find_input_format(const short_name: PAnsiChar): pAVInputFormat; cdecl; external avformat_dll; (* * * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. *) // AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened); function av_probe_input_format(pd: pAVProbeData; is_opened: int): pAVInputFormat; cdecl; external avformat_dll; (* * * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_max A probe score larger that this is required to accept a * detection, the variable is set to the actual detection * score afterwards. * If the score is <= AVPROBE_SCORE_MAX / 4 it is recommended * to retry with a larger probe buffer. *) // AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max); function av_probe_input_format2(pd: pAVProbeData; is_opened: int; var score_max: int): pAVInputFormat; cdecl; external avformat_dll; (* * * Guess the file format. * * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_ret The score of the best detection. *) // AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret); function av_probe_input_format3(pd: pAVProbeData; is_opened: int; var score_ret: int): pAVInputFormat; cdecl; external avformat_dll; (* * * Probe a bytestream to determine the input format. Each time a probe returns * with a score that is too low, the probe buffer size is increased and another * attempt is made. When the maximum probe size is reached, the input format * with the highest score is returned. * * @param pb the bytestream to probe * @param fmt the input format is put here * @param url the url of the stream * @param logctx the log context * @param offset the offset within the bytestream to probe from * @param max_probe_size the maximum probe buffer size (zero for default) * @return the score in case of success, a negative value corresponding to an * the maximal score is AVPROBE_SCORE_MAX * AVERROR code otherwise *) // int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt, // const char *url, void *logctx, // unsigned int offset, unsigned int max_probe_size); function av_probe_input_buffer2(pb: pAVIOContext; var fmt: pAVInputFormat; const url: PAnsiChar; logctx: pointer; offset: unsigned_int; max_probe_size: unsigned_int): int; cdecl; external avformat_dll; (* * * Like av_probe_input_buffer2() but returns 0 on success *) // int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt, // const char *url, void *logctx, // unsigned int offset, unsigned int max_probe_size); function av_probe_input_buffer(pb: pAVIOContext; var fmt: pAVInputFormat; const url: PAnsiChar; logctx: pointer; offset: unsigned_int; max_probe_size: unsigned_int): int; cdecl; external avformat_dll; (* * * Open an input stream and read the header. The codecs are not opened. * The stream must be closed with avformat_close_input(). * * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context). * May be a pointer to NULL, in which case an AVFormatContext is allocated by this * function and written into ps. * Note that a user-supplied AVFormatContext will be freed on failure. * @param url URL of the stream to open. * @param fmt If non-NULL, this parameter forces a specific input format. * Otherwise the format is autodetected. * @param options A dictionary filled with AVFormatContext and demuxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return 0 on success, a negative AVERROR on failure. * * @note If you want to use custom IO, preallocate the format context and set its pb field. *) // int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options); function avformat_open_input(var ps: pAVFormatContext; const url: PAnsiChar; fmt: pAVInputFormat; options: ppAVDictionary): int; cdecl; external avformat_dll; // attribute_deprecated // int av_demuxer_open(AVFormatContext *ic); function av_demuxer_open(ic: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Read packets of a media file to get stream information. This * is useful for file formats with no headers such as MPEG. This * function also computes the real framerate in case of MPEG-2 repeat * frame mode. * The logical file position is not changed by this function; * examined packets may be buffered for later processing. * * @param ic media file handle * @param options If non-NULL, an ic.nb_streams long array of pointers to * dictionaries, where i-th member contains options for * codec corresponding to i-th stream. * On return each dictionary will be filled with options that were not found. * @return >=0 if OK, AVERROR_xxx on error * * @note this function isn't guaranteed to open all the codecs, so * options being non-empty at return is a perfectly normal behavior. * * @todo Let the user decide somehow what information is needed so that * we do not waste time getting stuff the user does not need. *) // int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options); function avformat_find_stream_info(ic: pAVFormatContext; options: ppAVDictionary): int; cdecl; external avformat_dll; (* * * Find the programs which belong to a given stream. * * @param ic media file handle * @param last the last found program, the search will start after this * program, or from the beginning if it is NULL * @param s stream index * @return the next program which belongs to s, NULL if no program is found or * the last program is not among the programs of ic. *) // AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s); function av_find_program_from_stream(ic: pAVFormatContext; last: pAVProgram; s: int): pAVProgram; cdecl; external avformat_dll; // void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx); procedure av_program_add_stream_index(ac: pAVFormatContext; progid: int; idx: unsigned_int); cdecl; external avformat_dll; (* * * Find the "best" stream in the file. * The best stream is determined according to various heuristics as the most * likely to be what the user expects. * If the decoder parameter is non-NULL, av_find_best_stream will find the * default decoder for the stream's codec; streams for which no decoder can * be found are ignored. * * @param ic media file handle * @param type stream type: video, audio, subtitles, etc. * @param wanted_stream_nb user-requested stream number, * or -1 for automatic selection * @param related_stream try to find a stream related (eg. in the same * program) to this one, or -1 if none * @param decoder_ret if non-NULL, returns the decoder for the * selected stream * @param flags flags; none are currently defined * @return the non-negative stream number in case of success, * AVERROR_STREAM_NOT_FOUND if no stream with the requested type * could be found, * AVERROR_DECODER_NOT_FOUND if streams were found but no decoder * @note If av_find_best_stream returns successfully and decoder_ret is not * NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec. *) // int av_find_best_stream(AVFormatContext *ic, // enum AVMediaType type, // int wanted_stream_nb, // int related_stream, // AVCodec **decoder_ret, // int flags); function av_find_best_stream(ic: pAVFormatContext; _type: AVMediaType; wanted_stream_nb: int; related_stream: int; decoder_ret: ppAVCodec; flags: int): int; cdecl; external avformat_dll; (* * * Return the next frame of a stream. * This function returns what is stored in the file, and does not validate * that what is there are valid frames for the decoder. It will split what is * stored in the file into frames and return one for each call. It will not * omit invalid data between valid frames so as to give the decoder the maximum * information possible for decoding. * * If pkt->buf is NULL, then the packet is valid until the next * av_read_frame() or until avformat_close_input(). Otherwise the packet * is valid indefinitely. In both cases the packet must be freed with * av_packet_unref when it is no longer needed. For video, the packet contains * exactly one frame. For audio, it contains an integer number of frames if each * frame has a known fixed size (e.g. PCM or ADPCM data). If the audio frames * have a variable size (e.g. MPEG audio), then it contains one frame. * * pkt->pts, pkt->dts and pkt->duration are always set to correct * values in AVStream.time_base units (and guessed if the format cannot * provide them). pkt->pts can be AV_NOPTS_VALUE if the video format * has B-frames, so it is better to rely on pkt->dts if you do not * decompress the payload. * * @return 0 if OK, < 0 on error or end of file *) // int av_read_frame(AVFormatContext *s, AVPacket *pkt); function av_read_frame(s: pAVFormatContext; pkt: pAVPacket): int; cdecl; external avformat_dll; (* * * Seek to the keyframe at timestamp. * 'timestamp' in 'stream_index'. * * @param s media file handle * @param stream_index If stream_index is (-1), a default * stream is selected, and timestamp is automatically converted * from AV_TIME_BASE units to the stream specific time_base. * @param timestamp Timestamp in AVStream.time_base units * or, if no stream is specified, in AV_TIME_BASE units. * @param flags flags which select direction and seeking mode * @return >= 0 on success *) // int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags); function av_seek_frame(s: pAVFormatContext; stream_index: int; timestamp: int64_t; flags: int): int; cdecl; external avformat_dll; (* * * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. * * If flags contain AVSEEK_FLAG_BYTE, then all timestamps are in bytes and * are the file position (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_FRAME, then all timestamps are in frames * in the stream with stream_index (this may not be supported by all demuxers). * Otherwise all timestamps are in units of the stream selected by stream_index * or if stream_index is -1, in AV_TIME_BASE units. * If flags contain AVSEEK_FLAG_ANY, then non-keyframes are treated as * keyframes (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_BACKWARD, it is ignored. * * @param s media file handle * @param stream_index index of the stream which is used as time base reference * @param min_ts smallest acceptable timestamp * @param ts target timestamp * @param max_ts largest acceptable timestamp * @param flags flags * @return >=0 on success, error code otherwise * * @note This is part of the new seek API which is still under construction. * Thus do not use this yet. It may change at any time, do not expect * ABI compatibility yet! *) // int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); function avformat_seek_file(s: pAVFormatContext; stream_index: int; min_ts: int64_t; ts: int64_t; max_ts: int64_t; flags: int): int; cdecl; external avformat_dll; (* * * Discard all internally buffered data. This can be useful when dealing with * discontinuities in the byte stream. Generally works only with formats that * can resync. This includes headerless formats like MPEG-TS/TS but should also * work with NUT, Ogg and in a limited way AVI for example. * * The set of streams, the detected duration, stream parameters and codecs do * not change when calling this function. If you want a complete reset, it's * better to open a new AVFormatContext. * * This does not flush the AVIOContext (s->pb). If necessary, call * avio_flush(s->pb) before calling this function. * * @param s media file handle * @return >=0 on success, error code otherwise *) // int avformat_flush(AVFormatContext *s); function avformat_flush(s: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Start playing a network-based stream (e.g. RTSP stream) at the * current position. *) // int av_read_play(AVFormatContext *s); function av_read_play(s: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Pause a network-based stream (e.g. RTSP stream). * * Use av_read_play() to resume it. *) // int av_read_pause(AVFormatContext *s); function av_read_pause(s: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Close an opened input AVFormatContext. Free it and all its contents * and set *s to NULL. *) // void avformat_close_input(AVFormatContext **s); procedure avformat_close_input(var s: pAVFormatContext); cdecl; external avformat_dll; (* * * @} *) const AVSEEK_FLAG_BACKWARD = 1; // < seek backward AVSEEK_FLAG_BYTE = 2; // < seeking based on position in bytes AVSEEK_FLAG_ANY = 4; // < seek to any frame, even non-keyframes AVSEEK_FLAG_FRAME = 8; // < seeking based on frame number (* * * @addtogroup lavf_encoding * @{ *) AVSTREAM_INIT_IN_WRITE_HEADER = 0; // < stream parameters initialized in avformat_write_header AVSTREAM_INIT_IN_INIT_OUTPUT = 1; // < stream parameters initialized in avformat_init_output (* * * Allocate the stream private data and write the stream header to * an output media file. * * @param s Media file handle, must be allocated with avformat_alloc_context(). * Its oformat field must be set to the desired output format; * Its pb field must be set to an already opened AVIOContext. * @param options An AVDictionary filled with AVFormatContext and muxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return AVSTREAM_INIT_IN_WRITE_HEADER on success if the codec had not already been fully initialized in avformat_init, * AVSTREAM_INIT_IN_INIT_OUTPUT on success if the codec had already been fully initialized in avformat_init, * negative AVERROR on failure. * * @see av_opt_find, av_dict_set, avio_open, av_oformat_next, avformat_init_output. *) // av_warn_unused_result // int avformat_write_header(AVFormatContext *s, AVDictionary **options); function avformat_write_header(s: pAVFormatContext; options: ppAVDictionary): int; cdecl; external avformat_dll; (* * * Allocate the stream private data and initialize the codec, but do not write the header. * May optionally be used before avformat_write_header to initialize stream parameters * before actually writing the header. * If using this function, do not pass the same options to avformat_write_header. * * @param s Media file handle, must be allocated with avformat_alloc_context(). * Its oformat field must be set to the desired output format; * Its pb field must be set to an already opened AVIOContext. * @param options An AVDictionary filled with AVFormatContext and muxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return AVSTREAM_INIT_IN_WRITE_HEADER on success if the codec requires avformat_write_header to fully initialize, * AVSTREAM_INIT_IN_INIT_OUTPUT on success if the codec has been fully initialized, * negative AVERROR on failure. * * @see av_opt_find, av_dict_set, avio_open, av_oformat_next, avformat_write_header. *) // av_warn_unused_result // int avformat_init_output(AVFormatContext *s, AVDictionary **options); function avformat_init_output(s: pAVFormatContext; var options: pAVDictionary): int; cdecl; external avformat_dll; (* * * Write a packet to an output media file. * * This function passes the packet directly to the muxer, without any buffering * or reordering. The caller is responsible for correctly interleaving the * packets if the format requires it. Callers that want libavformat to handle * the interleaving should call av_interleaved_write_frame() instead of this * function. * * @param s media file handle * @param pkt The packet containing the data to be written. Note that unlike * av_interleaved_write_frame(), this function does not take * ownership of the packet passed to it (though some muxers may make * an internal reference to the input packet). * <br> * This parameter can be NULL (at any time, not just at the end), in * order to immediately flush data buffered within the muxer, for * muxers that buffer up data internally before writing it to the * output. * <br> * Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". * <br> * The timestamps (@ref AVPacket.pts "pts", @ref AVPacket.dts "dts") * must be set to correct values in the stream's timebase (unless the * output format is flagged with the AVFMT_NOTIMESTAMPS flag, then * they can be set to AV_NOPTS_VALUE). * The dts for subsequent packets passed to this function must be strictly * increasing when compared in their respective timebases (unless the * output format is flagged with the AVFMT_TS_NONSTRICT, then they * merely have to be nondecreasing). @ref AVPacket.duration * "duration") should also be set if known. * @return < 0 on error, = 0 if OK, 1 if flushed and there is no more data to flush * * @see av_interleaved_write_frame() *) // int av_write_frame(AVFormatContext *s, AVPacket *pkt); function av_write_frame(s: pAVFormatContext; pkt: pAVPacket): int; cdecl; external avformat_dll; (* * * Write a packet to an output media file ensuring correct interleaving. * * This function will buffer the packets internally as needed to make sure the * packets in the output file are properly interleaved in the order of * increasing dts. Callers doing their own interleaving should call * av_write_frame() instead of this function. * * Using this function instead of av_write_frame() can give muxers advance * knowledge of future packets, improving e.g. the behaviour of the mp4 * muxer for VFR content in fragmenting mode. * * @param s media file handle * @param pkt The packet containing the data to be written. * <br> * If the packet is reference-counted, this function will take * ownership of this reference and unreference it later when it sees * fit. * The caller must not access the data through this reference after * this function returns. If the packet is not reference-counted, * libavformat will make a copy. * <br> * This parameter can be NULL (at any time, not just at the end), to * flush the interleaving queues. * <br> * Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". * <br> * The timestamps (@ref AVPacket.pts "pts", @ref AVPacket.dts "dts") * must be set to correct values in the stream's timebase (unless the * output format is flagged with the AVFMT_NOTIMESTAMPS flag, then * they can be set to AV_NOPTS_VALUE). * The dts for subsequent packets in one stream must be strictly * increasing (unless the output format is flagged with the * AVFMT_TS_NONSTRICT, then they merely have to be nondecreasing). * @ref AVPacket.duration "duration") should also be set if known. * * @return 0 on success, a negative AVERROR on error. Libavformat will always * take care of freeing the packet, even if this function fails. * * @see av_write_frame(), AVFormatContext.max_interleave_delta *) // int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt); function av_interleaved_write_frame(s: pAVFormatContext; pkt: pAVPacket): int; cdecl; external avformat_dll; (* * * Write an uncoded frame to an output media file. * * The frame must be correctly interleaved according to the container * specification; if not, then av_interleaved_write_frame() must be used. * * See av_interleaved_write_frame() for details. *) // int av_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); function av_write_uncoded_frame(s: pAVFormatContext; stream_index: int; frame: pAVFrame): int; cdecl; external avformat_dll; (* * * Write an uncoded frame to an output media file. * * If the muxer supports it, this function makes it possible to write an AVFrame * structure directly, without encoding it into a packet. * It is mostly useful for devices and similar special muxers that use raw * video or PCM data and will not serialize it into a byte stream. * * To test whether it is possible to use it with a given muxer and stream, * use av_write_uncoded_frame_query(). * * The caller gives up ownership of the frame and must not access it * afterwards. * * @return >=0 for success, a negative code on error *) // int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); function av_interleaved_write_uncoded_frame(s: pAVFormatContext; stream_index: int; frame: pAVFrame): int; cdecl; external avformat_dll; (* * * Test whether a muxer supports uncoded frame. * * @return >=0 if an uncoded frame can be written to that muxer and stream, * <0 if not *) // int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index); function av_write_uncoded_frame_query(s: pAVFormatContext; stream_index: int): int; cdecl; external avformat_dll; (* * * Write the stream trailer to an output media file and free the * file private data. * * May only be called after a successful call to avformat_write_header. * * @param s media file handle * @return 0 if OK, AVERROR_xxx on error *) // int av_write_trailer(AVFormatContext *s); function av_write_trailer(s: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Return the output format in the list of registered output formats * which best matches the provided parameters, or return NULL if * there is no match. * * @param short_name if non-NULL checks if short_name matches with the * names of the registered formats * @param filename if non-NULL checks if filename terminates with the * extensions of the registered formats * @param mime_type if non-NULL checks if mime_type matches with the * MIME type of the registered formats *) // AVOutputFormat *av_guess_format(const char *short_name, // const char *filename, // const char *mime_type); function av_guess_format(const short_name: PAnsiChar; const filename: PAnsiChar; const mime_type: PAnsiChar): pAVOutputFormat; cdecl; external avformat_dll; (* * * Guess the codec ID based upon muxer and filename. *) // enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name, // const char *filename, const char *mime_type, // enum AVMediaType type); function av_guess_codec(fmt: pAVOutputFormat; const short_name: PAnsiChar; const filename: PAnsiChar; const mime_type: PAnsiChar; _type: AVMediaType) : AVCodecID; cdecl; external avformat_dll; (* * * Get timing information for the data currently output. * The exact meaning of "currently output" depends on the format. * It is mostly relevant for devices that have an internal buffer and/or * work in real time. * @param s media file handle * @param stream stream in the media file * @param[out] dts DTS of the last packet output for the stream, in stream * time_base units * @param[out] wall absolute time when that packet whas output, * in microsecond * @return 0 if OK, AVERROR(ENOSYS) if the format does not support it * Note: some formats or devices may not allow to measure dts and wall * atomically. *) // int av_get_output_timestamp(struct AVFormatContext *s, int stream, // int64_t *dts, int64_t *wall); function av_get_output_timestamp(s: pAVFormatContext; stream: int; var dts: int64_t; var wall: int64_t): int; cdecl; external avformat_dll; (* * * @} *) (* * * @defgroup lavf_misc Utility functions * @ingroup libavf * @{ * * Miscellaneous utility functions related to both muxing and demuxing * (or neither). *) (* * * Send a nice hexadecimal dump of a buffer to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param buf buffer * @param size buffer size * * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2 *) // void av_hex_dump(FILE *f, const uint8_t *buf, int size); procedure av_hex_dump(f: pFILE; const buf: puint8_t; size: int); cdecl; external avformat_dll; (* * * Send a nice hexadecimal dump of a buffer to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param buf buffer * @param size buffer size * * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2 *) // void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size); procedure av_hex_dump_log(avcl: pointer; level: int; const buf: puint8_t; size: int); cdecl; external avformat_dll; (* * * Send a nice dump of a packet to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to *) // void av_pkt_dump2(FILE *f, const AVPacket *pkt, int dump_payload, const AVStream *st); procedure av_pkt_dump2(f: pFILE; const pkt: pAVPacket; dump_payload: int; const st: pAVStream); cdecl; external avformat_dll; (* * * Send a nice dump of a packet to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to *) // void av_pkt_dump_log2(void *avcl, int level, const AVPacket *pkt, int dump_payload, // const AVStream *st); procedure av_pkt_dump_log2(avcl: pointer; level: int; const pkt: pAVPacket; dump_payload: int; const st: pAVStream); cdecl; external avformat_dll; (* * * Get the AVCodecID for the given codec tag tag. * If no codec id is found returns AV_CODEC_ID_NONE. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param tag codec tag to match to a codec ID *) // enum AVCodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag); function av_codec_get_id(const tags: ppAVCodecTag; tag: unsigned_int): AVCodecID; cdecl; external avformat_dll; (* * * Get the codec tag for the given codec id id. * If no codec tag is found returns 0. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec ID to match to a codec tag *) // unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum AVCodecID id); function av_codec_get_tag(const tags: ppAVCodecTag; id: AVCodecID): unsigned_int; cdecl; external avformat_dll; (* * * Get the codec tag for the given codec id. * * @param tags list of supported codec_id - codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec id that should be searched for in the list * @param tag A pointer to the found tag * @return 0 if id was not found in tags, > 0 if it was found *) // int av_codec_get_tag2(const struct AVCodecTag * const *tags, enum AVCodecID id, // unsigned int *tag); function av_codec_get_tag2(const tags: ppAVCodecTag; id: AVCodecID; tag: punsigned_int): int; cdecl; external avformat_dll; // int av_find_default_stream_index(AVFormatContext *s); function av_find_default_stream_index(s: pAVFormatContext): int; cdecl; external avformat_dll; (* * * Get the index for a specific timestamp. * * @param st stream that the timestamp belongs to * @param timestamp timestamp to retrieve the index for * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond * to the timestamp which is <= the requested one, if backward * is 0, then it will be >= * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise * @return < 0 if no such timestamp could be found *) // int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags); function av_index_search_timestamp(st: pAVStream; timestamp: int64_t; flags: int): int; cdecl; external avformat_dll; (* * * Add an index entry into a sorted list. Update the entry if the list * already contains it. * * @param timestamp timestamp in the time base of the given stream *) // int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, // int size, int distance, int flags); function av_add_index_entry(st: pAVStream; pos: int64_t; timestamp: int64_t; size: int; distance: int; flags: int): int; cdecl; external avformat_dll; (* * * Split a URL string into components. * * The pointers to buffers for storing individual components may be null, * in order to ignore that component. Buffers for components not found are * set to empty strings. If the port is not found, it is set to a negative * value. * * @param proto the buffer for the protocol * @param proto_size the size of the proto buffer * @param authorization the buffer for the authorization * @param authorization_size the size of the authorization buffer * @param hostname the buffer for the host name * @param hostname_size the size of the hostname buffer * @param port_ptr a pointer to store the port number in * @param path the buffer for the path * @param path_size the size of the path buffer * @param url the URL to split *) // void av_url_split(char *proto, int proto_size, // char *authorization, int authorization_size, // char *hostname, int hostname_size, // int *port_ptr, // char *path, int path_size, // const char *url); procedure av_url_split(proto: PAnsiChar; proto_size: int; authorization: PAnsiChar; authorization_size: int; hostname: PAnsiChar; hostname_size: int; var port_ptr: int; path: PAnsiChar; path_size: int; const url: PAnsiChar); cdecl; external avformat_dll; (* * * Print detailed information about the input or output format, such as * duration, bitrate, streams, container, programs, metadata, side data, * codec and time base. * * @param ic the context to analyze * @param index index of the stream to dump information about * @param url the URL to print, such as source or destination file * @param is_output Select whether the specified context is an input(0) or output(1) *) // void av_dump_format(AVFormatContext *ic, // int index, // const char *url, // int is_output); procedure av_dump_format(ic: pAVFormatContext; index: int; const url: PAnsiChar; is_output: int); cdecl; external avformat_dll; const AV_FRAME_FILENAME_FLAGS_MULTIPLE = 1; // < Allow multiple %d (* * * Return in 'buf' the path with '%d' replaced by a number. * * Also handles the '%0nd' format where 'n' is the total number * of digits and '%%'. * * @param buf destination buffer * @param buf_size destination buffer size * @param path numbered sequence string * @param number frame number * @param flags AV_FRAME_FILENAME_FLAGS_* * @return 0 if OK, -1 on format error *) // int av_get_frame_filename2(char *buf, int buf_size, // const char *path, int number, int flags); function av_get_frame_filename2(buf: PAnsiChar; buf_size: int; const path: PAnsiChar; number: int; flags: int): int; cdecl; external avformat_dll; // int av_get_frame_filename(char *buf, int buf_size, // const char *path, int number); function av_get_frame_filename(buf: PAnsiChar; buf_size: int; const path: PAnsiChar; number: int): int; cdecl; external avformat_dll; (* * * Check whether filename actually is a numbered sequence generator. * * @param filename possible numbered sequence string * @return 1 if a valid numbered sequence string, 0 otherwise *) // int av_filename_number_test(const char *filename); function av_filename_number_test(const filename: PAnsiChar): int; cdecl; external avformat_dll; (* * * Generate an SDP for an RTP session. * * Note, this overwrites the id values of AVStreams in the muxer contexts * for getting unique dynamic payload types. * * @param ac array of AVFormatContexts describing the RTP streams. If the * array is composed by only one context, such context can contain * multiple AVStreams (one AVStream per RTP stream). Otherwise, * all the contexts in the array (an AVCodecContext per RTP stream) * must contain only one AVStream. * @param n_files number of AVCodecContexts contained in ac * @param buf buffer where the SDP will be stored (must be allocated by * the caller) * @param size the size of the buffer * @return 0 if OK, AVERROR_xxx on error *) // int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size); function av_sdp_create(ac: ppAVFormatContext; n_files: int; buf: PAnsiChar; size: int): int; cdecl; external avformat_dll; (* * * Return a positive value if the given filename has one of the given * extensions, 0 otherwise. * * @param filename file name to check against the given extensions * @param extensions a comma-separated list of filename extensions *) // int av_match_ext(const char *filename, const char *extensions); function av_match_ext(const filename: PAnsiChar; const extensions: PAnsiChar): int; cdecl; external avformat_dll; (* * * Test if the given container can store a codec. * * @param ofmt container to check for compatibility * @param codec_id codec to potentially store in container * @param std_compliance standards compliance level, one of FF_COMPLIANCE_* * * @return 1 if codec with ID codec_id can be stored in ofmt, 0 if it cannot. * A negative number if this information is not available. *) // int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id, // int std_compliance); function avformat_query_codec(const ofmt: pAVOutputFormat; codec_id: AVCodecID; std_compliance: int): int; cdecl; external avformat_dll; (* * * @defgroup riff_fourcc RIFF FourCCs * @{ * Get the tables mapping RIFF FourCCs to libavcodec AVCodecIDs. The tables are * meant to be passed to av_codec_get_id()/av_codec_get_tag() as in the * following code: * @code * uint32_t tag = MKTAG('H', '2', '6', '4'); * const struct AVCodecTag *table[] = { avformat_get_riff_video_tags(), 0 }; * enum AVCodecID id = av_codec_get_id(table, tag); * @endcode *) (* * * @return the table mapping RIFF FourCCs for video to libavcodec AVCodecID. *) // const struct AVCodecTag *avformat_get_riff_video_tags(void); function avformat_get_riff_video_tags(): pAVCodecTag; cdecl; external avformat_dll; (* * * @return the table mapping RIFF FourCCs for audio to AVCodecID. *) // const struct AVCodecTag *avformat_get_riff_audio_tags(void); function avformat_get_riff_audio_tags(): pAVCodecTag; cdecl; external avformat_dll; (* * * @return the table mapping MOV FourCCs for video to libavcodec AVCodecID. *) // const struct AVCodecTag *avformat_get_mov_video_tags(void); function avformat_get_mov_video_tags(): pAVCodecTag; cdecl; external avformat_dll; (* * * @return the table mapping MOV FourCCs for audio to AVCodecID. *) // const struct AVCodecTag *avformat_get_mov_audio_tags(void); function avformat_get_mov_audio_tags(): pAVCodecTag; cdecl; external avformat_dll; (* * * @} *) (* * * Guess the sample aspect ratio of a frame, based on both the stream and the * frame aspect ratio. * * Since the frame aspect ratio is set by the codec but the stream aspect ratio * is set by the demuxer, these two may not be equal. This function tries to * return the value that you should use if you would like to display the frame. * * Basic logic is to use the stream aspect ratio if it is set to something sane * otherwise use the frame aspect ratio. This way a container setting, which is * usually easy to modify can override the coded value in the frames. * * @param format the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame with the aspect ratio to be determined * @return the guessed (valid) sample_aspect_ratio, 0/1 if no idea *) // AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame); function av_guess_sample_aspect_ratio(format: pAVFormatContext; stream: pAVStream; frame: pAVFrame): AVRational; cdecl; external avformat_dll; (* * * Guess the frame rate, based on both the container and codec information. * * @param ctx the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame for which the frame rate should be determined, may be NULL * @return the guessed (valid) frame rate, 0/1 if no idea *) // AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame); function av_guess_frame_rate(ctx: pAVFormatContext; stream: pAVStream; frame: pAVFrame): AVRational; cdecl; external avformat_dll; (* * * Check if the stream st contained in s is matched by the stream specifier * spec. * * See the "stream specifiers" chapter in the documentation for the syntax * of spec. * * @return >0 if st is matched by spec; * 0 if st is not matched by spec; * AVERROR code if spec is invalid * * @note A stream specifier can match several streams in the format. *) // int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st, // const char *spec); function avformat_match_stream_specifier(s: pAVFormatContext; st: pAVStream; const spec: PAnsiChar): int; cdecl; external avformat_dll; // int avformat_queue_attached_pictures(AVFormatContext *s); function avformat_queue_attached_pictures(s: pAVFormatContext): int; cdecl; external avformat_dll; {$IFDEF FF_API_OLD_BSF} (* * * Apply a list of bitstream filters to a packet. * * @param codec AVCodecContext, usually from an AVStream * @param pkt the packet to apply filters to. If, on success, the returned * packet has size == 0 and side_data_elems == 0, it indicates that * the packet should be dropped * @param bsfc a NULL-terminated list of filters to apply * @return >=0 on success; * AVERROR code on failure *) // attribute_deprecated // int av_apply_bitstream_filters(AVCodecContext *codec, AVPacket *pkt, // AVBitStreamFilterContext *bsfc); function av_apply_bitstream_filters(codec: pAVCodecContext; pkt: pAVPacket; bsfc: pAVBitStreamFilterContext): int; cdecl; external avformat_dll; {$ENDIF} type AVTimebaseSource = ( // AVFMT_TBCF_AUTO = -1, // AVFMT_TBCF_DECODER, // AVFMT_TBCF_DEMUXER // {$IFDEF FF_API_R_FRAME_RATE} , AVFMT_TBCF_R_FRAMERATE {$ENDIF} ); (* * * Transfer internal timing information from one stream to another. * * This function is useful when doing stream copy. * * @param ofmt target output format for ost * @param ost output stream which needs timings copy and adjustments * @param ist reference input stream to copy timings from * @param copy_tb define from where the stream codec timebase needs to be imported *) // int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt, // AVStream *ost, const AVStream *ist, // enum AVTimebaseSource copy_tb); function avformat_transfer_internal_stream_timing_info(const ofmt: pAVOutputFormat; ost: pAVStream; const ist: pAVStream; copy_tb: AVTimebaseSource): int; cdecl; external avformat_dll; (* * * Get the internal codec timebase from a stream. * * @param st input stream to extract the timebase from *) // AVRational av_stream_get_codec_timebase(const AVStream *st); function av_stream_get_codec_timebase(const st: AVStream): AVRational; cdecl; external avformat_dll; {$ENDREGION} implementation function avio_tell(s: pAVIOContext): int64_t; inline; begin Result := avio_seek(s, 0, 1 { SEEK_CUR } ); end; end.
unit RiverRide; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.MPlayer,PngImage, Jpeg, Vcl.StdCtrls, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc; type TFormJogo = class(TForm) painelEsq: TPanel; painelDir: TPanel; nave: TImage; navio: TImage; helicoptero: TImage; ajato: TImage; tempoInimigo: TTimer; tempoTiro: TTimer; criaInimigo: TTimer; mensagemPerdeu: TPanel; jogarNao: TButton; mensagemFimJogo: TLabel; fase: TLabel; trilha: TMediaPlayer; levelUp: TMediaPlayer; carregarJogo: TPanel; Label2: TLabel; btnNovoJogo: TButton; btnCarregarJogo: TButton; lblnomeJogador: TLabel; pontosJogador: TLabel; initJogo: TPanel; Label3: TLabel; txtNomeJogador: TEdit; btnIniciarJogo: TButton; salvarXML: TXMLDocument; Label4: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure atirar(); procedure criarTiro(); procedure criarInimigo(Sender: TObject); procedure tempoTiroTimer(Sender: TObject); procedure tempoInimigoTimer(Sender: TObject); procedure declararVitoria(); procedure mudarNivel(); procedure iniciaJogo(); function VerificaColisao(O1, O2 : TControl):boolean; procedure exibeBatida(); procedure FormCreate(Sender: TObject); procedure btnIniciarJogoClick(Sender: TObject); procedure btnNovoJogoClick(Sender: TObject); procedure btnCarregarJogoClick(Sender: TObject); procedure jogarNaoClick(Sender: TObject); procedure salvar(); procedure carregarJogoSalvo(nomeJogador :string); private { Private declarations } public { Public declarations } end; var FormJogo: TFormJogo; numInimigosMatados, nivel: Integer; bateu : Boolean; nomeJogador: string; implementation {$R *.dfm} procedure TFormJogo.FormCreate(Sender: TObject); begin trilha.FileName := 'D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\sons\trilha.mp3'; trilha.Open; trilha.Play; end; procedure TFormJogo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var incremento : integer; begin incremento := 10; case key of VK_LEFT : if (nave.Left >= painelEsq.Width) then nave.Left := nave.Left - incremento; VK_RIGHT : if (nave.Left <= 352) then nave.Left := nave.Left + incremento; VK_UP : nave.Top := nave.Top - incremento; VK_DOWN : nave.Top := nave.Top + incremento; VK_SPACE: atirar(); end; end; procedure TFormJogo.iniciaJogo; begin DoubleBuffered := True; nave.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\eu.png'); navio.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\port.png'); helicoptero.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\helicoptero-militar.png'); ajato.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\plane2.png'); navio.Visible := False; helicoptero.Visible := False; ajato.Visible := False; bateu := false; numInimigosMatados := 0; nivel := 1; criaInimigo.OnTimer := criarInimigo; criaInimigo.Enabled := true; end; procedure TFormJogo.jogarNaoClick(Sender: TObject); begin salvar(); FormJogo.Close(); end; procedure TFormJogo.atirar(); begin criarTiro(); tempoTiro.Enabled := True; end; procedure TFormJogo.criarTiro(); var tiro: TPanel; tiroSom : TMediaPlayer ; begin if not bateu then begin tiro := TPanel.Create(FormJogo); tiro.Parent := FormJogo; tiro.Left := nave.Left + 22; tiro.Top := nave.Top; tiro.Width := 5; tiro.Height := 5; tiro.Color := clYellow; tiro.ParentBackground := False; tiro.ParentColor := False; tiro.Caption := ''; tiro.Visible := True; tiro.Tag := 1; // tiroSom := TMediaPlayer.Create(FormJogo); // tiroSom.Parent := FormJogo; // tiroSom.Visible := false; // tiroSom.FileName := 'D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\sons\tiro.mp3'; // tiroSom.Open; // tiroSom.Play; end; end; procedure TFormJogo.tempoTiroTimer(Sender: TObject); var i, j: Integer; begin if not bateu then begin for i := 0 to FormJogo.ComponentCount-1 do begin if FormJogo.Components[i] is TPanel then begin // Verificando se é o tiro if TPanel(FormJogo.Components[i]).Tag = 1 then begin // Movendo o tiro pra cima TPanel(FormJogo.Components[i]).Top := TPanel(FormJogo.Components[i]).Top - 15; // verificando se o tiro acertou um dos inimigos for j := 0 to FormJogo.ComponentCount-1 do begin if FormJogo.Components[j] is TImage then begin // Verificando se é o navio ou ajato ou helicoptero if (TImage(FormJogo.Components[j]).Tag = 2) or (TImage(FormJogo.Components[j]).Tag = 3) or (TImage(FormJogo.Components[j]).Tag = 4) then begin //Verificando se o Tiro acertou o inimigo if VerificaColisao(TPanel(FormJogo.Components[i]), TImage(FormJogo.Components[j])) then begin numInimigosMatados := numInimigosMatados + 1; pontosJogador.Caption := 'Pontos: ' + inttostr(numInimigosMatados); // sumir com o Tiro TPanel(FormJogo.Components[i]).Visible := False; TPanel(FormJogo.Components[i]).Left := 1000; // sumir com o Inimigo TImage(FormJogo.Components[j]).Visible := false; TImage(FormJogo.Components[j]).Left := 1000; // aumentando o nível do Jogo if (numInimigosMatados = 20) then begin nivel := 2; mudarNivel(); fase.Caption := 'Fase: ' + inttostr(nivel); fase.Font.Color := clFuchsia; criaInimigo.Interval := 2500; end; if (numInimigosMatados = 40) then begin nivel := 3; mudarNivel(); fase.Caption := 'Fase: ' + inttostr(nivel); fase.Font.Color := clRed; criaInimigo.Interval := 2000; end; if (numInimigosMatados = 60) then begin bateu:= true; declararVitoria(); end; end; end; end; end; end; end; end; end; end; procedure TFormJogo.btnIniciarJogoClick(Sender: TObject); begin nomeJogador := txtNomeJogador.Text; lblnomeJogador.Caption := nomeJogador; initJogo.Visible := False; carregarJogo.Visible:= true; end; procedure TFormJogo.btnCarregarJogoClick(Sender: TObject); begin iniciaJogo(); carregarJogoSalvo(nomeJogador); carregarJogo.Visible := False; end; procedure TFormJogo.btnNovoJogoClick(Sender: TObject); begin iniciaJogo(); carregarJogo.Visible := False; end; procedure TFormJogo.criarInimigo(Sender: TObject); var inimigoNavio, inimigoHelicoptero, inimigoAjato : TImage; begin if not bateu then begin // NAVIO inimigoNavio := TImage.Create(FormJogo); inimigoNavio.Parent := FormJogo; inimigoNavio.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\port.png'); inimigoNavio.Height := 33; inimigoNavio.Width := 33; inimigoNavio.Stretch := true; inimigoNavio.Proportional := true; inimigoNavio.Left := random(painelDir.Left-painelEsq.Left);; inimigoNavio.Top := 0; inimigoNavio.Visible := True; inimigoNavio.Tag := 2; // AJATO inimigoAjato := TImage.Create(FormJogo); inimigoAjato.Parent := FormJogo; inimigoAjato.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\plane2.png'); inimigoAjato.Height := 41; inimigoAjato.Width := 39; inimigoAjato.Stretch := true; inimigoAjato.Proportional := true; inimigoAjato.Left := random(painelDir.Left-painelEsq.Left); inimigoAjato.Top := 0; inimigoAjato.Visible := True; inimigoAjato.Tag := 4; // HELICOPTERO inimigoHelicoptero := TImage.Create(FormJogo); inimigoHelicoptero.Parent := FormJogo; inimigoHelicoptero.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\inimigo\helicoptero-militar.png'); inimigoHelicoptero.Height := 40; inimigoHelicoptero.Width := 46; inimigoHelicoptero.Stretch := true; inimigoHelicoptero.Proportional := true; inimigoHelicoptero.Left := random(painelDir.Left-painelEsq.Left); inimigoHelicoptero.Top := 0; inimigoHelicoptero.Visible := True; inimigoHelicoptero.Tag := 3; // ativa a movimentação dos inimigos tempoInimigo.Enabled := True; end; end; procedure TFormJogo.tempoInimigoTimer(Sender: TObject); var i: Integer; begin if not bateu then begin for i := 0 to FormJogo.ComponentCount-1 do begin if FormJogo.Components[i] is TImage then begin // Verificando se é o NAVIO if TPanel(FormJogo.Components[i]).Tag = 2 then begin // Movendo o NAVIO pra baixo TPanel(FormJogo.Components[i]).Top := TPanel(FormJogo.Components[i]).Top + 2 * nivel; //Verificando se o NAVIO acertou A NAVE if VerificaColisao(TPanel(FormJogo.Components[i]), nave) then begin bateu := true; exibeBatida(); end; end; // Verificando se é o HELICOPTERO if TPanel(FormJogo.Components[i]).Tag = 3 then begin // Movendo o HELICOPTERO pra baixo TPanel(FormJogo.Components[i]).Top := TPanel(FormJogo.Components[i]).Top + 5 * nivel; //Verificando se o HELICOPTERO acertou A NAVE if VerificaColisao(TPanel(FormJogo.Components[i]), nave) then begin bateu := true; exibeBatida(); end; end; // Verificando se é o AJATO if TPanel(FormJogo.Components[i]).Tag = 4 then begin // Movendo o AJATO pra baixo TPanel(FormJogo.Components[i]).Top := TPanel(FormJogo.Components[i]).Top + 7 * nivel; //Verificando se o AJATO acertou A NAVE if VerificaColisao(TPanel(FormJogo.Components[i]), nave) then begin bateu := true; exibeBatida(); end; end; end; end; end; end; function TFormJogo.VerificaColisao(O1, O2 : TControl): boolean; var topo, baixo, esquerda, direita : boolean; begin topo := false; baixo := false; esquerda := false; direita := false; if (O1.Top >= O2.top ) and (O1.top <= O2.top + O2.Height) then begin topo := true; end; if (O1.left >= O2.left) and (O1.left <= O2.left + O2.Width ) then begin esquerda := true; end; if (O1.top + O1.Height >= O2.top ) and (O1.top + O1.Height <= O2.top + O2.Height) then begin baixo := true; end; if (O1.left + O1.Width >= O2.left ) and (O1.left + O1.Width <= O2.left + O2.Width) then begin direita := true; end; if (topo or baixo) and (esquerda or direita) then o2.Visible := false; VerificaColisao := (topo or baixo) and (esquerda or direita); end; procedure TFormJogo.exibeBatida; var explosao: TImage; explosaoSom : TMediaPlayer ; begin explosao := TImage.Create(FormJogo); explosao.Parent := FormJogo; explosao.Picture.LoadFromFile('D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\explosao.png'); explosao.Height := 50; explosao.Width := 50; explosao.Stretch := true; explosao.Proportional := true; explosao.Left := nave.Left; explosao.Top := nave.Top; explosao.Visible := True; trilha.Close; explosaoSom := TMediaPlayer.Create(FormJogo); explosaoSom.Parent := FormJogo; explosaoSom.Visible := false; explosaoSom.FileName := 'D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\sons\explosao.mp3'; explosaoSom.Open; explosaoSom.Play; mensagemPerdeu.Visible := True; explosao.Visible := false; end; procedure TFormJogo.declararVitoria; var somVitoria: TMediaPlayer; begin trilha.Close; somVitoria := TMediaPlayer.Create(FormJogo); somVitoria.Parent := FormJogo; somVitoria.Visible := false; somVitoria.FileName := 'D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\sons\vitoria.mp3'; somVitoria.Open; somVitoria.Play; mensagemFimJogo.Caption := 'VOCÊ GANHOU!'; mensagemFimJogo.Font.Color := clGreen; mensagemPerdeu.Visible := true; end; procedure TFormJogo.mudarNivel; begin levelUp.Close; levelUp.FileName := 'D:\Documentos\Desktop\01 - Jogo\Rive Rider\img\sons\levelup.mp3'; levelUp.Open; levelUp.Play; end; procedure TFormJogo.salvar; var riverRide, jogadores, player, naveIcon: IXMLNode; i: integer; jaJogou: Boolean; begin if FileExists('riverride.xml') then //verificando se o arquivo existe begin jaJogou := False; salvarXML.LoadFromFile('riverride.xml'); // se existir lê até a lista de jogadores riverRide := salvarXML.ChildNodes.FindNode('riverride'); jogadores := riverRide.ChildNodes.FindNode('jogadores'); // percorrendo os jogadores for i := 0 to jogadores.ChildNodes.Count-1 do begin // verificando se é o jogador já jogou antes. Se jogou sobreEscreva a ultima jogada dele if jogadores.ChildNodes[i].Attributes['nome'] = lblnomeJogador.Caption then begin jaJogou := True; player := jogadores.ChildNodes[i]; naveIcon := player.ChildNodes.FindNode('nave'); naveIcon.ChildValues['left'] := intToStr(nave.Left);; naveIcon.ChildValues['top'] := intToStr(nave.Top);; player.ChildValues['pontos'] := intToStr(numInimigosMatados); player.ChildValues['fase'] := intToStr(nivel); end; end; if not jaJogou then begin // adiciona um node jogador player := jogadores.AddChild('jogador'); player.Attributes['nome'] := lblnomeJogador.Caption; naveicon := player.AddChild('nave'); naveicon.AddChild('left').Text := intToStr(nave.Left); naveicon.AddChild('top').Text := intToStr(nave.Top); player.AddChild('pontos').Text := intToStr(numInimigosMatados); player.AddChild('fase').Text := intToStr(nivel); end; end else begin // se não existir cria o nó riverride e jogadores salvarXML.Active := True; riverRide := salvarXML.AddChild('riverride'); jogadores := riverRide.AddChild('jogadores'); // adiciona um node jogador player := jogadores.AddChild('jogador'); player.Attributes['nome'] := lblnomeJogador.Caption; naveicon := player.AddChild('nave'); naveicon.AddChild('left').Text := intToStr(nave.Left); naveicon.AddChild('top').Text := intToStr(nave.Top); player.AddChild('pontos').Text := intToStr(numInimigosMatados); player.AddChild('fase').Text := intToStr(nivel); end; salvarXML.SaveToFile('riverride.xml'); end; procedure TFormJogo.carregarJogoSalvo(nomeJogador :string); var riverRide, jogadores, player, naveIcon: IXMLNode; i, left, top :Integer; jogadorExiste: Boolean; begin jogadorExiste := false; if FileExists('riverride.xml') then //verificando se o arquivo existe begin salvarXML.LoadFromFile('riverride.xml'); riverRide := salvarXML.ChildNodes.FindNode('riverride'); jogadores := riverRide.ChildNodes.FindNode('jogadores'); // percorrendo os jogadores for i := 0 to jogadores.ChildNodes.Count-1 do begin // verificando se é o jogador a jogar if jogadores.ChildNodes[i].Attributes['nome'] = nomeJogador then begin jogadorExiste := true; player := jogadores.ChildNodes[i]; naveIcon := player.ChildNodes.FindNode('nave'); left := StrtoInt(naveIcon.ChildValues['left']); top := StrtoInt(naveIcon.ChildValues['top']); nave.Top := top; nave.Left := left; numInimigosMatados := StrToInt(player.ChildValues['pontos']); nivel := StrToInt(player.ChildValues['fase']); fase.Caption := 'Fase: ' + inttostr(nivel); pontosJogador.Caption := 'Pontos: ' + inttostr(numInimigosMatados); end; end; end else begin showmessage('Você não possui nenhum jogo salvo, então iniciará um novo jogo'); jogadorExiste := true; end; if not jogadorExiste then showmessage('Você não possui nenhum jogo salvo, então iniciará um novo jogo'); end; //FIM end.
unit SearchAndReplacePrimTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Daily/SearchAndReplacePrimTest.pas" // Начат: 28.06.2010 15:45 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TSearchAndReplacePrimTest // // Тест поиска/замены // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses nevTools, evTypes, TextViaEditorProcessor, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TSearchAndReplacePrimTest = {abstract} class(TTextViaEditorProcessor) {* Тест поиска/замены } protected // realized methods procedure Process(aForm: TPrimTextLoadForm); override; {* Собственно процесс обработки текста } protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } protected // protected methods function Searcher: IevSearcher; virtual; abstract; function Replacer: IevReplacer; virtual; abstract; function Options: TevSearchOptionSet; virtual; abstract; end;//TSearchAndReplacePrimTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TSearchAndReplacePrimTest procedure TSearchAndReplacePrimTest.Process(aForm: TPrimTextLoadForm); //#UC START# *4BE13147032C_4C288B4D012F_var* //#UC END# *4BE13147032C_4C288B4D012F_var* begin //#UC START# *4BE13147032C_4C288B4D012F_impl* aForm.Text.Find(Searcher, Replacer, Options); //#UC END# *4BE13147032C_4C288B4D012F_impl* end;//TSearchAndReplacePrimTest.Process function TSearchAndReplacePrimTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TSearchAndReplacePrimTest.GetFolder function TSearchAndReplacePrimTest.GetModelElementGUID: AnsiString; {-} begin Result := '4C288B4D012F'; end;//TSearchAndReplacePrimTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit Control.RoteirosExpressas; interface uses FireDAC.Comp.Client, Common.ENum, Model.RoteirosExpressas, Control.Sistema, System.Classes, System.SysUtils; type TRoteirosExpressasControl = class private FRoteiros : TRoteirosExpressas; procedure StartProcess(); procedure UpdateProcess(dCount: Double); procedure TerminateProcess(); public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): TFDQuery; function GetId(): Integer; function DeleteCliente(iCliente: Integer): Boolean; function PopulateRoteiros(sRoteiro: string): Boolean; procedure ImportRoteiros(sFile: String; iCliente: Integer); function SaveData(): Boolean; function ListRoteiro(): TFDQuery; function SetupModel(FDQuery: TFDQuery): Boolean; property Roteiros: TRoteirosExpressas read FRoteiros write FRoteiros; end; implementation { TRoteirosExpressasControl } uses View.RoteirosExpressas, Data.SisGeF, Global.Parametros, Common.Utils, System.Threading; constructor TRoteirosExpressasControl.Create; begin FRoteiros := TRoteirosExpressas.Create; end; function TRoteirosExpressasControl.DeleteCliente(iCliente: Integer): Boolean; begin Result := FRoteiros.DeleteCliente(iCliente); end; destructor TRoteirosExpressasControl.Destroy; begin FRoteiros.Free; inherited; end; function TRoteirosExpressasControl.GetId: Integer; begin Result := FRoteiros.GetID(); end; function TRoteirosExpressasControl.Gravar: Boolean; begin Result := FRoteiros.Gravar(); end; procedure TRoteirosExpressasControl.ImportRoteiros(sFile: String; iCliente: Integer); var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; iTotal : Integer; dCount : Double; i : Integer; iTipo: Integer; begin TTask.Run(procedure begin TThread.Synchronize(nil, procedure begin Self.StartProcess(); end); if Data_Sisgef.mtbRoteirosExpressas.Active then Data_Sisgef.mtbRoteirosExpressas.Close; Data_Sisgef.mtbRoteirosExpressas.Open; AssignFile(ArquivoCSV, sFile); sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); iTotal := Common.Utils.TUtils.NumeroDeLinhasTXT(sFile); i := 0; dCount := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; if Common.Utils.TUtils.ENumero(sDetalhe[0]) then begin iTipo := 0; Data_Sisgef.mtbRoteirosExpressas.Insert; Data_Sisgef.mtbRoteirosExpressasid_roteiro.AsInteger := 0; Data_Sisgef.mtbRoteirosExpressascod_ccep5.AsString:= sDetalhe[7]; Data_Sisgef.mtbRoteirosExpressasdes_roteiro.AsString := UTF8ToString(sDetalhe[8]); Data_Sisgef.mtbRoteirosExpressasnum_cep_inicial.AsString := sDetalhe[0]; if sDetalhe[1] = '' then begin Data_Sisgef.mtbRoteirosExpressasnum_cep_final.AsString := sDetalhe[0]; end else begin Data_Sisgef.mtbRoteirosExpressasnum_cep_final.AsString := sDetalhe[1]; end; Data_Sisgef.mtbRoteirosExpressasdes_prazo.AsString := UTF8ToString(sDetalhe[2]); Data_Sisgef.mtbRoteirosExpressasdom_zona.AsString := Copy(sDetalhe[3],1,1); if sDetalhe[4] = 'ABRANG. LEVE e PESADO' then begin iTipo := 3; end else if sDetalhe[4] = 'NÃO FAZ' then begin iTipo := 0; end else if Pos('FAZ PESADO', sDetalhe[4]) > 0 then begin iTipo := 2; end else if sDetalhe[4] = 'SÓ FAZ LEVE' then begin iTipo := 1; end; Data_Sisgef.mtbRoteirosExpressascod_tipo.AsInteger := iTipo; Data_Sisgef.mtbRoteirosExpressasdes_logradouro.AsString := UTF8ToString(sDetalhe[5]); Data_Sisgef.mtbRoteirosExpressasdes_bairro.AsString := UTF8ToString(sdetalhe[6]); if sDetalhe.Count > 10 then begin Data_Sisgef.mtbRoteirosExpressascod_leve.AsInteger := StrToIntDef(sDetalhe[11], 0); Data_Sisgef.mtbRoteirosExpressascod_pesado.AsInteger := StrToIntDef(sDetalhe[12], 0); end else begin Data_Sisgef.mtbRoteirosExpressascod_leve.AsInteger := 0; Data_Sisgef.mtbRoteirosExpressascod_pesado.AsInteger := 0; end; Data_Sisgef.mtbRoteirosExpressascod_cliente.AsInteger := iCliente; Data_Sisgef.mtbRoteirosExpressas.Post; end; Inc(i); dCount := (i / iTotal) * 100; TThread.Synchronize(nil, procedure begin Self.UpdateProcess(dCount); end); end; CloseFile(ArquivoCSV); TThread.Synchronize(nil, procedure begin Self.TerminateProcess; end); end); end; function TRoteirosExpressasControl.ListRoteiro: TFDQuery; begin Result := FRoteiros.ListRoteiro(); end; function TRoteirosExpressasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FRoteiros.Localizar(aParam); end; function TRoteirosExpressasControl.PopulateRoteiros(sRoteiro: string): Boolean; var fdQuery : TFDQuery; aParam : Array of variant; begin try Result := False; SetLength(aParam, 2); aParam[0] := 'CCEP5'; aParam[1] := sRoteiro; fdQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery(); fdQuery := FRoteiros.Localizar(aParam); Finalize(aParam); if Data_Sisgef.mtbRoteirosExpressas.Active then Data_Sisgef.mtbRoteirosExpressas.Close; if not fdQuery.IsEmpty then begin Data_Sisgef.mtbRoteirosExpressas.Data := fdQuery.Data; end else begin Exit; end; Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TRoteirosExpressasControl.SaveData(): Boolean; begin Result := FRoteiros.SaveData(Data_Sisgef.mtbRoteirosExpressas); end; function TRoteirosExpressasControl.SetupModel(FDQuery: TFDQuery): Boolean; begin Result := FRoteiros.SetupModel(FDQuery); end; procedure TRoteirosExpressasControl.StartProcess; begin view_RoteirosExpressas.ds.Enabled := False; view_RoteirosExpressas.progressBar.Position := 0; view_RoteirosExpressas.lyiProgresso.Visible := True; view_RoteirosExpressas.actGravarRoteiros.Enabled := False; view_RoteirosExpressas.actCancelar.Enabled := False; end; procedure TRoteirosExpressasControl.TerminateProcess; begin view_RoteirosExpressas.progressBar.Position := 0; view_RoteirosExpressas.lyiProgresso.Visible := False; view_RoteirosExpressas.ds.Enabled := True; if not Data_Sisgef.mtbRoteirosExpressas.IsEmpty then begin view_RoteirosExpressas.actGravarRoteiros.Enabled := True; view_RoteirosExpressas.actCancelar.Enabled := True; end; end; procedure TRoteirosExpressasControl.UpdateProcess(dCount: Double); begin view_RoteirosExpressas.progressBar.Position := dCount; view_RoteirosExpressas.progressBar.Refresh; end; end.
unit Cliente_u; interface uses System.Classes, Vcl.CheckLst, System.SysUtils, Vcl.StdCtrls, System.SyncObjs, Vcl.Forms; type Cliente = class(TThread) private { Private declarations } FilaClientes: TCheckListBox; QuantidadeCadeiras: Integer; CadeiraCabeleireiro: TCheckBox; SecaoCritica: TCriticalSection; FTempoParaNovoCliente: Integer; FProgramaExecutando: Boolean; FPrioridade: Integer; procedure setProgramaExecutando(const Value: Boolean); procedure setTempoParaNovoCliente(const Value: Integer); procedure setPrioridade(const Value: Integer); procedure AtualizaStatus; procedure BuscaReservaCadeira(Const APrioridadeAtendimento: Integer; Const AVaiDiretoFilaEspera: Boolean); protected procedure Execute; override; public constructor Create(const ACreateSuspended: Boolean; const AProgramaExecutando: boolean; Var AFilaClientes: TCheckListBox; const AQuantidadeCadeiras: Integer; Var ACadeiraCabeleireiro: TCheckBox; Var ASecaoCritica: TCriticalSection); property TempoParaNovoCliente: Integer read FTempoParaNovoCliente write setTempoParaNovoCliente; property ProgramaExecutando: Boolean read FProgramaExecutando write setProgramaExecutando; property Prioridade: Integer read FPrioridade write setPrioridade; end; implementation { Cliente } procedure Cliente.AtualizaStatus; begin FilaClientes.Update; CadeiraCabeleireiro.Update; end; procedure Cliente.BuscaReservaCadeira(const APrioridadeAtendimento: Integer; Const AVaiDiretoFilaEspera: Boolean); var i, vCadeiraVazia: Integer; vAlguemJaEsperando: Boolean; begin Application.ProcessMessages; vAlguemJaEsperando := False; if not AVaiDiretoFilaEspera then for i := 0 to QuantidadeCadeiras - 1 do begin if FilaClientes.Checked[i] then begin vAlguemJaEsperando := True; Break; end; end; if (vAlguemJaEsperando) or (CadeiraCabeleireiro.Checked) or (AVaiDiretoFilaEspera) then begin vCadeiraVazia := -1; for i := 0 to QuantidadeCadeiras - 1 do begin if not FilaClientes.Checked[i] then begin FilaClientes.Checked[i] := True; FilaClientes.Items[i] := IntToStr(APrioridadeAtendimento); AtualizaStatus; break; end; end; end else begin SecaoCritica.Acquire; try CadeiraCabeleireiro.Checked := True; CadeiraCabeleireiro.Caption := 'Ocupada por Cliente'; Synchronize(AtualizaStatus); finally SecaoCritica.Release; end; //Caso o caption não seja o que foi tentado setar a cima, significa que alguém estava usando a seção crítica //e por isso não foi possível usá-la, com isso chama-se a função BuscaReservaCadeira que agora irá mandar // o cliente direto para a Fila de espera if CadeiraCabeleireiro.Caption <> 'Ocupada por Cliente' then begin BuscaReservaCadeira(APrioridadeAtendimento, True); end; end; end; constructor Cliente.Create(const ACreateSuspended, AProgramaExecutando: boolean; Var AFilaClientes: TCheckListBox; const AQuantidadeCadeiras: Integer; Var ACadeiraCabeleireiro: TCheckBox; Var ASecaoCritica: TCriticalSection); begin Self.ProgramaExecutando := AProgramaExecutando; Self.FilaClientes := AFilaClientes; Self.QuantidadeCadeiras := AQuantidadeCadeiras; Self.CadeiraCabeleireiro := ACadeiraCabeleireiro; Self.SecaoCritica := ASecaoCritica; inherited Create(ACreateSuspended); end; procedure Cliente.Execute; var vCadeiraVazia: Integer; begin while ProgramaExecutando do begin AtualizaStatus; if (Random(1) + 1) = 1 then begin Self.FPrioridade := Prioridade + 1; BuscaReservaCadeira(Prioridade, False); end; AtualizaStatus; Sleep(TempoParaNovoCliente * 1000); end; end; procedure Cliente.setPrioridade(const Value: Integer); begin FPrioridade := Value; end; procedure Cliente.setProgramaExecutando(const Value: Boolean); begin FProgramaExecutando := Value; end; procedure Cliente.setTempoParaNovoCliente(const Value: Integer); begin FTempoParaNovoCliente := Value; end; end.
{ Subroutine SST_SYMBOL_NEW (NAME_H, CHARCASE, SYMBOL_P, STAT) * * Add a new symbol to the current scope. It is an error if the symbol * already exists in that name space, although it may exists in more global * name spaces. NAME_H is the string handle for the symbol name returned * from one of the SYO_GET_TAG routines. SYMBOL_P is returned pointing to * the newly created data block for the symbol. STAT is returned with an * error if the symbol already exists in the current scope. * * The value of CHARCASE effects what kind of case conversions are applied to * the symbol name before storing it in the symbol table. Values can be: * * SYO_CHARCASE_DOWN_K - Force symbol name to all lower case. * SYO_CHARCASE_UP_K - Force symbol name to all upper case. * SYO_CHARCASE_ASIS_K - Do not alter name. } module sst_SYMBOL_NEW; define sst_symbol_new; %include 'sst2.ins.pas'; procedure sst_symbol_new ( {add symbol to current scope given syn handle} in name_h: syo_string_t; {handle to name string from tag} in charcase: syo_charcase_k_t; {SYO_CHARCASE_xxx_K with DOWN, UP or ASIS} out symbol_p: sst_symbol_p_t; {points to new symbol descriptor} out stat: sys_err_t); {completion status code} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var name: string_var132_t; {symbol name string} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin name.max := sizeof(name.str); {init local var string} syo_get_tag_string (name_h, name); {get actual symbol name} case charcase of syo_charcase_down_k: string_downcase(name); syo_charcase_up_k: string_upcase(name); syo_charcase_asis_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(charcase)); sys_message_bomb ('syn', 'charcase_bad', msg_parm, 1); end; sst_symbol_new_name (name, symbol_p, stat); {add new symbol to symbol table} if not sys_error(stat) then begin {really did create new symbol ?} symbol_p^.char_h := name_h.first_char; {save handle to first symbol source char} end; end;
unit GateInfo; interface uses Classes, SysUtils; type TGateInfo = class public constructor Create; destructor Destroy; override; private fLoaded : boolean; fValues : TStringList; public function GetIntValue(ppName : string) : integer; procedure SetIntValue(ppName : string; value : integer); function GetFloatValue(ppName : string) : double; procedure SetFloatValue(ppName : string; value : double); function GetStrValue(ppName : string) : string; function GetStrArray(ppName : string; index : integer) : string; procedure SetStrArray(ppName : string; index : integer; Value : string); function GetMLSStrArray(ppName, langid : string; index : integer) : string; procedure SetMLSStrArray(ppName, langid : string; index : integer; value : string); procedure Load(source : string); procedure AddProp(ppName, ppValue : string); public property Loaded : boolean read fLoaded write fLoaded; property Values : TStringList read fValues; property IntValue[ppName : string] : integer read GetIntValue write SetIntValue; property FloatValue[ppName : string] : double read GetFloatValue write SetFloatValue; property StrValue[ppName : string] : string read GetStrValue; property StrArray[ppName : string; index : integer] : string read GetStrArray write SetStrArray; property MLSStrArray[ppName, langid : string; index : integer] : string read GetMLSStrArray write SetMLSStrArray; end; implementation // TGateInfo constructor TGateInfo.Create; begin inherited; fValues := TStringList.Create; end; destructor TGateInfo.Destroy; begin fValues.Free; inherited; end; function TGateInfo.GetIntValue(ppName : string) : integer; var aux : string; begin aux := fValues.Values[ppName]; if aux <> '' then try result := StrToInt(aux); except result := 0; end else result := 0; end; function TGateInfo.GetFloatValue(ppName : string) : double; var aux : string; begin aux := fValues.Values[ppName]; if aux <> '' then try result := StrToFloat(aux); except result := 0; end else result := 0; end; procedure TGateInfo.SetIntValue(ppName : string; value : integer); begin fValues.Values[ppName] := IntToStr(value); end; procedure TGateInfo.SetFloatValue(ppName : string; value : double); begin fValues.Values[ppName] := FloatToStr(value); end; function TGateInfo.GetStrValue(ppName : string) : string; begin result := fValues.Values[ppName]; end; function TGateInfo.GetStrArray(ppName : string; index : integer) : string; begin result := fValues.Values[ppName + IntToStr(index)]; end; procedure TGateInfo.SetStrArray(ppName : string; index : integer; Value : string); begin fValues.Values[ppName + IntToStr(index)] := Value; end; function TGateInfo.GetMLSStrArray(ppName, langid : string; index : integer) : string; begin result := fValues.Values[ppName + IntToStr(index) + '.' + langid]; end; procedure TGateInfo.SetMLSStrArray(ppName, langid : string; index : integer; value : string); begin fValues.Values[ppName + IntToStr(index) + '.' + langid] := Value; end; procedure TGateInfo.Load(source : string); begin fValues.Text := source; end; procedure TGateInfo.AddProp(ppName, ppValue : string); begin fValues.Values[ppName] := ppValue; end; end.
{$MODE OBJFPC} {$R-,Q-,S-,I-} {$OPTIMIZATION LEVEL3} {$INLINE ON} program _PROBLEM_Testing; uses SysUtils, Math, JudgerV2; const TimeLimit = 30.0; //Seconds ProblemTitle = 'LINES'; //Title bar Prefix = 'LINES'; //file name without extension ExeName = Prefix + '.EXE'; TestCases: Ansistring = '1234567890abcdefghijklmnopqrstuvwxyz'; InputFormat = Prefix + '._%s'; InputFile = Prefix + '.INP'; OutputFile = Prefix + '.OUT'; maxN = Round(1E5); type TPoint = packed record x, y: LongInt; end; TVector = TPoint; PNode = ^TNode; TLine = packed record ptr: PNode; case Boolean of False: (x1, y1, x2, y2: LongInt); True: (eP, eQ: TPoint); end; TEndPoint = record x, y: Integer; close: Boolean; lineid: Integer; end; TNode = record lineid: Integer; P, L, R: PNode; end; var lines: array[1..maxN] of TLine; p: array[1..2 * maxN] of TEndPoint; n: Integer; res: Integer; root, nilT: PNode; sentinel: TNode; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n); for i := 1 to n do with lines[i] do ReadLn(f, x1, y1, x2, y2); finally CloseFile(f); end; end; operator <(const p, q: TEndPoint): Boolean; begin if p.x < q.x then Exit(True); if p.x > q.x then Exit(False); if p.close < q.close then Exit(True); if p.close > q.close then Exit(False); Result := p.y < q.y end; procedure SortPoints(L, H: Integer); var pivot: TEndPoint; i, j: Integer; begin if L >= H then Exit; i := L + Random(H - L + 1); pivot := p[i]; p[i] := p[L]; i := L; j := H; repeat while (pivot < p[j]) and (i < j) do Dec(j); if i < j then begin p[i] := p[j]; Inc(i); end else Break; while (p[i] < pivot) and (i < j) do Inc(i); if i < j then begin p[j] := p[i]; Dec(j); end else Break; until i = j; p[i] := pivot; SortPoints(L, i - 1); SortPoints(i + 1, H); end; procedure Refine; var i, j: Integer; procedure Swap(var a, b: Integer); var t: Integer; begin t := a; a := b; b := t; end; begin for i := 1 to n do with lines[i] do if x1 > x2 then begin Swap(x1, x2); Swap(y1, y2); end; j := 2 * n; for i := 1 to n do with lines[i] do begin p[i].x := x1; p[i].y := y1; p[i].close := False; p[i].lineid := i; p[j].x := x2; p[j].y := y2; p[j].close := True; p[j].lineid := i; Dec(j); end; SortPoints(1, 2 * n); end; function Sign(x: Int64): Integer; inline; begin if x > 0 then Result := 1 else if x < 0 then Result := -1 else Result := 0; end; operator -(const u, v: TVector): TVector; inline; begin Result.x := u.x - v.x; Result.y := u.y - v.y; end; operator *(const u, v: TVector): Int64; //inline; begin Result := Int64(u.x) * v.x + Int64(u.y) * v.y;end; operator ><(const u, v: TVector): Integer; //inline; begin Result := Sign(Int64(u.x) * v.y - Int64(u.y) * v.x); end; function Intersect(const a, b: TLine): Boolean; //inline var d1, d2, d3, d4: Integer; function OnSeg(const M, N, P: TPoint): Boolean; inline; begin Result := Sign((M - P) * (N - P)) <= 0; end; function Dir(const M, N, P: TPoint): Integer; inline; begin Result := (N - M) >< (P - N); if (Result = 0) and OnSeg(M, N, P) then Result := 2; end; begin d1 := Dir(b.eP, b.eQ, a.eP); if d1 = 2 then Exit(True); d2 := Dir(b.eP, b.eQ, a.eQ); if d2 = 2 then Exit(True); d3 := Dir(a.eP, a.eQ, b.eP); if d3 = 2 then Exit(True); d4 := Dir(a.eP, a.eQ, b.eQ); if d4 = 2 then Exit(True); Result := (d1 * d2 = -1) and (d3 * d4 = -1); end; procedure InitTree; begin nilT := @sentinel; root := nilT; end; procedure DeleteTree(x: PNode); begin if x = nilT then Exit; DeleteTree(x^.L); DeleteTree(x^.R); Dispose(x); end; procedure SetR(x, y: PNode); //inline; begin x^.R := y; y^.P := x; end; procedure SetL(x, y: PNode); //inline; begin x^.L := y; y^.P := x; end; procedure SetC(x, y: PNode; InRight: Boolean); //inline; begin if InRight then SetR(x, y) else SetL(x, y); end; procedure UpTree(x: PNode); //inline; var y, z: PNode; begin y := x^.P; z := y^.P; if x = y^.L then begin SetL(y, x^.R); SetR(x, y); end else begin SetR(y, x^.L); SetL(x, y); end; SetC(z, x, z^.R = y); end; procedure Splay(x: PNode); //inline; var y, z: PNode; begin repeat y := x^.P; if y = nilT then Break; z := y^.P; if z <> nilT then if (y = z^.L) = (x = y^.L) then UpTree(y) else UpTree(x); UpTree(x); until False; root := x; end; function Predecessor(x: PNode): PNode; //inline; begin Splay(x); if x^.L <> nilT then begin Result := x^.L; while Result^.R <> nilT do Result := Result^.R; Splay(Result); end else Result := nilT; end; function Successor(x: PNode): PNode; //inline; begin Splay(x); if x^.R <> nilT then begin Result := x^.R; while Result^.L <> nilT do Result := Result^.L; Splay(Result); end else Result := nilT; end; function Above(const a, b: TLine): Boolean; //inline; begin Result := (b.eP - a.eP) >< (b.eQ - a.eP) > 0; end; procedure Insert(lid: Integer); //inline; var x, y: PNode; tr: Boolean; begin x := nilT; y := root; while y <> nilT do begin x := y; tr := Above(lines[lid], lines[y^.lineid]); if tr then y := y^.R else y := y^.L; end; New(y); y^.lineid := lid; y^.L := nilT; y^.R := nilT; lines[lid].ptr := y; SetC(x, y, tr); Splay(y); end; procedure Delete(lid: Integer); //inline; var x, y, z: PNode; begin x := lines[lid].ptr; y := Predecessor(x); if y <> nilT then Splay(y); z := x^.P; if x^.L <> nilT then y := x^.L else y := x^.R; SetC(z, y, z^.R = x); if x = root then root := y; Dispose(x); end; function Upper(lineid: Integer): Integer; //inline; var x: PNode; begin x := lines[lineid].ptr; x := Successor(x); if x = nilT then Result := -1 else Result := x^.lineid; end; function Lower(lineid: Integer): Integer; //inline; var x: PNode; begin x := lines[lineid].ptr; x := Predecessor(x); if x = nilT then Result := -1 else Result := x^.lineid; end; function Check(threshold: Integer): Boolean; var i: Integer; current: Integer; upperline, lowerline: Integer; begin InitTree; try for i := 1 to 2 * n do if p[i].lineid <= threshold then if not p[i].close then begin current := p[i].lineid; Insert(current); upperline := Upper(current); if (upperline <> - 1) and Intersect(lines[current], lines[upperline]) then Exit(True); lowerline := Lower(current); if (lowerline <> -1) and Intersect(lines[current], lines[lowerline]) then Exit(True); end else begin current := p[i].lineid; upperline := Upper(current); lowerline := Lower(current); if (upperline <> -1) and (lowerline <> -1) and Intersect(lines[upperline], lines[lowerline]) then Exit(True); Delete(current); end; Result := False; finally DeleteTree(root); end; end; procedure Solve; var low, middle, high: Integer; begin low := 2; high := n; //low - 1: ko cat, high + 1: cat repeat middle := (low + high) div 2; if Check(middle) then high := middle - 1 else low := middle + 1; until low > high; if low <= n then res := low else res := -1; end; procedure AllTasks; begin Enter; Refine; InitTree; Solve; end; procedure DoCheck(obj: TJudger); var f: TextFile; hsres: Integer; begin //Solve AllTasks; obj.ev := 0; if not FileExists(OutputFile) then begin TTextEngine.MsgError('Output file not found', []); Exit; end; AssignFile(f, OutputFile); Reset(f); try try //Checking, set mark by ev from 0 to 1 WriteLn('Checking the result: '); ReadLn(f, hsres); TTextEngine.bl1; WriteLn('Answer: ', res); TTextEngine.bl1; WriteLn('Output: ', hsres); if res <> hsres then GenErr('Ke^''t qua? sai', []); WriteLn; TTextEngine.MsgOK; obj.ev := 1; finally CloseFile(f); end; except on E:Exception do TTextEngine.MsgError(E.Message) end; end; begin Judger.Title := ProblemTitle; Judger.ExecCmd := ExeName; Judger.InputFormat := InputFormat; Judger.InputFile := InputFile; Judger.OutputFile := OutputFile; Judger.GetTestCases(TestCases); Judger.TimeLimit := TimeLimit; Judger.CheckProc := @DoCheck; Judger.Silent := TFileEngine.ParamStr(1) = '/SILENT'; if Judger.Silent then Judger.LogFile := Prefix + '.log'; Judger.Run; if Judger.Silent then TStdIO.Pause; if (Judger.Score + 1E-6 >= Judger.MaxScore) then TTextEngine.SayPerfect; Judger.ShowLog; end.
unit MsgBoxUtils; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows; const idOK = 1; idCancel = 2; idAbort = 3; idRetry = 4; idIgnore = 5; idYes = 6; idNo = 7; const ttYesNo = MB_YESNO + MB_ICONQUESTION; ttAbort = MB_ABORTRETRYIGNORE + MB_ICONSTOP; ttRetry = MB_RETRYCANCEL + MB_ICONSTOP; ttCancel = MB_YESNOCANCEL + MB_ICONSTOP; ttErrorInfo = MB_OK + MB_ICONSTOP; ttInfo = MB_OK + MB_ICONINFORMATION; function ShowInfoBox( const Msg : string; args : array of const; Caption : string; TextType : cardinal) : integer; function ShowMessageBox( const Msg, Caption : string; TextType : cardinal) : integer; implementation uses SysUtils; function ShowInfoBox( const Msg : string; args : array of const; Caption : string; TextType : cardinal) : integer; var Buf : string; begin FmtStr( Buf, Msg, args); Result := MessageBox( 0, pchar(Buf), pchar(Caption), TextType); end; function ShowMessageBox( const Msg, Caption : string; TextType : cardinal) : integer; begin Result := MessageBox( 0, pchar(msg), pchar(Caption), TextType); end; end.
unit EquipmentCommandForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SynEditHighlighter, OkCancel_frame, Mask, DBCtrlsEh, StdCtrls, DBCtrls, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, DBLookupEh, Menus, PrjConst, DBGridEh, Vcl.ExtCtrls; type TEquipmentCommandForm = class(TForm) okcnclfrm1: TOkCancelFrame; srcGC: TDataSource; lbl2: TLabel; dbm1: TDBMemoEh; srcGroup: TDataSource; dsGroup: TpFIBDataSet; dsGC: TpFIBDataSet; trWrite: TpFIBTransaction; pmMemo: TPopupMenu; pnlMain: TPanel; lbl4: TLabel; edtName: TDBEditEh; lbl5: TLabel; lcbGroup: TDBLookupComboboxEh; lbl3: TLabel; cbType: TDBComboBoxEh; dbchGUI: TDBCheckBoxEh; cbEOL: TDBComboBoxEh; lbl6: TLabel; pnlURL: TPanel; pnlCMD: TPanel; lbl1: TLabel; dbmNotice: TDBMemoEh; lblURL: TLabel; edtURL: TDBEditEh; edtUSR: TDBEditEh; edtPSWD: TDBEditEh; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure IP1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure okcnclfrm1bbOkClick(Sender: TObject); procedure cbTypeChange(Sender: TObject); private { Private declarations } public { Public declarations } end; function EditGroupCommand(C_ID: Integer): Boolean; implementation uses DM; {$R *.dfm} function EditGroupCommand(C_ID: Integer): Boolean; begin result := false; with TEquipmentCommandForm.Create(Application) do try dsGC.ParamByName('CID').AsInteger := C_ID; dsGC.Open; if C_ID = -1 then dsGC.Insert else dsGC.Edit; // eACCOUNT_NO.Enabled := (EditMode = 0); if ShowModal = mrOk then begin result := true; if (dsGC.State in [dsEdit, dsInsert]) then dsGC.Post; end else if (dsGC.State in [dsEdit, dsInsert]) then dsGC.Cancel; finally free end; end; procedure TEquipmentCommandForm.cbTypeChange(Sender: TObject); begin try pnlURL.Visible := (cbType.Value = 2); except pnlURL.Visible := false; end; end; procedure TEquipmentCommandForm.FormClose(Sender: TObject; var Action: TCloseAction); begin dsGroup.Close; end; procedure TEquipmentCommandForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then okcnclfrm1bbOkClick(Sender); end; procedure TEquipmentCommandForm.FormShow(Sender: TObject); var NewItem: TMenuItem; begin pmMemo.Items.Clear; NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanUserEquipment; NewItem.Hint := '<e_admin>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanPasswordEquipment; NewItem.Hint := '<e_pass>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanIPEquipment; NewItem.Hint := '<e_ip>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACEquipment; NewItem.Hint := '<e_mac>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACEquipmentH; NewItem.Hint := '<e_mac_h>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACEquipmentD; NewItem.Hint := '<e_mac_d>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACEquipmentJun; NewItem.Hint := '<e_mac_j>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanIPCustomer; NewItem.Hint := '<c_ip>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACCustomer; NewItem.Hint := '<c_mac>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACCustomerH; NewItem.Hint := '<c_mac_h>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACCustomerD; NewItem.Hint := '<c_mac_d>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanMACCustomerJun; NewItem.Hint := '<c_mac_j>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanPortCustomer; NewItem.Hint := '<c_port>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanVLANCustomer; NewItem.Hint := '<c_vlan>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanTAGCustomer; NewItem.Hint := '<c_tag>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanTAGSTRCustomer; NewItem.Hint := '<c_tagstr>'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); NewItem := TMenuItem.Create(pmMemo); NewItem.Caption := rsLanTelnetWait; NewItem.Hint := 'wait'; NewItem.OnClick := IP1Click; pmMemo.Items.Add(NewItem); dsGroup.Open; end; procedure TEquipmentCommandForm.IP1Click(Sender: TObject); begin if (Sender is TMenuItem) and (ActiveControl is TDBMemoEh) then (ActiveControl as TDBMemoEh).SelText := (Sender as TMenuItem).Hint; end; procedure TEquipmentCommandForm.okcnclfrm1bbOkClick(Sender: TObject); begin okcnclfrm1.actExitExecute(Sender); end; end.
unit CommonHeader; interface uses fmx.Graphics, fmxJabberClient, sysutils, system.IOUtils, FMX.Dialogs; var GJabberClient : TfmxJabberClient; function GetImageFilename(AName : string) : string; implementation {------------------------------------------------------------------------------- Procedure: GetImageFilename : Return the fullname(path+name) of an image depending on the target OS Arguments: AName : string Result: string // TODO : Add copatibility with OSX and IOS -------------------------------------------------------------------------------} function GetImageFilename(AName : string) : string; begin {$IFDEF ANDROID} Result := TPath.Combine(TPath.GetHomePath(),AName) {$ELSE} Result := ExtractFilepath(ParamStr(0))+AName; {$ENDIF} end; initialization GJabberClient := TfmxJabberClient.Create(nil); // Create Jaber client finalization GJabberClient.Free; end.
unit logger; { $Id: logger.pas,v 1.2 2006/11/26 16:58:04 savage Exp $ } {******************************************************************************} { } { Error Logging Unit } { } { The initial developer of this Pascal code was : } { Dominique Louis <Dominique@SavageSoftware.com.au> } { } { Portions created by Dominique Louis are } { Copyright (C) 2000 - 2001 Dominique Louis. } { } { } { } { Contributor(s) } { -------------- } { } { } { Obtained through: } { Joint Endeavour of Delphi Innovators ( Project JEDI ) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { 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. } { } { Description } { ----------- } { Logging functions... } { } { } { Requires } { -------- } { SDL.dll on Windows platforms } { libSDL-1.1.so.0 on Linux platform } { } { Programming Notes } { ----------------- } { } { } { } { } { Revision History } { ---------------- } { 2001 - DL : Initial creation } { 25/10/2001 - DRE : Added $M+ directive to allow published } { in classes. Added a compile directive } { around fmShareExclusive as this does not } { exist in Free Pascal } { } {******************************************************************************} { $Log: logger.pas,v $ Revision 1.2 2006/11/26 16:58:04 savage Modifed to create separate log files. Therefore each instance running from the same directory will have their own individual log file, prepended with a number. Revision 1.1 2004/02/05 00:08:20 savage Module 1.0 release } {$I jedi-sdl.inc} {$WEAKPACKAGEUNIT OFF} interface uses Classes, SysUtils; type TLogger = class private FFileHandle : TextFile; FApplicationName : string; FApplicationPath : string; protected public constructor Create; destructor Destroy; override; function GetApplicationName: string; function GetApplicationPath: string; procedure LogError( ErrorMessage : string; Location : string ); procedure LogWarning( WarningMessage : string; Location : string ); procedure LogStatus( StatusMessage : string; Location : string ); // published property ApplicationName : string read GetApplicationName; property ApplicationPath : string read GetApplicationPath; end; var Log : TLogger; implementation { TLogger } constructor TLogger.Create; var FileName : string; FileNo : integer; begin FApplicationName := ExtractFileName( ParamStr(0) ); FApplicationPath := ExtractFilePath( ParamStr(0) ); FileName := FApplicationPath + ChangeFileExt( FApplicationName, '.log' ); FileNo := 0; while FileExists( FileName ) do begin inc( FileNo ); FileName := FApplicationPath + IntToStr( FileNo ) + ChangeFileExt( FApplicationName, '.log' ) end; AssignFile( FFileHandle, FileName ); ReWrite( FFileHandle ); (*inherited Create( FApplicationPath + ChangeFileExt( FApplicationName, '.log' ), fmCreate {$IFNDEF FPC}or fmShareExclusive{$ENDIF} );*) end; destructor TLogger.Destroy; begin CloseFile( FFileHandle ); inherited; end; function TLogger.GetApplicationName: string; begin result := FApplicationName; end; function TLogger.GetApplicationPath: string; begin result := FApplicationPath; end; procedure TLogger.LogError(ErrorMessage, Location: string); var S : string; begin S := '*** ERROR *** : @ ' + TimeToStr(Time) + ' MSG : ' + ErrorMessage + ' IN : ' + Location + #13#10; WriteLn( FFileHandle, S ); Flush( FFileHandle ); end; procedure TLogger.LogStatus(StatusMessage, Location: string); var S : string; begin S := 'STATUS INFO : @ ' + TimeToStr(Time) + ' MSG : ' + StatusMessage + ' IN : ' + Location + #13#10; WriteLn( FFileHandle, S ); Flush( FFileHandle ); end; procedure TLogger.LogWarning(WarningMessage, Location: string); var S : string; begin S := '=== WARNING === : @ ' + TimeToStr(Time) + ' MSG : ' + WarningMessage + ' IN : ' + Location + #13#10; WriteLn( FFileHandle, S ); Flush( FFileHandle ); end; initialization begin Log := TLogger.Create; Log.LogStatus( 'Starting Application', 'Initialization' ); end; finalization begin Log.LogStatus( 'Terminating Application', 'Finalization' ); Log.Free; Log := nil; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. $Log$ Rev 1.10 2/22/2004 12:04:00 AM JPMugaas Updated for file rename. Rev 1.9 2/12/2004 11:28:04 PM JPMugaas Modified compression intercept to use the ZLibEx unit. Rev 1.8 2004.02.09 9:56:00 PM czhower Fixed for lib changes. Rev 1.7 5/12/2003 12:31:00 AM GGrieve Get compiling again with DotNet Changes Rev 1.6 10/12/2003 1:49:26 PM BGooijen Changed comment of last checkin Rev 1.5 10/12/2003 1:43:24 PM BGooijen Changed IdCompilerDefines.inc to Core\IdCompilerDefines.inc Rev 1.3 6/27/2003 2:38:04 PM BGooijen Fixed bug where last part was not compressed/send Rev 1.2 4/10/2003 4:12:42 PM BGooijen Added TIdServerCompressionIntercept Rev 1.1 4/3/2003 2:55:48 PM BGooijen Now calls DeinitCompressors on disconnect Rev 1.0 11/14/2002 02:15:50 PM JPMugaas } unit IdCompressionIntercept; { This file implements an Indy intercept component that compresses a data stream using the open-source zlib compression library. In order for this file to compile on Windows, the follow .obj files *must* be provided as delivered with this file: deflate.obj inflate.obj inftrees.obj trees.obj adler32.obj infblock.obj infcodes.obj infutil.obj inffast.obj On Linux, the shared-object file libz.so.1 *must* be available on the system. Most modern Linux distributions include this file. Simply set the CompressionLevel property to a value between 1 and 9 to enable compressing of the data stream. A setting of 0(zero) disables compression and the component is dormant. The sender *and* received must have compression enabled in order to properly decompress the data stream. They do *not* have to use the same CompressionLevel as long as they are both set to a value between 1 and 9. Original Author: Allen Bauer This source file is submitted to the Indy project on behalf of Borland Sofware Corporation. No warranties, express or implied are given with this source file. } interface {$I IdCompilerDefines.inc} uses Classes, IdCTypes, IdException, IdGlobal, IdGlobalProtocols, IdIntercept, IdTCPClient, IdTCPConnection, IdZLibHeaders, IdZLib; type EIdCompressionException = class(EIdException); EIdCompressorInitFailure = class(EIdCompressionException); EIdDecompressorInitFailure = class(EIdCompressionException); EIdCompressionError = class(EIdCompressionException); EIdDecompressionError = class(EIdCompressionException); TIdCompressionLevel = 0..9; TIdCompressionIntercept = class(TIdConnectionIntercept) protected FCompressionLevel: TIdCompressionLevel; FCompressRec: TZStreamRec; FDecompressRec: TZStreamRec; FRecvBuf: TIdBytes; FRecvCount, FRecvSize: TIdC_UINT; FSendBuf: TIdBytes; FSendCount, FSendSize: TIdC_UINT; procedure SetCompressionLevel(Value: TIdCompressionLevel); procedure InitCompressors; procedure DeinitCompressors; public destructor Destroy; override; procedure Disconnect; override; procedure Receive(var VBuffer: TIdBytes); override; procedure Send(var VBuffer: TIdBytes); override; published property CompressionLevel: TIdCompressionLevel read FCompressionLevel write SetCompressionLevel; end; TIdServerCompressionIntercept = class(TIdServerIntercept) protected FCompressionLevel: TIdCompressionLevel; public procedure Init; override; function Accept(AConnection: TComponent): TIdConnectionIntercept; override; published property CompressionLevel: TIdCompressionLevel read FCompressionLevel write FCompressionLevel; end; implementation uses IdResourceStringsProtocols, IdExceptionCore; { TIdCompressionIntercept } procedure TIdCompressionIntercept.DeinitCompressors; begin if Assigned(FCompressRec.zalloc) then begin deflateEnd(FCompressRec); FillChar(FCompressRec, SizeOf(FCompressRec), 0); end; if Assigned(FDecompressRec.zalloc) then begin inflateEnd(FDecompressRec); FillChar(FDecompressRec, SizeOf(FDecompressRec), 0); end; end; destructor TIdCompressionIntercept.Destroy; begin DeinitCompressors; SetLength(FRecvBuf, 0); SetLength(FSendBuf, 0); inherited Destroy; end; procedure TIdCompressionIntercept.Disconnect; begin inherited Disconnect; DeinitCompressors; end; procedure TIdCompressionIntercept.InitCompressors; begin if not Assigned(FCompressRec.zalloc) then begin FCompressRec.zalloc := IdZLibHeaders.zlibAllocMem; FCompressRec.zfree := IdZLibHeaders.zlibFreeMem; if deflateInit_(FCompressRec, FCompressionLevel, zlib_Version, SizeOf(FCompressRec)) <> Z_OK then begin EIdCompressorInitFailure.Toss(RSZLCompressorInitializeFailure); end; end; if not Assigned(FDecompressRec.zalloc) then begin FDecompressRec.zalloc := IdZLibHeaders.zlibAllocMem; FDecompressRec.zfree := IdZLibHeaders.zlibFreeMem; if inflateInit_(FDecompressRec, zlib_Version, SizeOf(FDecompressRec)) <> Z_OK then begin EIdDecompressorInitFailure.Toss(RSZLDecompressorInitializeFailure); end; end; end; procedure TIdCompressionIntercept.Receive(var VBuffer: TIdBytes); var LBuffer: TIdBytes; LPos : integer; nChars, C : TIdC_UINT; StreamEnd: Boolean; begin // let the next Intercept in the chain decode its data first inherited Receive(VBuffer); SetLength(LBuffer, 2048); if FCompressionLevel in [1..9] then begin InitCompressors; StreamEnd := False; LPos := 0; repeat nChars := IndyMin(Length(VBuffer) - LPos, Length(LBuffer)); if nChars = 0 then begin Break; end; CopyTIdBytes(VBuffer, LPos, LBuffer, 0, nChars); Inc(LPos, nChars); FDecompressRec.next_in := PAnsiChar(@LBuffer[0]); FDecompressRec.avail_in := nChars; FDecompressRec.total_in := 0; while FDecompressRec.avail_in > 0 do begin if FRecvCount = FRecvSize then begin if FRecvSize = 0 then begin FRecvSize := 2048; end else begin Inc(FRecvSize, 1024); end; SetLength(FRecvBuf, FRecvSize); end; FDecompressRec.next_out := PAnsiChar(@FRecvBuf[FRecvCount]); C := FRecvSize - FRecvCount; FDecompressRec.avail_out := C; FDecompressRec.total_out := 0; case inflate(FDecompressRec, Z_NO_FLUSH) of Z_STREAM_END: StreamEnd := True; Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR: EIdDecompressionError.Toss(RSZLDecompressionError); end; Inc(FRecvCount, C - FDecompressRec.avail_out); end; until StreamEnd; SetLength(VBuffer, FRecvCount); CopyTIdBytes(FRecvBuf, 0, VBuffer, 0, FRecvCount); FRecvCount := 0; end; end; procedure TIdCompressionIntercept.Send(var VBuffer: TIdBytes); var LBuffer: TIdBytes; LLen, LSize: TIdC_UINT; begin LBuffer := nil; if FCompressionLevel in [1..9] then begin InitCompressors; // Make sure the Send buffer is large enough to hold the input data LSize := Length(VBuffer); if LSize > FSendSize then begin if LSize > 2048 then begin FSendSize := LSize + (LSize + 1023) mod 1024; end else begin FSendSize := 2048; end; SetLength(FSendBuf, FSendSize); end; // Get the data from the input and save it off // TODO: get rid of FSendBuf and use ABuffer directly FSendCount := LSize; CopyTIdBytes(VBuffer, 0, FSendBuf, 0, FSendCount); FCompressRec.next_in := PAnsiChar(@FSendBuf[0]); FCompressRec.avail_in := FSendCount; FCompressRec.avail_out := 0; // clear the output stream in preparation for compression SetLength(VBuffer, 0); SetLength(LBuffer, 1024); // As long as data is being outputted, keep compressing while FCompressRec.avail_out = 0 do begin FCompressRec.next_out := PAnsiChar(@LBuffer[0]); FCompressRec.avail_out := Length(LBuffer); case deflate(FCompressRec, Z_SYNC_FLUSH) of Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR: raise EIdCompressionError.Create(RSZLCompressionError); end; // Place the compressed data into the output stream LLen := Length(VBuffer); SetLength(VBuffer, LLen + TIdC_UINT(Length(LBuffer)) - FCompressRec.avail_out); CopyTIdBytes(LBuffer, 0, VBuffer, LLen, TIdC_UINT(Length(LBuffer)) - FCompressRec.avail_out); end; end; // let the next Intercept in the chain encode its data next inherited Send(VBuffer); end; procedure TIdCompressionIntercept.SetCompressionLevel(Value: TIdCompressionLevel); begin if Value < 0 then begin Value := 0; end else if Value > 9 then begin Value := 9; end; if Value <> FCompressionLevel then begin DeinitCompressors; FCompressionLevel := Value; end; end; { TIdServerCompressionIntercept } procedure TIdServerCompressionIntercept.Init; begin end; function TIdServerCompressionIntercept.Accept(AConnection: TComponent): TIdConnectionIntercept; begin Result := TIdCompressionIntercept.Create(nil); TIdCompressionIntercept(Result).CompressionLevel := CompressionLevel; end; end.
unit StdTaxes; interface uses Taxes, BasicTaxes; procedure RegisterTaxes; procedure RegisterTaxesToAccounts; implementation uses Kernel, ClassStorage, Accounts, BasicAccounts, SysUtils, Collection; procedure RegisterTaxesToAccounts; var count : integer; i : integer; MA : TMetaAccount; ToTax : TCollection; begin try count := TheClassStorage.ClassCount[tidClassFamily_Accounts]; except count := 0; end; ToTax := TCollection.Create( count, rkUse ); try for i := 0 to pred(count) do try MA := TMetaAccount(TheClassStorage.ClassByIdx[tidClassFamily_Accounts, i]); if MA.Taxable then ToTax.Insert( MA ); except raise Exception.Create( IntToStr(i) ); end; for i := 0 to pred(ToTax.Count) do begin MA := TMetaAccount(ToTax[i]); with TMetaTaxToAccount.Create( MA.Id, MA.AccId, TTaxToAccount ) do begin Register( tidClassFamily_Taxes ); end; end; finally ToTax.Free; end; end; procedure RegisterTaxes; begin with TMetaAccount.Create( accIdx_Taxes, accIdx_Special, 'Taxes', '', TAccount ) do begin TaxAccount := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_LandTax, accIdx_Taxes, 'Land Tax', '', TAccount ) do begin TaxAccount := true; Register( tidClassFamily_Accounts ); end; end; end.
(**************************************************) (* *) (* 本单元用于爬取网易音乐 *) (* *) (* Copyright (c) 2019 *) (* 南烛 *) (* *) (**************************************************) //方法: //1、Key_Word传入歌名或歌手名关键字 //2、Num传入搜索数量 //3、执行线程开始搜索并添加到NextGrid unit Music_163_Spider; interface uses System.Classes, system.sysutils, IdHTTP, IdIOHandlerSocket, superobject, JDAESExtend, Winapi.Windows, MSGs, VMsgMonitor; type Get_163_Info = class(TTHread) private const UserAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3408.400 QQBrowser/9.6.12028.400'; skey = 'a8dfcd22f776d072cde96b0bc309dc8e845d0a145b11f5e02d1144e61e619aedd3c4ee2a1774b5e998c6e3f85a3ae64a1defc66e4896aa92decd9e132a20a413819509abc0552' + 'f3b1885340f4eaa0ac2f19239f197a41120747205082b77c944e9541fc67a6fc6f7e5c770923748f5b4f48d55be9585bd930918b92888a9102b'; OnceKey = '0CoJUm6Qyw8W8jud'; Music_Post = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='; MV_Post = 'https://music.163.com/weapi/song/enhance/play/mv/url?csrf_token='; var // S_Type: Integer; //搜索类型,0为歌曲。1为MV。2为列表 // M_Type: Integer; //MV的清晰度,输入240,480,720,,1080 WY163: Word; // 搜索结果计数 public var HTTP: TIdHTTP; SSL: TIdIOHandlerSocket; Key_Word: string; //搜索关键字 Num: integer; //搜索数量 constructor Create(S_Key_Word: string; S_Num: Integer); overload; //构造函数 protected function AES_Params(i: integer; Video_HD: Integer; str: string): string; //根据需要的内容获取对应的POST参数,返回值为params function Post(url, params: string): string; //根据POST接口地址和POST内容获取返回值,返回值为JOSN function JO_Song_ID(jo_str: string): TStringList; //解析JSON获取歌曲ID列表 function JO_SOng_Time(jo_str: string): TStringList; //解析JSON获取歌曲时长列表 procedure Execute; override; end; implementation uses System.NetEncoding, Main; { Get_163_Info } procedure Get_163_Info.Execute; var(*线程内执行*) Params_Str: string; str163: string; jo163, item163: Isuperobject; // 网易音乐API Time_Ls: TStringList; // 网易数据列表 vMsg: TSearch_163_Song_MSG; begin FreeOnTerminate := true; OnTerminate := Fm_Main.Search_Over; WY163 := 0; Time_Ls := TStringList.Create; // 网易时间列表 Params_Str := AES_Params(2, 720, Key_Word); //搜索获得歌曲列表的Params str163 := Post('http://music.163.com/weapi/cloudsearch/get/web?csrf_token=', Params_Str); jo163 := SO(str163); Time_Ls.Assign(JO_Song_TIME(str163)); // 网易音乐下载地址获取 for item163 in jo163['result.songs'] do begin vMsg := TSearch_163_Song_MSG.Create; vMsg.Song_Name := jo163['result.songs[' + inttostr(WY163) + '].name'].AsString; // 歌名 vMsg.Song_Album := jo163['result.songs[' + inttostr(WY163) + '].al.name'].AsString; // 专辑名 vMsg.Song_Singer := jo163['result.songs[' + inttostr(WY163) + '].ar[0].name'].AsString; // 歌手名 vMsg.Song_Time := inttostr(Trunc(strtofloat(Time_Ls[WY163]) / 1000)); //时长秒 vMsg.Song_From := '2'; vMsg.Song_Img := jo163['result.songs[' + inttostr(WY163) + '].al.picUrl'].AsString; // 图片 vMsg.Song_ID := jo163['result.songs[' + inttostr(WY163) + '].id'].AsString; // ID vMsg.Song_AlbumID := jo163['result.songs[' + inttostr(WY163) + '].al.id'].AsString; //专辑ID vMsg.Song_SingerID := jo163['result.songs[' + inttostr(WY163) + '].ar[0].id'].AsString; //歌手ID vMsg.Song_MVID := jo163['result.songs[' + inttostr(WY163) + '].mv'].AsString; //歌MV_ID vMsg.Song_Lrc := ''; GlobalVMsgMonitor.PostVMsg(vMsg); //发送消息 inc(WY163); end; // Url_Ls.Free; Time_Ls.Free; end; function Get_163_Info.AES_Params(i: integer; Video_HD: Integer; str: string): string; var (*根据需要的内容获取对应的POST参数,返回值为2次加密后的params*) OneceEncode: string; TwiceEncode: string; strx: string; begin case i of 0: begin //post获取的歌曲id列表 strx := '{"ids":"[' + str + ']","br":128000,"csrf_token":""}'; end; 1: begin //post获取的视频id列表 strx := '{"id":"' + str + '","r":"' + inttostr(Video_HD) + '","csrf_token":""}'; end; 2: begin //post获取搜索歌名得到的歌曲列表 strx := '{"hlpretag":"<span class=\"s-fc7\">","hlposttag":"</span>","s":"' + str + '","type":"1","offset":"0","total":"true","limit":"' + inttostr(NUM) + '","csrf_token":""}'; end; end; OneceEncode := string(EncryptString(AnsiString(strx), OnceKey, kb128, amCBC, PKCS5Padding, '0102030405060708', ctBase64)); //第一次AES加密 OneceEncode := stringreplace(OneceEncode, #13#10, '', [rfReplaceall]); TwiceEncode := string(EncryptString(AnsiString(OneceEncode), 'svoXIdz7ZwOI1bXm', kb128, amCBC, PKCS5Padding, '0102030405060708', ctBase64)); //第二次AES加密 TwiceEncode := stringreplace(TwiceEncode, #13#10, '', [rfReplaceall]); result := TNetEncoding.URL.Encode(UTF8Encode(TwiceEncode)); end; constructor Get_163_Info.Create(S_Key_Word: string; S_Num: Integer); begin Key_Word := S_Key_Word; //搜索关键字 Num := S_Num; //搜索数量 inherited Create(false); end; function Get_163_Info.JO_Song_ID(jo_str: string): TStringList; var(*解析JSON获取歌曲ID,返回值为歌曲ID列表*) jo163, item163: Isuperobject; // 网易音乐API jo_music: Isuperobject; // 下载地址 ct163: Integer; begin ct163 := 0; result := TStringList.Create; jo163 := so(jo_str); try for item163 in jo163['result.songs'] do begin jo_music := SO(Post(Music_Post, AES_Params(0, 0, jo163['result.songs[' + inttostr(ct163) + '].id'].AsString))); result.Add(jo_music['data[0].url'].AsString); inc(ct163); end; except begin //不做任何事 end; end; end; function Get_163_Info.JO_SOng_Time(jo_str: string): TStringList; var (*解析JSON获取歌曲时长,返回值为歌曲时长列表*) jo163, item163: Isuperobject; ct163: Integer; begin ct163 := 0; result := TStringList.Create; jo163 := so(jo_str); try for item163 in jo163['result.songs'] do begin result.Add(jo163['result.songs[' + inttostr(ct163) + '].dt'].AsString); inc(ct163); end; except begin //不做任何事 end; end; end; function Get_163_Info.Post(url, params: string): string; var (*根据POST接口地址和POST内容获取返回值,返回值为JOSN*) st, stb: tstringstream; begin HTTP := TIdHTTP.Create(nil); SSL := TIdIOHandlerSocket(nil); HTTP.IOHandler := SSL; st := tstringstream.Create; stb := tstringstream.Create('', tencoding.UTF8); st.WriteString('params=' + params + '&encSecKey=' + skey); HTTP.Request.ContentType := 'application/x-www-form-urlencoded'; HTTP.Request.UserAgent := UserAgent; HTTP.Request.Referer := 'http://music.163.com/'; HTTP.post(url, st, stb); result := stb.DataString; st.free; stb.free; HTTP.Free; SSL.Free; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit AreasVenta; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QMenus, QTypes, QcurrEdit, QGrids, QDBGrids, Inifiles, QButtons; type TfrmAreasVenta = class(TForm) btnInsertar: TBitBtn; btnEliminar: TBitBtn; btnModificar: TBitBtn; btnGuardar: TBitBtn; btnCancelar: TBitBtn; gddListado: TDBGrid; lblRegistros: TLabel; txtRegistros: TcurrEdit; grpDatos: TGroupBox; Label1: TLabel; txtNombre: TEdit; MainMenu1: TMainMenu; Archivo1: TMenuItem; mnuInsertar: TMenuItem; mnuEliminar: TMenuItem; mnuModificar: TMenuItem; N3: TMenuItem; mnuGuardar: TMenuItem; mnuCancelar: TMenuItem; N2: TMenuItem; Salir1: TMenuItem; mnuConsulta: TMenuItem; mnuAvanza: TMenuItem; mnuRetrocede: TMenuItem; Label2: TLabel; txtCaja: TcurrEdit; procedure FormShow(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnInsertarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure btnEliminarClick(Sender: TObject); procedure btnModificarClick(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure mnuAvanzaClick(Sender: TObject); procedure mnuRetrocedeClick(Sender: TObject); procedure FormCreate(Sender: TObject); private sModo:String; iClave:Integer; procedure RecuperaConfig; procedure LimpiaDatos; procedure Listar; procedure ActivaControles; procedure RecuperaDatos; procedure GuardaDatos; function VerificaIntegridad:boolean; function VerificaDatos:boolean; public end; var frmAreasVenta: TfrmAreasVenta; implementation uses dm; {$R *.xfm} procedure TfrmAreasVenta.FormShow(Sender: TObject); begin btnCancelarClick(Sender); end; procedure TfrmAreasVenta.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('AreasVenta', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('AreasVenta', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmAreasVenta.btnCancelarClick(Sender: TObject); begin sModo := 'Consulta'; LimpiaDatos; Listar; ActivaControles; Height := 220; btnInsertar.SetFocus; end; procedure TfrmAreasVenta.LimpiaDatos; begin txtNombre.Clear; txtCaja.Value:=0; end; procedure TfrmAreasVenta.Listar; var sBM : String; begin with dmDatos.qryListados do begin sBM := dmDatos.cdsCliente.Bookmark; dmDatos.cdsCliente.Active := false; Close; SQL.Clear; SQL.Add('SELECT clave, nombre, caja FROM AreasVenta ORDER BY nombre'); Open; dmDatos.cdsCliente.Active := true; dmDatos.cdsCliente.FieldByName('clave').Visible := false; dmDatos.cdsCliente.FieldByName('nombre').DisplayLabel := 'Área de Venta'; dmDatos.cdsCliente.FieldByName('caja').DisplayLabel := 'Caja'; dmDatos.cdsCliente.FieldByName('nombre').DisplayWidth := 13; dmDatos.cdsCliente.FieldByName('caja').DisplayWidth := 6; txtRegistros.Value := dmDatos.cdsCliente.RecordCount; try dmDatos.cdsCliente.Bookmark := sBM; except txtRegistros.Value := txtRegistros.Value; end; end; RecuperaDatos; end; procedure TfrmAreasVenta.ActivaControles; begin if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin btnInsertar.Enabled := false; btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuInsertar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; btnGuardar.Enabled := true; btnCancelar.Enabled := true; mnuGuardar.Enabled := true; mnuCancelar.Enabled := true; mnuConsulta.Enabled := false; txtNombre.ReadOnly := false; txtNombre.TabStop := true; txtCaja.ReadOnly := False; txtCaja.TabStop := True; end; if(sModo = 'Consulta') then begin btnInsertar.Enabled := true; mnuInsertar.Enabled := true; if(txtRegistros.Value > 0) then begin btnModificar.Enabled := true; btnEliminar.Enabled := true; mnuModificar.Enabled := true; mnuEliminar.Enabled := true; end else begin btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; end; btnGuardar.Enabled := false; btnCancelar.Enabled := false; mnuGuardar.Enabled := false; mnuCancelar.Enabled := false; mnuConsulta.Enabled := true; txtNombre.ReadOnly := true; txtNombre.TabStop := false; txtCaja.ReadOnly := true; txtCaja.TabStop := false; end; end; procedure TfrmAreasVenta.RecuperaDatos; begin with dmDatos.cdsCliente do begin if(Active) then begin iClave := FieldByName('Clave').AsInteger; txtNombre.Text := Trim(FieldByName('Nombre').AsString); txtCaja.Value := FieldByName('Caja').AsInteger; end; end; end; procedure TfrmAreasVenta.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('AreasVenta', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('AreasVenta', 'Posx', IntToStr(Left)); Free; end; dmDatos.qryListados.Close; dmDatos.cdsCliente.Active := false; end; procedure TfrmAreasVenta.btnInsertarClick(Sender: TObject); begin limpiaDatos; sModo := 'Insertar'; Height := 320; ActivaControles; txtNombre.SetFocus; end; procedure TfrmAreasVenta.btnGuardarClick(Sender: TObject); begin if(VerificaDatos) then begin GuardaDatos; btnCancelarClick(Sender); end; end; function TfrmAreasVenta.VerificaDatos:boolean; var bRegreso : boolean; begin btnGuardar.SetFocus; bRegreso := true; if(Length(txtNombre.Text) = 0) then begin Application.MessageBox('Introduce el nombre del área de venta','Error',[smbOK],smsCritical); txtNombre.SetFocus; bRegreso := false; end else if(not VerificaIntegridad) then bRegreso := false; Result := bRegreso; end; function TfrmAreasVenta.VerificaIntegridad:boolean; var bRegreso : boolean; begin bRegreso := true; with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT * FROM areasventa WHERE nombre = ''' + txtNombre.Text + ''''); Open; if(not Eof) and ((sModo = 'Insertar') or ((FieldByName('clave').AsInteger <> iClave) and (sModo = 'Modificar'))) then begin bRegreso := false; Application.MessageBox('El área de venta ya existe','Error',[smbOK],smsCritical); txtNombre.SetFocus; end; Close; end; Result := bRegreso; end; procedure TfrmAreasVenta.GuardaDatos; var sCaja : String; begin if(txtCaja.Value = 0) then sCaja := 'null' else sCaja := FloatToStr(txtCaja.Value); if(sModo = 'Insertar') then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('INSERT INTO areasventa (nombre, caja, fecha_umov) VALUES('); SQL.Add('''' + txtNombre.Text + ''',' + sCaja + ',''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''')'); ExecSQL; Close; end; end else begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('UPDATE areasventa SET nombre = ''' + txtNombre.Text + ''','); SQL.Add('caja = ' + sCaja + ', fecha_umov = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''''); SQL.Add('WHERE clave = ' + IntToStr(iClave)); ExecSQL; Close; end; end; end; procedure TfrmAreasVenta.btnEliminarClick(Sender: TObject); begin if(Application.MessageBox('Se eliminará el área de venta seleccionada','Eliminar',[smbOK]+[smbCancel]) = smbOK) then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM areasventa WHERE clave = ' + dmDatos.cdsCliente.FieldByName('clave').AsString); ExecSQL; Close; end; btnCancelarClick(Sender); end; end; procedure TfrmAreasVenta.btnModificarClick(Sender: TObject); begin if(txtRegistros.Value > 0) then begin sModo := 'Modificar'; RecuperaDatos; ActivaControles; Height := 320; txtNombre.SetFocus; end; end; procedure TfrmAreasVenta.Salir1Click(Sender: TObject); begin Close; end; procedure TfrmAreasVenta.mnuAvanzaClick(Sender: TObject); begin dmDatos.cdsCliente.Next; end; procedure TfrmAreasVenta.mnuRetrocedeClick(Sender: TObject); begin dmDatos.cdsCliente.Prior; end; procedure TfrmAreasVenta.FormCreate(Sender: TObject); begin RecuperaConfig; end; end.
unit StdReporters; interface uses News; type TCrimeHi = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TCrimeLo = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; THealthHi = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; THealthLo = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TSchoolHi = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TSchoolLo = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TOverempHiClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TOverempMidClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TOverempLoClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TUnempHiClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TUnempMidClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TUnempLoClass = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; end; TBoardMessage = class( TMetaReporter ) protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; public function RenderStory( StoryReqs : TStoryReqs; Newspaper : TNewspaper; Reporter : TReporter ) : THTML; override; end; procedure RegisterReporters; implementation uses SysUtils, ComObj, Protocol; function TCrimeHi.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covPolice', '0', aNewspaper )) < 80 then result := 100 - StrToInt(SolveSymbol( 'Town.covPolice', '0', aNewspaper )) else result := 0; end; function TCrimeLo.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covPolice', '0', aNewspaper )) > 95 then result := 10 else result := 0; end; function THealthHi.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covHealth', '0', aNewspaper )) > 95 then result := 10 else result := 0; end; function THealthLo.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covHealth', '100', aNewspaper )) < 80 then result := 100 - StrToInt(SolveSymbol( 'Town.covHealth', '100', aNewspaper )) else result := 0; end; function TSchoolHi.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covSchool', '0', aNewspaper )) > 95 then result := 10 else result := 0; end; function TSchoolLo.StoryStrength( aNewspaper : TNewspaper ) : integer; begin if StrToInt(SolveSymbol( 'Town.covSchool', '100', aNewspaper )) < 80 then result := 100 - StrToInt(SolveSymbol( 'Town.covSchool', '100', aNewspaper )) else result := 0; end; function TOverempHiClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var WorkDemand : integer; Population : integer; begin WorkDemand := StrToInt(SolveSymbol( 'Town.hiWorkDemand', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.hiPopulation', '0', aNewspaper )); if (Population > 0) and (WorkDemand/Population > 0.05) then result := round(1000*WorkDemand/Population) else result := 0; end; function TOverempMidClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var WorkDemand : integer; Population : integer; begin WorkDemand := StrToInt(SolveSymbol( 'Town.midWorkDemand', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.midPopulation', '0', aNewspaper )); if (Population > 0) and (WorkDemand/Population > 0.05) then result := round(1000*WorkDemand/Population) else result := 0; end; function TOverempLoClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var WorkDemand : integer; Population : integer; begin WorkDemand := StrToInt(SolveSymbol( 'Town.loWorkDemand', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.loPopulation', '0', aNewspaper )); if (Population > 0) and (WorkDemand/Population > 0.05) then result := round(1000*WorkDemand/Population) else result := 0; end; function TUnempHiClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var Unemployment : integer; Population : integer; begin Unemployment := StrToInt(SolveSymbol( 'Town.hiUnemployment', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.hiPopulation', '0', aNewspaper )); if (Population > 150) and (Unemployment > 5) then result := 10*Unemployment else result := 0; end; function TUnempMidClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var Unemployment : integer; Population : integer; begin Unemployment := StrToInt(SolveSymbol( 'Town.midUnemployment', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.midPopulation', '0', aNewspaper )); if (Population > 150) and (Unemployment > 5) then result := 10*Unemployment else result := 0; end; function TUnempLoClass.StoryStrength( aNewspaper : TNewspaper ) : integer; var Unemployment : integer; Population : integer; begin Unemployment := StrToInt(SolveSymbol( 'Town.loUnemployment', '0', aNewspaper )); Population := StrToInt(SolveSymbol( 'Town.loPopulation', '0', aNewspaper )); if (Population > 150) and (Unemployment > 5) then result := 10*Unemployment else result := 0; end; function TBoardMessage.StoryStrength( aNewspaper : TNewspaper ) : integer; begin result := 50 + random(90); end; function TBoardMessage.RenderStory( StoryReqs : TStoryReqs; Newspaper : TNewspaper; Reporter : TReporter ) : THTML; function GetSample( source : string; out trucated : boolean ) : string; const MaxLength = 300; var i : integer; finish : boolean; begin result := ''; finish := false; i := 1; while (i <= length(source)) and (length(result) < MaxLength + 10) and not finish do begin result := result + source[i]; case result[length(result)] of '.', ' ', '?', '!', ',', ';' : finish := length(result) > MaxLength - 10; end; inc( i ); end; trucated := i < length(source); end; var NewsObj : olevariant; rootpath : string; path : string; trunc : boolean; begin NewsObj := CreateOleObject( 'NewsBoard.NewsObject' ); rootpath := Newspaper.NewsCenter.NewsPath + tidPath_Boards + Newspaper.NewsCenter.Name + '\' + Newspaper.Name; NewsObj.SetRootPath( rootpath ); NewsObj.SetIndexSize( 10 ); path := NewsObj.GlobalMsgPath( Reporter.Lapse ); if (path <> '') and (NewsObj.Open( path ) = 0) then begin result := '<h<%= LayoutImp %>>' + LineBreak + NewsObj.Subject + LineBreak + '</h<%= LayoutImp %>>' + LineBreak + '<div class=author>' + LineBreak + ' by ' + NewsObj.Author + LineBreak + '</div>' + LineBreak + LineBreak + GetSample( NewsObj.BodyHTML, trunc ); result := result + LineBreak + '<a href="../../../../boardreader.asp?root=' + rootpath + '&path=' + path + '&tycoon=<%= Request("Tycoon") %>&PaperName=' + Newspaper.Name + '&WorldName=' + Newspaper.NewsCenter.Name + '&DAAddr=' + Newspaper.NewsCenter.DAAddr + '&DAPort=' + IntToStr(Newspaper.NewsCenter.DAPort) + '&TownName=' + Newspaper.Town + '">'; if trunc then result := result + '[>>]' else result := result + '[>>]'; result := result + '</a>'; end else result := '' end; // RegisterReporters procedure RegisterReporters; begin RegisterMetaReporterType( 'Misc', TMetaReporter ); RegisterMetaReporterType( 'CrimeLo', TCrimeLo ); RegisterMetaReporterType( 'CrimeHi', TCrimeHi ); RegisterMetaReporterType( 'HealthLo', THealthLo ); RegisterMetaReporterType( 'HealthHi', THealthHi ); RegisterMetaReporterType( 'SchoolLo', TSchoolLo ); RegisterMetaReporterType( 'SchoolHi', TSchoolHi ); RegisterMetaReporterType( 'OverempHiclass', TOverempHiclass ); RegisterMetaReporterType( 'OverempMidclass', TOverempMidclass ); RegisterMetaReporterType( 'OverempLoclass', TOverempLoclass ); RegisterMetaReporterType( 'UnempHiclass', TUnempHiclass ); RegisterMetaReporterType( 'UnempMidclass', TUnempMidclass ); RegisterMetaReporterType( 'UnempLoclass', TUnempLoclass ); RegisterMetaReporterType( 'BoardMessage', TBoardMessage ); end; end.
{ Date Created: 5/22/00 11:17:32 AM } unit InfoGROUPNAMESTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoGROUPNAMESRecord = record PIndex: Integer; PName: String[10]; End; TInfoGROUPNAMESBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoGROUPNAMESRecord end; TEIInfoGROUPNAMES = (InfoGROUPNAMESPrimaryKey, InfoGROUPNAMESByName); TInfoGROUPNAMESTable = class( TDBISAMTableAU ) private FDFIndex: TAutoIncField; FDFName: TStringField; procedure SetPName(const Value: String); function GetPName:String; procedure SetEnumIndex(Value: TEIInfoGROUPNAMES); function GetEnumIndex: TEIInfoGROUPNAMES; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoGROUPNAMESRecord; procedure StoreDataBuffer(ABuffer:TInfoGROUPNAMESRecord); property DFIndex: TAutoIncField read FDFIndex; property DFName: TStringField read FDFName; property PName: String read GetPName write SetPName; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoGROUPNAMES read GetEnumIndex write SetEnumIndex; end; { TInfoGROUPNAMESTable } procedure Register; implementation procedure TInfoGROUPNAMESTable.CreateFields; begin FDFIndex := CreateField( 'Index' ) as TAutoIncField; FDFName := CreateField( 'Name' ) as TStringField; end; { TInfoGROUPNAMESTable.CreateFields } procedure TInfoGROUPNAMESTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoGROUPNAMESTable.SetActive } procedure TInfoGROUPNAMESTable.Validate; begin { Enter Validation Code Here } end; { TInfoGROUPNAMESTable.Validate } procedure TInfoGROUPNAMESTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoGROUPNAMESTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoGROUPNAMESTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Index, AutoInc, 0, Y'); Add('Name, String, 10, Y'); end; end; procedure TInfoGROUPNAMESTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Index, Y, Y, N, N'); Add('ByName, Name, N, N, N, N'); end; end; procedure TInfoGROUPNAMESTable.SetEnumIndex(Value: TEIInfoGROUPNAMES); begin case Value of InfoGROUPNAMESPrimaryKey : IndexName := ''; InfoGROUPNAMESByName : IndexName := 'ByName'; end; end; function TInfoGROUPNAMESTable.GetDataBuffer:TInfoGROUPNAMESRecord; var buf: TInfoGROUPNAMESRecord; begin fillchar(buf, sizeof(buf), 0); buf.PIndex := DFIndex.Value; buf.PName := DFName.Value; result := buf; end; procedure TInfoGROUPNAMESTable.StoreDataBuffer(ABuffer:TInfoGROUPNAMESRecord); begin DFName.Value := ABuffer.PName; end; function TInfoGROUPNAMESTable.GetEnumIndex: TEIInfoGROUPNAMES; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoGROUPNAMESPrimaryKey; if iname = 'BYNAME' then result := InfoGROUPNAMESByName; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoGROUPNAMESTable, TInfoGROUPNAMESBuffer ] ); end; { Register } function TInfoGROUPNAMESBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PIndex; 2 : result := @Data.PName; end; end; end. { InfoGROUPNAMESTable }
unit uFuzzyMatching; // Fuzzy matching algorithm. // LICENSE: CC0, Creative Commons Zero, (public domain) // Returns if all characters of a given pattern are found in a string, and calculates a matching score // Applies case insensitive matching, although case can influcence the score // Based on the C++ version by Forrest Smith // Original source: https://github.com/forrestthewoods/lib_fts/blob/master/code/fts_fuzzy_match.h // Blog: https://www.forrestthewoods.com/blog/reverse_engineering_sublime_texts_fuzzy_match/ interface uses System.SysUtils, System.Character; type TMatch = Byte; TMatches = array[0..255] of TMatch; PMatch = ^TMatch; PMatches = ^TMatches; function FuzzyMatch(const Pattern: String; const Str: String; out Score: Integer): Boolean; overload; function FuzzyMatch(const Pattern: String; const Str: String; out Score: Integer; var Matches: TMatches): Boolean; overload; implementation function FuzzyMatchRecursive( Pattern: PChar; Str: PChar; out OutScore: Integer; const StrBegin: PChar; const SrcMatches: PMatches; const Matches: PMatches; const MaxMatches: Integer; NextMatch: Integer; RecursionCount: Integer; const RecursionLimit: Integer; MatchId: integer): Boolean; const sequential_bonus: Integer = 15; // bonus for adjacent matches separator_bonus: Integer = 30; // bonus if match occurs after a separator camel_bonus: Integer = 30; // bonus if match is uppercase and prev is lower first_letter_bonus: Integer = 15; // bonus if the first letter is matched first_letter_count: Integer = 1; // How many letters count as 'first'. Try setting to 2 to skip the first, single letter prefix leading_letter_penalty: Integer = -5; // penalty applied for every letter in str before the first match max_leading_letter_penalty: Integer = -15; // maximum penalty for leading letters unmatched_letter_penalty: Integer = -1; // penalty for every letter that doesn't match var RecursiveMatch: Boolean; BestRecursiveMatches: TMatches; BestRecursiveScore: Integer; FirstMatch: Boolean; RecursiveMatches: TMatches; RecursiveScore: Integer; Matched: Boolean; Penalty: Integer; Unmatched: Integer; i: Integer; currIdx: Byte; prevIdx: Integer; Neighbor: Char; Curr: Char; begin OutScore := 100; RecursiveMatches:= Default(TMatches); Inc(RecursionCount); if RecursionCount >= RecursionLimit then Exit(False); if (Pattern^ = #0) or (Str^ = #0) then Exit(False); RecursiveMatch := False; BestRecursiveScore := 0; FirstMatch := True; while (Pattern^ <> #0) and (Str^ <> #0) do begin if Pattern^ = Str^ then begin if NextMatch >= MaxMatches then Exit(False); if FirstMatch and (SrcMatches <> nil) then begin Move(SrcMatches^, Matches^, NextMatch); FirstMatch := False; end; if FuzzyMatchRecursive(Pattern, Str+1, RecursiveScore, StrBegin, Matches, @RecursiveMatches[0], MaxMatches, NextMatch, RecursionCount, RecursionLimit, MatchId+1) then begin if (not RecursiveMatch) or (RecursiveScore > BestRecursiveScore) then begin Move(RecursiveMatches[0], BestRecursiveMatches[0], MaxMatches); BestRecursiveScore := RecursiveScore; end; RecursiveMatch := True; end; Matches[NextMatch] := MatchId; Inc(NextMatch); Inc(Pattern); end; Inc(Str); Inc(MatchId); end; Matched := Pattern^ = #0; if Matched then begin Penalty := leading_letter_penalty * matches[0]; if Penalty < max_leading_letter_penalty then Penalty := max_leading_letter_penalty; Inc(OutScore, Penalty); Unmatched := Length(StrBegin) - NextMatch; Inc(OutScore, unmatched_letter_penalty * unmatched); for i := 0 to NextMatch - 1 do begin currIdx := Matches[i]; if i > 0 then begin prevIdx := Matches[i-1]; if currIdx = prevIdx+1 then begin Inc(OutScore, sequential_bonus); end; end; if currIdx > 0 then begin Neighbor := StrBegin[currIdx - 1]; Curr := StrBegin[Curridx]; if NeighBor.IsLetter and Curr.IsLetter and (NeighBor <> Neighbor.ToUpper) and (Curr = Curr.ToUpper) then Inc(OutScore, camel_bonus); if Neighbor in ['.','_',' ','\'] then Inc(OutScore, separator_bonus); end; if currIdx < first_letter_count then begin Inc(OutScore, first_letter_bonus); end; end; end; if RecursiveMatch and ((not Matched) or (BestRecursiveScore > OutScore)) then begin Move(BestRecursiveMatches[0], Matches[0], MaxMatches); OutScore := BestRecursiveScore; Exit(True); end else if Matched then begin Exit(True); end; Exit(False); end; function FuzzyMatch(const Pattern: String; const Str: String; out Score: Integer): Boolean; var Matches: TMatches; begin Result := FuzzyMatch(Pattern, Str, Score, Matches); end; function FuzzyMatch(const Pattern: String; const Str: String; out Score: Integer; var Matches: TMatches): Boolean; var RecursionCount, RecursionLimit: Integer; PatternUC, StrUC: string; begin RecursionCount := 0; RecursionLimit := 10; PatternUC := UpperCase(Pattern); StrUC := UpperCase(Str); Result := FuzzyMatchRecursive(PChar(PatternUC), PChar(StrUC), Score, PChar(Str), nil, @Matches[0], Length(Matches), 0, recursionCount, recursionLimit, 0); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { * ------------------------------------------------------- * } { * NB: the unit should normally be 'used' * } { * in implementation section of other units (inlining) * } { *********************************************************** } unit tfRecords; {$I TFL.inc} interface uses tfTypes; type PForgeInstance = ^TForgeInstance; TForgeInstance = record FVTable: PPointer; FRefCount: Integer; class function QueryIntf(Inst: Pointer; const IID: TGUID; out Obj): TF_RESULT; stdcall; static; class function AddRef(Inst: Pointer): Integer; stdcall; static; class function Release(Inst: Pointer): Integer; stdcall; static; class function SafeRelease(Inst: Pointer): Integer; stdcall; static; end; PForgeSingleton = ^TForgeSingleton; TForgeSingleton = record FVTable: PPointer; class function AddRef(Inst: Pointer): Integer; stdcall; static; class function Release(Inst: Pointer): Integer; stdcall; static; end; function tfIncrement(var Value: Integer): Integer; function tfDecrement(var Value: Integer): Integer; // deprecated; use TForgeHelper methods procedure tfAddrefInstance(Inst: Pointer); inline; procedure tfReleaseInstance(Inst: Pointer); inline; procedure tfFreeInstance(Inst: Pointer); inline; function tfTryAllocMem(var P: Pointer; Size: Integer): TF_RESULT; function tfTryGetMem(var P: Pointer; Size: Integer): TF_RESULT; // remove after THash redesign function HashAlgRelease(Inst: Pointer): Integer; stdcall; implementation function tfTryAllocMem(var P: Pointer; Size: Integer): TF_RESULT; begin try P:= AllocMem(Size); Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; function tfTryGetMem(var P: Pointer; Size: Integer): TF_RESULT; begin try GetMem(P, Size); Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; class function TForgeInstance.QueryIntf(Inst: Pointer; const IID: TGUID; out Obj): TF_RESULT; begin Result:= TF_E_NOINTERFACE; end; { Warning: IUnknown uses ULONG (Cardinal) type for refcount; TtfRecord implementation uses Integer because FRefCount = -1 is reserved for read-only constants } {$IFDEF TFL_CPUX86_32} { We assume register calling conventions for any 32-bit OS} (* function InterlockedAdd(var Addend: Integer; Increment: Integer): Integer; {$IFDEF FPC}nostackframe;{$ENDIF} asm MOV ECX,EAX MOV EAX,EDX LOCK XADD [ECX],EAX ADD EAX,EDX end; *) function tfIncrement(var Value: Integer): Integer; {$IFDEF FPC}assembler; nostackframe;{$ENDIF} asm MOV ECX,EAX MOV EAX,1 LOCK XADD [ECX],EAX INC EAX end; function tfDecrement(var Value: Integer): Integer; {$IFDEF FPC}assembler; nostackframe;{$ENDIF} asm MOV ECX,EAX MOV EAX,-1 LOCK XADD [ECX],EAX DEC EAX end; {$ELSE} {$IFDEF TFL_CPUX86_WIN64} (* function InterlockedAdd(var Addend: Integer; Increment: Integer): Integer; {$IFDEF FPC}nostackframe;{$ENDIF} asm MOV EAX,EDX LOCK XADD DWORD [RCX],EAX ADD EAX,EDX end; *) function tfIncrement(var Value: Integer): Integer; {$IFDEF FPC}assembler; nostackframe;{$ENDIF} asm MOV EAX,1 LOCK XADD DWORD [RCX],EAX INC EAX end; function tfDecrement(var Value: Integer): Integer; {$IFDEF FPC}assembler; nostackframe;{$ENDIF} asm MOV EAX,-1 LOCK XADD DWORD [RCX],EAX DEC EAX end; {$ELSE} function tfIncrement(var Value: Integer): Integer; begin Result:= Value + 1; Value:= Result; end; function tfDecrement(var Value: Integer): Integer; begin Result:= Value - 1; Value:= Result; end; {$ENDIF} {$ENDIF} class function TForgeInstance.Addref(Inst: Pointer): Integer; begin // we need this check because FRefCount = -1 is allowed if PForgeInstance(Inst).FRefCount > 0 then Result:= tfIncrement(PForgeInstance(Inst).FRefCount) else Result:= PForgeInstance(Inst).FRefCount; end; class function TForgeInstance.Release(Inst: Pointer): Integer; begin // we need this check because FRefCount = -1 is allowed if PForgeInstance(Inst).FRefCount > 0 then begin Result:= tfDecrement(PForgeInstance(Inst).FRefCount); if Result = 0 then begin FreeMem(Inst); end; end else Result:= PForgeInstance(Inst).FRefCount; end; class function TForgeInstance.SafeRelease(Inst: Pointer): Integer; type TVTable = array[0..3] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TBurn = function(Inst: Pointer): Integer;{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} begin // we need this check because FRefCount = -1 is allowed if PForgeInstance(Inst).FRefCount > 0 then begin Result:= tfDecrement(PForgeInstance(Inst).FRefCount); if Result = 0 then begin if PPVTable(Inst)^^[3] <> nil then TBurn(PPVTable(Inst)^^[3])(Inst); FreeMem(Inst); end; end else Result:= PForgeInstance(Inst).FRefCount; end; procedure tfAddrefInstance(Inst: Pointer); type TVTable = array[0..2] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TAddref = function(Inst: Pointer): Integer; stdcall; begin TAddref(PPVTable(Inst)^^[1])(Inst); end; procedure tfReleaseInstance(Inst: Pointer); type TVTable = array[0..2] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TRelease = function(Inst: Pointer): Integer; stdcall; begin TRelease(PPVTable(Inst)^^[2])(Inst); end; procedure tfFreeInstance(Inst: Pointer); type TVTable = array[0..2] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TRelease = function(Inst: Pointer): Integer; stdcall; begin if Inst <> nil then TRelease(PPVTable(Inst)^^[2])(Inst); end; // todo: remove // release with purging sensitive information for hash algorithms function HashAlgRelease(Inst: Pointer): Integer; type TVTable = array[0..9] of Pointer; PVTable = ^TVTable; PPVTable = ^PVTable; TPurgeProc = procedure(Inst: Pointer); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} var PurgeProc: Pointer; begin if PForgeInstance(Inst).FRefCount > 0 then begin Result:= tfDecrement(PForgeInstance(Inst).FRefCount); if Result = 0 then begin PurgeProc:= PPVTable(Inst)^^[6]; // 6 is 'Purge' index TPurgeProc(PurgeProc)(Inst); FreeMem(Inst); end; end else Result:= PForgeInstance(Inst).FRefCount; end; { TForgeSingleton } class function TForgeSingleton.Addref(Inst: Pointer): Integer; begin Result:= -1; end; class function TForgeSingleton.Release(Inst: Pointer): Integer; begin Result:= -1; end; end.
unit WallpaperChooserStatementParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, ChooserStatementBaseTestCase, WpcStatements, WpcScriptParser; type { TWallpaperChooserStatementParsingTest } TWallpaperChooserStatementParsingTest = class(TAbstractChooserStatementParsingTest) public const TEST_FILE1 = 'File1.ext'; TEST_FILE2 = 'File2.ext'; protected procedure SetUp(); override; protected procedure AddRequiredObjectsIntoScript(); override; published procedure ShouldParseItemWithDefaultWeightWhichConsistsFromOneWord(); end; implementation { TWallpaperChooserStatementParsingTest } procedure TWallpaperChooserStatementParsingTest.SetUp(); begin inherited SetUp(); ChooserType := ' ' + WALLPAPER_KEYWORD + ' '; ChooserItem1 := ' ' + TEST_FILE1 + STYLE_PROPERTY; ChooserItem2 := ' ' + TEST_FILE2 + ' ' + STYLE_KEYWORD + ' TILE '; end; procedure TWallpaperChooserStatementParsingTest.AddRequiredObjectsIntoScript(); begin // Does nothing end; // CHOOSE WALLAPER FROM // Item1 // Item2 // END CHOOSE procedure TWallpaperChooserStatementParsingTest.ShouldParseItemWithDefaultWeightWhichConsistsFromOneWord(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + FROM_KEYWORD); ScriptLines.Add(' ' + TEST_FILE1); ScriptLines.Add(' ' + TEST_FILE2); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, DEFAULT_WEIGHT_SELECTOR_VALUE, ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, DEFAULT_WEIGHT_SELECTOR_VALUE, ChooserItems[1].Weight); end; initialization RegisterTest(PARSER_TEST_SUITE_NAME, TWallpaperChooserStatementParsingTest); end.
unit bsFrozenNode; {------------------------------------------------------------------------------} { Библиотека : Бизнес слой проекта "Немезис"; } { Автор : Морозов М.А. } { Начат : 12.12.2005 16.48; } { Модуль : bsFrozenNode } { Описание : Модуль предназначен для работы с замороженными узлами; } {------------------------------------------------------------------------------} // $Id: bsFrozenNode.pas,v 1.2 2009/12/04 11:53:08 lulin Exp $ // $Log: bsFrozenNode.pas,v $ // Revision 1.2 2009/12/04 11:53:08 lulin // - перенесли на модель и добились собираемости. // // Revision 1.1 2009/09/14 11:28:58 lulin // - выводим пути и для незавершённых модулей. // // Revision 1.15 2008/12/25 12:19:30 lulin // - <K>: 121153186. // // Revision 1.14 2008/12/24 19:49:12 lulin // - <K>: 121153186. // // Revision 1.13 2008/12/04 14:58:41 lulin // - <K>: 121153186. // // Revision 1.12 2008/04/01 05:52:33 oman // warning fix // // Revision 1.11 2008/03/25 08:33:01 mmorozov // - bugfix: при изменении настроек не перечитывались вкладки с пользовательскими СКР (CQ: OIT5-28504); // // Revision 1.10 2008/01/21 07:18:36 mmorozov // - new: работа с пользовательскими ссылками на докумени и из документа перенесене на sdsDocInfo, чтобы быть доступной для списка и документа + сопутствующий рефакторинг (в рамках работы над CQ: OIT5-17587); // // Revision 1.9 2008/01/10 07:23:00 oman // Переход на новый адаптер // // Revision 1.8.4.1 2007/11/21 10:26:15 oman // Перепиливаем на новый адаптер // // Revision 1.8 2007/09/25 13:47:17 oman // - new: Дерево СКР теперь одно (cq26792) // // Revision 1.7 2007/02/09 12:37:43 lulin // - переводим на строки с кодировкой. // // Revision 1.6 2007/01/22 12:55:00 lulin // - избавляемся от переполнения стека. // // Revision 1.5 2007/01/22 12:22:55 lulin // - переходим на более правильные строки. // // Revision 1.4 2006/11/03 09:45:31 oman // Merge with B_NEMESIS_6_4_0 // // Revision 1.3.12.1 2006/10/31 16:18:55 oman // - fix: СКР переведены со строк на типы (cq23213) // // Revision 1.3 2005/12/23 13:25:23 mmorozov // - bugfix: при разморозке ищем узлы корр\респ по имени; // // Revision 1.2 2005/12/13 09:45:05 mmorozov // - bugfix: замороженный узел после разморозки запоминался; // - new behaviour: при разморозке сначала используется усченное дерево для поиска узла, если не найден, то используется расширенное дерево корр\респ, т.к. не известно из какого дерева был открыт узел; // // Revision 1.1 2005/12/13 08:51:07 mmorozov // - new: использование замороженных узлов при работе с корр\респ для решения проблем связанных с обновлением; // interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, l3Types, DynamicTreeUnit, bsBase, bsInterfaces ; type TbsFrozenNode = class(TbsBase, IbsFrozenNode) {* Базовый класс для работы с замороженными узлами. } protected // protected fields f_Value: INodeBase; protected // protected methods procedure Cleanup; override; {-} function DefreezeNode: INodeBase; virtual; {* - разморозить узел. } protected // IbsFrozenNode function pm_GetValue: INodeBase; procedure pm_SetValue(const aValue: INodeBase); {-} function pm_GetHasNode: Boolean; {* - определяет установлено ли значение. } function pm_GetCaption: Tl3PCharLen; {* - Заголовок замороженной ноды. } function IsSame(const aValue: IbsFrozenNode): Boolean; {* - проверяет на равенство. } procedure IbsFrozenNode.Assign = IbsFrozenNode_Assign; procedure IbsFrozenNode_Assign(const aValue: IbsFrozenNode); {* - скопировать данные. } protected // properties property Value: INodeBase read pm_GetValue write pm_SetValue; {* - хранимое значение, которое размораживается при получении. } property HasNode: Boolean read pm_GetHasNode; {* - определяет установлено ли значение. } property Caption: Tl3PCharLen read pm_GetCaption; {* - Заголовок замороженной ноды. } public // public methods constructor Create(const aValue: INodeBase = nil); reintroduce; {-} class function Make(const aValue: INodeBase = nil): IbsFrozenNode; {-} end;//TbsFrozenNode TbsCRTypeFrozen = class(TbsFrozenNode) {* Для работы с замороженным типом корр\респ. } protected // IbsFrozenNode function DefreezeNode: INodeBase; override; {-} end;//TbsCRTypeFrozen {$IfEnd} implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3String, vcmBase, bsUtils, DataAdapter, nsTreeStruct, nsTreeUtils, nsNodes ; { TbsFrozenNode } constructor TbsFrozenNode.Create(const aValue: INodeBase); // reintroduce; {-} begin inherited Create; pm_SetValue(aValue); end; class function TbsFrozenNode.Make(const aValue: INodeBase): IbsFrozenNode; var l_Class: TbsFrozenNode; begin l_Class := Create(aValue); try Result := l_Class; finally vcmFree(l_Class); end;{try..finally} end;//Make procedure TbsFrozenNode.Cleanup; // override; {-} begin f_Value := nil; inherited; end;//Cleanup function TbsFrozenNode.pm_GetHasNode: Boolean; {* - определяет установлено ли значение. } begin Result := Assigned(f_Value) and (DefreezeNode <> nil); end; function TbsFrozenNode.pm_GetValue: INodeBase; {-} begin // Размороженный узел Result := DefreezeNode; end;//pm_GetValue procedure TbsFrozenNode.pm_SetValue(const aValue: INodeBase); {-} begin f_Value := nil; if Assigned(aValue) then aValue.GetFrozenNode(f_Value); end; function TbsFrozenNode.DefreezeNode: INodeBase; // virtual; {* - разморозить узел. } begin Result := f_Value; end; procedure TbsFrozenNode.IbsFrozenNode_Assign(const aValue: IbsFrozenNode); {* - скопировать данные. } begin Value := aValue.Value; end; function TbsFrozenNode.IsSame(const aValue: IbsFrozenNode): Boolean; {* - проверяет на равенство. } begin Result := (aValue <> nil) and (HasNode = aValue.HasNode); if Result and HasNode then Result := Value.IsSameNode(aValue.Value); end;//IsSame function TbsFrozenNode.pm_GetCaption: Tl3PCharLen; begin if (f_Value <> nil) then Tl3WString(Result) := nsGetCaption(f_Value).AsWStr else l3AssignNil(Result); end; { TbsCRTypeFrozen } function TbsCRTypeFrozen.DefreezeNode: INodeBase; // override; var l_Cap : Tl3PCharLen; begin//DefrozeCRType Result := nil; if Assigned(f_Value) then begin l_Cap := pm_GetCaption; // Мы не знаем из какого дерева был выбран узел, ищем сначала в простом // дереве (выпадающий список типов) Result := bsFindNodeByCaption(DefDataAdapter.CRSimpleListTypeRootNode, l_Cap); end;//if Assigned(aType) then end;//DefreezeNode {$IfEnd} end.
UNIT uDmService; INTERFACE USES System.SysUtils, Classes, System.IOUtils, SysTypes, UDWDatamodule, System.JSON, System.DateUtils, UDWJSONObject, Dialogs, ServerUtils, UDWConsts, FireDAC.Dapt, UDWConstsData, FireDAC.Phys.FBDef, FireDAC.UI.Intf, FireDAC.VCLUI.Wait, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Stan.StorageJSON, URESTDWPoolerDB, URestDWDriverFD, System.JSON.Readers, uConsts, FireDAC.Phys.MSSQLDef, FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, Vcl.SvcMgr, FireDAC.Stan.Param, System.StrUtils, System.NetEncoding, FireDAC.DatS, FireDAC.Dapt.Intf, uRESTDWServerEvents, FireDAC.Comp.DataSet, uDWAbout, IniFiles, Vcl.Graphics, IdSSLOpenSSLHeaders, IdCoder, IdCoderMIME; TYPE TServerMethodDM = CLASS(TServerMethodDataModule) RESTDWPoolerDB1: TRESTDWPoolerDB; Server_FDConnection: TFDConnection; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDTransaction1: TFDTransaction; QAux: TFDQuery; memVendaSinc: TFDMemTable; memVendaSinccontroleinterno: TIntegerField; memVendaSinccpf_cnpj: TStringField; memVendaSincformapagto: TIntegerField; memVendaSincvendedor: TStringField; memVendaSincemissao: TDateField; memVendaSincvalor: TFloatField; memVendaSincdesconto: TFloatField; memVendaSinctotal: TFloatField; memVendaSincsituacao: TStringField; memVendaItemSinc: TFDMemTable; memVendaItemSinccontroleinterno: TIntegerField; memVendaItemSinccod_prod: TIntegerField; memVendaItemSinccod_venda: TIntegerField; memVendaItemSincnomeproduto: TStringField; memVendaItemSincquantidade: TFloatField; memVendaItemSincvalor: TFloatField; memVendaItemSincdesconto: TFloatField; memVendaItemSinctotal: TFloatField; memVendaItemSincunidade: TStringField; memVendaItemSincsituacao: TStringField; memVendaItemSinccomplemento: TStringField; FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink; DWServerEvents1: TDWServerEvents; RESTDWDataBase1: TRESTDWDataBase; RESTDWDriverFD1: TRESTDWDriverFD; procedure DWServerEvents1EventsValidarReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetClientesReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetProdutosReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetClienteInfoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetProdutoInfoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetVendasProdReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetVendasReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetFichaFinanceiraReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetNfeInfoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetProdutoInfoSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetClienteInfoSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetFormapagtoSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetUsuariosSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetPedidoAttSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetPedidoItemAttSincReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsSetPedidosReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsSetPedidosItemReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetPedidoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetItensPedidoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsUpdateItemReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsUpdatePedidoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsPedidoRelatorioReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsItensRelatorioReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsPedidoItensRelatorioReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetIdVendaReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsResumoAbateReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetLatLongReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetRotaReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetRelatorioVendedorReplyEvent(var Params: TDWParams; var Result: string); PROCEDURE Server_FDConnectionBeforeConnect(Sender: TObject); procedure ServerMethodDataModuleReplyEvent(SendType: TSendEvent; Context: string; var Params: TDWParams; var Result: string; AccessTag: string); procedure DWServerEvents1EventsGetFotoProdutoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetPedidoFinalizadoReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetUsuarioCPReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetVendasCPReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsGetPreCadReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsSetPreCadReplyEvent(var Params: TDWParams; var Result: string); procedure DWServerEvents1EventsgetFotoPrecadReplyEvent(var Params: TDWParams; var Result: string); PRIVATE FUNCTION ConsultaBanco(VAR Params: TDWParams): STRING; OVERLOAD; function ValidarUsuario(JSON: String): String; function ProxCod(Tabela, Campo, Formato, Condicao: String): String; function iif(Expressao: Variant; ParteTRUE, ParteFALSE: Variant): Variant; { Private declarations } PUBLIC { Public declarations } END; VAR ServerMethodDM: TServerMethodDM; IMPLEMENTATIOn uses Soap.EncdDecd; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} FUNCTION TServerMethodDM.ConsultaBanco(VAR Params: TDWParams): STRING; VAR VSQL: STRING; JSONValue: TJSONValue; FdQuery: TFDQuery; BEGIN IF Params.ItemsString['SQL'] <> NIL THEN BEGIN JSONValue := UDWJSONObject.TJSONValue.Create; JSONValue.Encoding := Encoding; IF Params.ItemsString['SQL'].Value <> '' THEN BEGIN IF Params.ItemsString['TESTPARAM'] <> NIL THEN Params.ItemsString['TESTPARAM'].SetValue('OK, OK'); VSQL := Params.ItemsString['SQL'].Value; {$IFDEF FPC} {$ELSE} FdQuery := TFDQuery.Create(NIL); TRY FdQuery.Connection := Server_FDConnection; FdQuery.SQL.Add(VSQL); JSONValue.LoadFromDataset('sql', FdQuery, EncodedData); Result := JSONValue.ToJSON; FINALLY JSONValue.Free; FdQuery.Free; END; {$ENDIF} END; END; END; procedure TServerMethodDM.ServerMethodDataModuleReplyEvent(SendType: TSendEvent; Context: string; var Params: TDWParams; var Result: string; AccessTag: string); VAR JSONObject: TJSONObject; BEGIN JSONObject := TJSONObject.Create; CASE SendType OF SePOST: BEGIN IF UpperCase(Context) = UpperCase('EMPLOYEE') THEN Result := ConsultaBanco(Params) ELSE BEGIN JSONObject.AddPair(TJSONPair.Create('STATUS', 'NOK')); JSONObject.AddPair(TJSONPair.Create('MENSAGEM', 'Método não encontrado')); Result := JSONObject.ToJSON; END; END; END; JSONObject.Free; END; PROCEDURE TServerMethodDM.Server_FDConnectionBeforeConnect(Sender: TObject); var ArqIni: TIniFile; LPort: Integer; LServidor: string; LUserName: string; LDatabase: string; LPassword: string; begin ArqIni := TIniFile.Create(CPathIniFile + '\cfg.ini'); try LPort := ArqIni.ReadInteger('Dados', 'Porta', 0); LUserName := ArqIni.ReadString('Dados', 'Usuario', ''); LPassword := ArqIni.ReadString('Dados', 'Senha', ''); LDatabase := ArqIni.ReadString('Dados', 'Banco', ''); LServidor := ArqIni.ReadString('Dados', 'Servidor', ''); TFDConnection(Sender).Params.Clear; TFDConnection(Sender).Params.Add('DriverID=MSSQL'); TFDConnection(Sender).Params.Add('Server=' + LServidor); TFDConnection(Sender).Params.Add('Database=' + LDatabase); TFDConnection(Sender).Params.Add('User_Name=' + LUserName); TFDConnection(Sender).Params.Add('Password=' + LPassword); TFDConnection(Sender).DriverName := 'MSSQL'; TFDConnection(Sender).LoginPrompt := FALSE; TFDConnection(Sender).UpdateOptions.CountUpdatedRecords := FALSE; finally ArqIni.Free; end; END; procedure TServerMethodDM.DWServerEvents1EventsGetClienteInfoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_PESSOA ' + 'WHERE COD_PESSOA = :COD '; var JSONValue: TJSONValue; Query3: TFDQuery; begin if (Params.ItemsString['Cliente'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query3 := TFDQuery.Create(nil); Query3.Connection := Server_FDConnection; TRY Query3.Active := FALSE; Query3.SQL.Clear; Query3.SQL.Text := _SQL; Query3.ParamByName('COD').AsInteger := Params.ItemsString['Cliente'].AsInteger; Query3.Active := True; TRY // Query3.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('cliente', Query3, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query3.Active then FreeAndNil(Query3); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetClienteInfoSincReplyEvent(var Params: TDWParams; var Result: string); const { t.situacao = 1 --- LIBERADO 0 --- BLOQUEADO } _SQL = 'select t.cod_pessoa, t.nome_razao, t.nome_fant, t.endereco, t.bairro, c.municipio, t.telefone, t.cpf_cnpj, t.email, t.cod_vend, t.cod_doc, t.situacao, ' + 'case when isnull(t1.vlr_crd, 0) < isnull(t2.sld_chq+t3.sld_dev, 0) then 0 else 1 end as credito, ' + 'case when min_dta is not null then 0 else 1 end as atraso ' + 'from t_cidade c, t_pessoa t left outer join (select tc.cod_cliente, tc.credito as vlr_crd from t_credito tc where cod_cliente = 15 ' + 'and tc.cod = (select max(cod) from t_credito where cod_cliente = tc.cod_cliente)) t1 on (t.cod_pessoa = t1.cod_cliente) ' + 'left outer join (select cod_cliente, sum(valor) as sld_chq from v_cheques_receb where status = 0 group by cod_cliente) t2 on (t.cod_pessoa = t2.cod_cliente) ' + 'left outer join (select cod_cliente, sum(sld_dev) as sld_dev from v_contas_receb where status = ''A'' group by cod_cliente) t3 on (t.cod_pessoa = t3.cod_cliente) ' + 'left outer join (select cod_cliente, min(data_venc) as min_dta from t_contas_receb where status = ''A'' and data_venc < (select dateadd(day, dias_carencia, getdate()) from t_config) group by cod_cliente) t4 on (t.cod_pessoa = t4.cod_cliente)' + 'where t.cod_vend = :cod and t.cod_cidade = c.cod_cidade and t.situacao = 1 '; var JSONValue: TJSONValue; QuerySinc2: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc2 := TFDQuery.Create(nil); QuerySinc2.Connection := Server_FDConnection; TRY QuerySinc2.Active := FALSE; QuerySinc2.SQL.Clear; QuerySinc2.SQL.Text := _SQL; QuerySinc2.ParamByName('cod').AsInteger := Params.ItemsString['Cod'].AsInteger; QuerySinc2.Active := True; TRY // QuerySinc2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('clientesinc', QuerySinc2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc2.Active then FreeAndNil(QuerySinc2); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetClientesReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT TOP(100) ' + ' COD_PESSOA, ' + ' NOME_FANT, ' + ' ENDERECO, ' + ' BAIRRO, ' + ' CLIENTE, ' + ' FORNECEDOR ' + 'FROM T_PESSOA ' + 'ORDER BY COD_PESSOA DESC'; _SQL2 = 'SELECT TOP(100) ' + ' COD_PESSOA, ' + ' NOME_FANT, ' + ' ENDERECO, ' + ' BAIRRO, ' + ' CLIENTE, ' + ' FORNECEDOR ' + 'FROM T_PESSOA ' + 'WHERE NOME_FANT = :NOME_FANT ' + 'ORDER BY COD_PESSOA DESC '; var JSONValue: TJSONValue; Query1: TFDQuery; begin if (Params.ItemsString['Get'].AsString.Equals(EmptyStr)) then begin JSONValue := TJSONValue.Create; Query1 := TFDQuery.Create(nil); Query1.Connection := Server_FDConnection; TRY Query1.Active := FALSE; Query1.SQL.Clear; Query1.SQL.Text := _SQL; Query1.Active := True; TRY // Query1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('clientes', Query1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except END; FINALLY JSONValue.Free; if Query1.Active then FreeAndNil(Query1); END; end else begin JSONValue := TJSONValue.Create; Query1 := TFDQuery.Create(nil); Query1.Connection := Server_FDConnection; TRY Query1.Active := FALSE; Query1.SQL.Clear; Query1.SQL.Text := _SQL2; Query1.ParamByName('NOME_FANT').AsString := Params.ItemsString['Get'].AsString; Query1.Active := True; if Query1.IsEmpty then Params.ItemsString['Result'].AsString := 'fail' else begin TRY // Query1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('clientes', Query1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except END; end; FINALLY JSONValue.Free; if Query1.Active then FreeAndNil(Query1); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetFichaFinanceiraReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT Top (100) * ' + 'FROM v_contas_receb C ' + 'WHERE 1 =1 and c.cod_cliente = :doc_cliente ' + 'order by data_emis desc; '; _SQL2 = 'SELECT Top (100) * ' + 'FROM v_contas_receb C ' + 'WHERE 1 =1 and c.cod_cliente = :doc_cliente ' + 'and status = :con_situacao ' + 'order by data_emis desc; '; var JSONValue: TJSONValue; Query7: TFDQuery; begin if ((Params.ItemsString['GetFicha'].AsString <> EmptyStr) and (Params.ItemsString['Situacao'].AsString <> EmptyStr)) then begin JSONValue := TJSONValue.Create; Query7 := TFDQuery.Create(nil); Query7.Connection := Server_FDConnection; TRY Query7.Active := FALSE; Query7.SQL.Clear; if Params.ItemsString['Situacao'].AsString.Equals('T') then begin Query7.SQL.Text := _SQL; Query7.ParamByName('doc_cliente').AsInteger := Params.ItemsString['GetFicha'].AsInteger end else begin Query7.SQL.Text := _SQL2; Query7.ParamByName('doc_cliente').AsInteger := Params.ItemsString['GetFicha'].AsInteger; Query7.ParamByName('con_situacao').AsString := Params.ItemsString['Situacao'].AsString; end; Query7.Active := True; TRY // Query7.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('ficha', Query7, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query7.Active then FreeAndNil(Query7); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetFormapagtoSincReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_DOCUMENTO '; var JSONValue: TJSONValue; QuerySinc3: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc3 := TFDQuery.Create(nil); QuerySinc3.Connection := Server_FDConnection; TRY QuerySinc3.Active := FALSE; QuerySinc3.SQL.Clear; QuerySinc3.SQL.Text := _SQL; QuerySinc3.Active := True; TRY // QuerySinc3.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('formapagtsinc', QuerySinc3, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc3.Active then FreeAndNil(QuerySinc3); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetFotoProdutoReplyEvent(var Params: TDWParams; var Result: string); const _SQLFOTO = 'SELECT cod_prod, nome_arq, foto_arq from t_produto_foto ORDER BY cod_prod OFFSET %s ROWS FETCH NEXT %s ROWS ONLY'; _SQL2008 = 'Select cod_prod, nome_arq, foto_arq ' + 'from ' + '( ' + ' select cod_prod, nome_arq, foto_arq, ' + ' ROW_NUMBER() OVER(ORDER by COD_PROD) as Seq ' + ' from t_produto_foto ' + ')t ' + 'where Seq between %s and %s '; var JSONValue: TJSONValue; QuerySinc1, qryAux: TFDQuery; ljo: TJSONObject; i: Integer; StreamIn: TStream; StreamOut: TStringStream; Result1: TJSONArray; Fotos: string; LFirst: Integer; LShow: Integer; begin if (Params.ItemsString['pFirst'] <> nil) and not(Params.ItemsString['pFirst'].AsString.Trim.IsEmpty) then LFirst := Params.ItemsString['pFirst'].AsInteger; if (Params.ItemsString['pShow'] <> nil) and not(Params.ItemsString['pShow'].AsString.Trim.IsEmpty) then LShow := Params.ItemsString['pShow'].AsInteger; JSONValue := TJSONValue.Create; qryAux := TFDQuery.Create(nil); qryAux.Connection := Server_FDConnection; // if not Params.ItemsString['Cod'].AsString.IsEmpty then // begin TRY qryAux.Active := FALSE; qryAux.SQL.Clear; qryAux.SQL.Text := Format(_SQL2008, [LFirst.ToString, LShow.ToString]); // qryAux.Params[0].AsString := Params.ItemsString['Cod'].AsString; qryAux.Active := True; qryAux.Last; Params.ItemsString['pResultCount'].AsInteger := qryAux.RecordCount; if not qryAux.IsEmpty or not qryAux.FieldByName('foto_arq').IsNull then begin try if qryAux.Active then begin if qryAux.RecordCount > 0 then begin Result1 := TJSONArray.Create; try qryAux.First; while not(qryAux.Eof) do begin ljo := TJSONObject.Create; for i := 0 to qryAux.FieldCount - 1 do begin if qryAux.Fields[i].IsNull then // Tratando valores nulos para não "quebrar" a aplicação ljo.AddPair(qryAux.Fields[i].DisplayName, EmptyStr) else begin if qryAux.Fields[i].IsBlob then begin StreamIn := qryAux.CreateBlobStream(qryAux.Fields[i], bmRead); StreamOut := TStringStream.Create; TNetEncoding.Base64.Encode(StreamIn, StreamOut); StreamOut.Position := 0; ljo.AddPair(qryAux.Fields[i].DisplayName, StreamOut.DataString); end else begin ljo.AddPair(qryAux.Fields[i].DisplayName, qryAux.Fields[i].Value); end; end; end; Result1.AddElement(ljo); // Fotos := ljo.ToJSON; // Params.ItemsString['Result'].AsString := Fotos; qryAux.Next; end; finally end; end; end; finally Params.ItemsString['Fotos'].AsString := Result1.ToString; end; end else Params.ItemsString['Fotos'].AsString := '0'; finally if qryAux.Active then FreeAndNil(qryAux); end; // end // else // Params.ItemsString['Result'].AsString := '0'; end; procedure TServerMethodDM.DWServerEvents1EventsGetIdVendaReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT controleinterno from t_vendamobile where vendedor = :vendedor order by controleinterno desc'; var JSONValue: TJSONValue; Query3: TFDQuery; begin if (Params.ItemsString['Vendedor'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query3 := TFDQuery.Create(nil); Query3.Connection := Server_FDConnection; TRY Query3.Active := FALSE; Query3.SQL.Clear; Query3.SQL.Text := _SQL; Query3.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query3.Active := True; TRY // Query3.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('idclientevenda', Query3, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query3.Active then FreeAndNil(Query3); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetItensPedidoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_VENDAITEMMOBILE ' + 'WHERE COD_VENDA = :CONTROLEINTERNO AND vendedor = :vendedor '; var JSONValue: TJSONValue; Query4: TFDQuery; begin if (Params.ItemsString['Pedido'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL; Query4.ParamByName('CONTROLEINTERNO').AsInteger := Params.ItemsString['Pedido'].AsInteger; Query4.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('itenspedido', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetLatLongReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT latitude, ' + ' longitude ' + 'FROM T_VENDAMOBILE ' + 'WHERE controleinterno = :CONTROLEINTERNO AND vendedor = :vendedor '; var JSONValue: TJSONValue; Query4: TFDQuery; begin if (Params.ItemsString['Venda'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL; Query4.ParamByName('CONTROLEINTERNO').AsInteger := Params.ItemsString['Venda'].AsInteger; Query4.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('latlong', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetNfeInfoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = ' select n.cod_nota, ' + ' n.data_emissao, ' + ' n.data_saida_entra, ' + ' n.hora, ' + ' n.pedido, ' + ' p.cod_pessoa, ' + ' n.cpf_cnpj_r_d, ' + ' p.nome_razao, ' + ' n.vr_total_nota, ' + ' n.forma_pgto, ' + ' n.status, ' + ' n.nfeaprovada, ' + ' n.lote, ' + ' n.protocolonfe, ' + ' ti.descricao, ' + ' ti.quant, ' + ' ti.valor_unitario, ' + ' ti.data_emissao, ' + ' ti.valor_total, ' + ' ti.ncm, ' + ' ti.cfop, ' + ' ti.valor_icms, ' + ' ti.valor_ipi ' + ' from t_nota_emitidas n, ' + ' t_pessoa p, t_nota_itens ti ' + ' where n.nf_sai_en = 2 ' + ' and ' + ' n.cod_nota = ti.cod_nota and n.cod_empresa = ti.cod_empresa' + ' and ' + ' p.cpf_cnpj=n.cpf_cnpj_r_d ' + ' and ' + ' p.cod_pessoa= :doc_cliente ' + ' and ' + ' n.cod_nota = :doc_nota ' + ' order by n.data_emissao desc '; var JSONValue: TJSONValue; Query7: TFDQuery; begin if ((Params.ItemsString['CodCliente'].AsString <> EmptyStr) and (Params.ItemsString['CodNota'].AsString <> EmptyStr)) then begin JSONValue := TJSONValue.Create; Query7 := TFDQuery.Create(nil); Query7.Connection := Server_FDConnection; TRY Query7.Active := FALSE; Query7.SQL.Clear; Query7.SQL.Text := _SQL; Query7.ParamByName('doc_cliente').AsInteger := Params.ItemsString['CodCliente'].AsInteger; Query7.ParamByName('doc_nota').AsInteger := Params.ItemsString['CodNota'].AsInteger; Query7.Active := True; TRY // Query7.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('infonfe', Query7, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query7.Active then FreeAndNil(Query7); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetPedidoAttSincReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select TOP(500) controleinterno, ' + ' cpf_cnpj, ' + ' formapagto, ' + ' vendedor, ' + ' convert(varchar(10), emissao, 103) as emissao, ' + ' valor, ' + ' desconto, ' + ' total, ' + ' cod_cliente, ' + ' data_emb, ' + ' cod_ret, ' + ' comissao ' + 'from t_vendamobile ' + 'where vendedor = :vendedor ' + 'order by emissao asc '; var JSONValue: TJSONValue; QuerySinc5: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc5 := TFDQuery.Create(nil); QuerySinc5.Connection := Server_FDConnection; TRY QuerySinc5.Active := FALSE; QuerySinc5.SQL.Clear; QuerySinc5.SQL.Text := _SQL; QuerySinc5.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; QuerySinc5.Active := True; QuerySinc5.Connection.Commit; TRY // QuerySinc5.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('pedidosinc', QuerySinc5, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc5.Active then FreeAndNil(QuerySinc5); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetPedidoFinalizadoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select cod_pedcar_mobile, status, valor_final FROM t_pedidovenda WHERE status = 3 and not cod_pedcar_mobile is null'; var JSONValue: TJSONValue; QuerySinc6: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc6 := TFDQuery.Create(nil); QuerySinc6.Connection := Server_FDConnection; TRY QuerySinc6.Active := FALSE; QuerySinc6.SQL.Clear; QuerySinc6.SQL.Text := _SQL; QuerySinc6.Active := True; QuerySinc6.Connection.Commit; TRY // QuerySinc6.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('pedidofinalizado', QuerySinc6, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc6.Active then FreeAndNil(QuerySinc6); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetPedidoItemAttSincReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select ' + ' vi.cod_prod, ' + ' vi.cod_venda, ' + ' vi.nomeproduto, ' + ' vi.quantidade, ' + ' vi.valor, ' + ' vi.desconto, ' + ' vi.total, ' + ' vi.unidade, ' + ' vi.vendedor ' + 'from t_vendaitemmobile vi ' + 'where vi.vendedor = :vendedor and vi.cod_venda = :cod '; var JSONValue: TJSONValue; QuerySinc6: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc6 := TFDQuery.Create(nil); QuerySinc6.Connection := Server_FDConnection; TRY QuerySinc6.Active := FALSE; QuerySinc6.SQL.Clear; QuerySinc6.SQL.Text := _SQL; QuerySinc6.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; QuerySinc6.ParamByName('cod').AsInteger := Params.ItemsString['Cod'].AsInteger; QuerySinc6.Active := True; QuerySinc6.Connection.Commit; TRY // QuerySinc6.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('pedidoitemsinc', QuerySinc6, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc6.Active then FreeAndNil(QuerySinc6); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetPedidoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_VENDAMOBILE ' + 'WHERE situacao = :situacao '; _SQLTODAS = 'SELECT ' + ' * ' + 'FROM T_VENDAMOBILE '; var JSONValue: TJSONValue; QuerySinc1: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc1 := TFDQuery.Create(nil); QuerySinc1.Connection := Server_FDConnection; if Params.ItemsString['Situacao'].AsString.Equals('todas') then begin TRY QuerySinc1.Active := FALSE; QuerySinc1.SQL.Clear; QuerySinc1.SQL.Text := _SQLTODAS; // QuerySinc1.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; QuerySinc1.Active := True; TRY // QuerySinc1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('pedidos', QuerySinc1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc1.Active then FreeAndNil(QuerySinc1); END; end else begin TRY QuerySinc1.Active := FALSE; QuerySinc1.SQL.Clear; QuerySinc1.SQL.Text := _SQL; QuerySinc1.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; QuerySinc1.Active := True; TRY // QuerySinc1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('pedidos', QuerySinc1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc1.Active then FreeAndNil(QuerySinc1); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetPreCadReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_cliente_precad ' + 'WHERE status = :pstatus '; _SQLTODAS = 'SELECT ' + ' * ' + 'FROM T_cliente_precad '; var JSONValue: TJSONValue; QuerySinc1: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc1 := TFDQuery.Create(nil); QuerySinc1.Connection := Server_FDConnection; if Params.ItemsString['pstatus'].AsString.Equals('todas') then begin TRY QuerySinc1.Active := FALSE; QuerySinc1.SQL.Clear; QuerySinc1.SQL.Text := _SQLTODAS; // QuerySinc1.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; QuerySinc1.Active := True; TRY // QuerySinc1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('precad', QuerySinc1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc1.Active then FreeAndNil(QuerySinc1); END; end else begin TRY QuerySinc1.Active := FALSE; QuerySinc1.SQL.Clear; QuerySinc1.SQL.Text := _SQL; QuerySinc1.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; QuerySinc1.Active := True; TRY // QuerySinc1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('precad', QuerySinc1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc1.Active then FreeAndNil(QuerySinc1); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetProdutoInfoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_PRODUTO ' + 'WHERE COD_PROD = :COD '; var JSONValue: TJSONValue; Query4: TFDQuery; begin if (Params.ItemsString['Produto'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL; Query4.ParamByName('COD').AsInteger := Params.ItemsString['Produto'].AsInteger; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('produto', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetProdutoInfoSincReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select tp.cod_prod, ' + ' tp.desc_ind, ' + ' tp.unid_med, ' + ' tp.validade, tp.tipo_calc, tp.quant_cx, tp.peso_padrao, ' + ' coalesce(tg.descricao_grupo,''SEM GRUPO'') as grupo_com, ' + ' coalesce(tpr.preco_venda, 0) as valor_prod, ' + ' coalesce(tpr.preco1, 0) as valor_min, ' + 'case when (ativo is null) or (ativo = 1) then ''SIM'' else ''NÃO'' end as ativo ' + 'from t_produto tp left outer join t_gruposcomerciais tg on (tg.cod_grupo = tp.grupo_com) ' + 'left outer join t_precos_prod tpr on (tpr.cod_prod = tp.cod_prod and tpr.data = (select max(data) from t_precos_prod where cod_prod = tpr.cod_prod)) ' + 'WHERE vendas = 1 and (ativo is null or ativo = 1)' + 'order by tp.cod_prod '; var JSONValue: TJSONValue; QuerySinc1, qryAux: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc1 := TFDQuery.Create(nil); QuerySinc1.Connection := Server_FDConnection; TRY QuerySinc1.Active := FALSE; QuerySinc1.SQL.Clear; QuerySinc1.SQL.Text := _SQL; QuerySinc1.Active := True; TRY // QuerySinc1.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('produtosinc', QuerySinc1, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc1.Active then FreeAndNil(QuerySinc1); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetProdutosReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT TOP(50) ' + ' COD_PROD, ' + ' DESC_IND, ' + ' DESC_FAT ' + 'FROM T_PRODUTO ' + 'ORDER BY COD_PROD '; _SQL2 = 'SELECT TOP(50) ' + ' COD_PROD, ' + ' DESC_IND, ' + ' DESC_FAT ' + 'FROM T_PRODUTO ' + 'WHERE DESC_IND = :DESC ' + 'ORDER BY COD_PROD '; var JSONValue: TJSONValue; Query2: TFDQuery; begin if (Params.ItemsString['Get'].AsString.Equals(EmptyStr)) then begin JSONValue := TJSONValue.Create; Query2 := TFDQuery.Create(nil); Query2.Connection := Server_FDConnection; TRY Query2.Active := FALSE; Query2.SQL.Clear; Query2.SQL.Text := _SQL; Query2.Active := True; TRY // Query2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('produtos', Query2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except END; FINALLY JSONValue.Free; if Query2.Active then FreeAndNil(Query2); END; end else begin JSONValue := TJSONValue.Create; Query2 := TFDQuery.Create(nil); Query2.Connection := Server_FDConnection; TRY Query2.Active := FALSE; Query2.SQL.Clear; Query2.SQL.Text := _SQL2; Query2.ParamByName('DESC').AsString := Params.ItemsString['Get'].AsString; Query2.Active := True; if Query2.IsEmpty then Params.ItemsString['Result'].AsString := 'fail' else begin TRY // Query2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('produtos', Query2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except END; end; FINALLY JSONValue.Free; if Query2.Active then FreeAndNil(Query2); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetRelatorioVendedorReplyEvent(var Params: TDWParams; var Result: string); const // _SQL = // 'SELECT vendedor, '+ // ' sum(total) as valor_total_vendedor, '+ // ' ((sum(total)*100)/(SELECT sum(total) as total_vendas '+ // ' from t_vendamobile '+ // ' where emissao between :emissaoA and :emissaoB)) as valor_porc_vendedor'+ // 'FROM t_vendamobile '+ // 'WHERE emissao between :emissaoA and :emissaoB '+ // 'group by vendedor '+ // 'order by valor_total_vendedor desc, valor_porc_vendedor desc '; _SQL = 'SELECT vendedor, ' + ' sum(total) as valor_total_vendedor ' + 'FROM t_vendamobile ' + 'WHERE emissao between :emissaoA and :emissaoB ' + 'group by vendedor ' + 'order by valor_total_vendedor desc '; _SQL2 = 'SELECT sum(total) as valor_total ' + 'from t_vendamobile ' + 'where emissao between :emissaoA and :emissaoB '; var JSONValue: TJSONValue; Query4: TFDQuery; begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; if Params.ItemsString['Opcao'].AsInteger = 1 then begin TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL; Query4.ParamByName('emissaoA').AsString := Params.ItemsString['DataA'].AsString; Query4.ParamByName('emissaoB').AsString := Params.ItemsString['DataB'].AsString; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatoriovendedor', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end else if Params.ItemsString['Opcao'].AsInteger = 0 then begin TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL2; Query4.ParamByName('emissaoA').AsString := Params.ItemsString['DataA'].AsString; Query4.ParamByName('emissaoB').AsString := Params.ItemsString['DataB'].AsString; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatoriovendedor', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetRotaReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT latitude, ' + ' longitude , ' + ' controleinterno, ' + ' vendedor, ' + ' cpf_cnpj, ' + ' total, ' + ' situacao ' + 'FROM T_VENDAMOBILE ' + 'WHERE vendedor = :vendedor and emissao = :emissao ' + 'ORDER BY emissao asc '; var JSONValue: TJSONValue; Query4: TFDQuery; begin if (Params.ItemsString['Data'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Text := _SQL; Query4.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query4.ParamByName('emissao').AsString := Params.ItemsString['Data'].AsString; Query4.Active := True; TRY // Query4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('rota', Query4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetUsuarioCPReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select nome ' + 'from t_usuarios ' + 'where cod_vend is not null'; var JSONValue: TJSONValue; QuerySinc20: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc20 := TFDQuery.Create(nil); QuerySinc20.Connection := Server_FDConnection; TRY QuerySinc20.Active := FALSE; QuerySinc20.SQL.Clear; QuerySinc20.SQL.Text := _SQL; QuerySinc20.Active := True; TRY // QuerySinc20.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('usuarioscp', QuerySinc20, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc20.Active then FreeAndNil(QuerySinc20); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetUsuariosSincReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT ' + ' * ' + 'FROM T_USUARIOS '; var JSONValue: TJSONValue; QuerySinc4: TFDQuery; begin JSONValue := TJSONValue.Create; QuerySinc4 := TFDQuery.Create(nil); QuerySinc4.Connection := Server_FDConnection; TRY QuerySinc4.Active := FALSE; QuerySinc4.SQL.Clear; QuerySinc4.SQL.Text := _SQL; QuerySinc4.Active := True; TRY // QuerySinc4.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('usuariossinc', QuerySinc4, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if QuerySinc4.Active then FreeAndNil(QuerySinc4); END; end; procedure TServerMethodDM.DWServerEvents1EventsGetVendasCPReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'select ve.controleinterno, ' + ' ve.vendedor, ' + ' FORMAT(cast(ve.emissao as date), ''dd/MM/yyyy'') emissao, ' + ' ve.total, ' + ' pe.nome_fant, ' + ' us.cod_vend as cod_vendedor ' + 'from t_vendamobile as ve, t_pessoa as pe, t_usuarios as us ' + 'where pe.cpf_cnpj = ve.cpf_cnpj and us.usuario = :usuario and ve.vendedor = :usuario ' + ' and CONVERT(date, zve.emissao, 121) between :dataA and :dataB ' + 'order by ve.emissao desc '; var JSONValue: TJSONValue; QuerySinc22: TFDQuery; begin JSONValue := TJSONValue.Create; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoded := FALSE; QuerySinc22 := TFDQuery.Create(NIL); QuerySinc22.Connection := Server_FDConnection; QuerySinc22.Active := FALSE; QuerySinc22.SQL.Clear; QuerySinc22.SQL.Text := _SQL; QuerySinc22.ParamByName('usuario').AsString := Params.ItemsString['Usuario'].AsString; QuerySinc22.ParamByName('dataA').AsString := Params.ItemsString['DataA'].AsString; QuerySinc22.ParamByName('dataB').AsString := Params.ItemsString['DataB'].AsString; QuerySinc22.Active := True; // ??? try try if Params.JsonMode in [jmPureJSON, jmMongoDB] then begin JSONValue.LoadFromDataset('', QuerySinc22, FALSE, Params.JsonMode, 'dd/mm/yyyy', '.'); Result := JSONValue.ToJSON; end; except on E: Exception do Result := Format('{"Error":"%s"}', [E.Message]) end; finally QuerySinc22.Close; JSONValue.Free; {$REGION 'CÓDIGO ANTIGO'} // JSONValue := TJSONValue.Create; // QuerySinc22 := TFDQuery.Create(nil); // QuerySinc22.Connection := Server_FDConnection; // TRY // QuerySinc22.Active := FALSE; // QuerySinc22.SQL.Clear; // QuerySinc22.SQL.Text := _SQL; // QuerySinc22.ParamByName('usuario').AsString := Params.ItemsString['Usuario'].AsString; // QuerySinc22.ParamByName('dataA').AsString := Params.ItemsString['DataA'].AsString; // QuerySinc22.ParamByName('dataB').AsString := Params.ItemsString['DataB'].AsString; // QuerySinc22.Active := True; // // {QuerySinc22.First; // ShowMessage(QuerySinc22.FieldByName('emissao').AsString);} // TRY // // QuerySinc22.Open; // JSONValue.JsonMode := Params.JsonMode; // JSONValue.Encoding := Encoding; // JSONValue.LoadFromDataset('vendascp', QuerySinc22, True, // Params.JsonMode, ''); // Params.ItemsString['Result'].AsString := JSONValue.ToJSON; // Except // // // END; // FINALLY // JSONValue.Free; // if QuerySinc22.Active then // FreeAndNil(QuerySinc22); // END; {$ENDREGION} end; end; procedure TServerMethodDM.DWServerEvents1EventsGetVendasProdReplyEvent(var Params: TDWParams; var Result: string); const _SQL = ' select Top (30) ti.cod_empresa, ' + ' ti.serie, ' + ' ti.cod_nota, ' + ' ti.num_item, ' + ' ti.cod_prod, ' + ' ti.sigla, ' + ' ti.descricao, ' + ' ti.st, ' + ' ti.valor_unitario_pt, ' + ' ti.valor_total_pt, ' + ' ti.data_emissao, ' + ' ti.unidade, ' + ' ti.ncm, ' + ' ti.cest, ' + ' ti.quant_pecas, ' + ' ti.quant, ' + ' ti.valor_unitario, ' + ' ti.vlr_base_calc, ' + ' ti.valor_desc, ' + ' ti.valor_frete, ' + ' ti.cfop, ' + ' ti.valor_total, ' + ' ti.icms, ' + ' ti.reducao, ' + ' ti.ipi, ' + ' ti.vlr_base_calc as base_calc, ' + ' ti.valor_icms, ' + ' ti.valor_ipi, ' + ' ti.inf_adic ' + ' from t_nota_itens ti, ' + ' t_nota_emitidas ne, ' + ' t_pessoa p ' + ' where 1=1 and ne.cod_nota=ti.cod_nota and ' + ' p.cpf_cnpj=ne.cpf_cnpj_r_d ' + ' and cod_pessoa= :doc_cliente ' + ' order by data_emissao desc '; var JSONValue: TJSONValue; Query5: TFDQuery; begin if (Params.ItemsString['VendasProd'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query5 := TFDQuery.Create(nil); Query5.Connection := Server_FDConnection; TRY Query5.Active := FALSE; Query5.SQL.Clear; Query5.SQL.Text := _SQL; Query5.ParamByName('doc_cliente').AsInteger := Params.ItemsString['VendasProd'].AsInteger; Query5.Active := True; TRY // Query5.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('vendasprod', Query5, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query5.Active then FreeAndNil(Query5); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsGetVendasReplyEvent(var Params: TDWParams; var Result: string); const _SQL = ' select Top (50) n.cod_nota, ' + ' n.data_emissao, ' + ' n.data_saida_entra, ' + ' n.hora, ' + ' n.pedido, ' + ' p.cod_pessoa, ' + ' n.cpf_cnpj_r_d, ' + ' p.nome_razao, ' + ' n.vr_total_nota, ' + ' n.forma_pgto, ' + ' n.status, ' + ' n.nfeaprovada, ' + ' n.lote, ' + ' n.protocolonfe ' + ' from t_nota_emitidas n, ' + ' t_pessoa p where n.nf_sai_en = 2 and ' + ' p.cpf_cnpj=n.cpf_cnpj_r_d and ' + ' p.cod_pessoa=:doc_cliente ' + ' order by n.data_emissao desc '; var JSONValue: TJSONValue; Query6: TFDQuery; begin if (Params.ItemsString['Vendas'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query6 := TFDQuery.Create(nil); Query6.Connection := Server_FDConnection; TRY Query6.Active := FALSE; Query6.SQL.Clear; Query6.SQL.Text := _SQL; Query6.ParamByName('doc_cliente').AsInteger := Params.ItemsString['Vendas'].AsInteger; Query6.Active := True; TRY // Query6.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('vendas', Query6, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query6.Active then FreeAndNil(Query6); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsItensRelatorioReplyEvent(var Params: TDWParams; var Result: string); const _SQLSITUACAO = 'SELECT * FROM t_vendaitemmobile WHERE situacao = :situacao'; _SQLNOME = 'SELECT * FROM t_vendaitemmobile WHERE vendedor = :vendedor'; var JSONValue: TJSONValue; qryRelatorio2: TFDQuery; begin if (Params.ItemsString['NomeVendedor'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; qryRelatorio2 := TFDQuery.Create(nil); qryRelatorio2.Connection := Server_FDConnection; TRY qryRelatorio2.Active := FALSE; qryRelatorio2.SQL.Clear; qryRelatorio2.SQL.Text := _SQLNOME; qryRelatorio2.ParamByName('vendedor').AsString := Params.ItemsString['NomeVendedor'].AsString; qryRelatorio2.Active := True; TRY // qryRelatorio2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatorionomei', qryRelatorio2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorio2.Active then FreeAndNil(qryRelatorio2); END; end else if (Params.ItemsString['Situacao'].AsString.Equals('aprovado')) then begin JSONValue := TJSONValue.Create; qryRelatorio2 := TFDQuery.Create(nil); qryRelatorio2.Connection := Server_FDConnection; TRY qryRelatorio2.Active := FALSE; qryRelatorio2.SQL.Clear; qryRelatorio2.SQL.Text := _SQLSITUACAO; qryRelatorio2.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; qryRelatorio2.Active := True; TRY // qryRelatorio2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatorioaprovadoi', qryRelatorio2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorio2.Active then FreeAndNil(qryRelatorio2); END; end else if (Params.ItemsString['Situacao'].AsString.Equals('reprovado')) then begin JSONValue := TJSONValue.Create; qryRelatorio2 := TFDQuery.Create(nil); qryRelatorio2.Connection := Server_FDConnection; TRY qryRelatorio2.Active := FALSE; qryRelatorio2.SQL.Clear; qryRelatorio2.SQL.Text := _SQLSITUACAO; qryRelatorio2.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; qryRelatorio2.Active := True; TRY // qryRelatorio2.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatorioreprovadoi', qryRelatorio2, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorio2.Active then FreeAndNil(qryRelatorio2); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsPedidoItensRelatorioReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'SELECT REPLICATE (''0'',5 - LEN (ve.controleinterno)) + RTrim (ve.controleinterno)as controleinterno,' + ' ve.cpf_cnpj, ' + ' REPLICATE (''0'',5 - LEN (ve.formapagto)) + RTrim (ve.formapagto)as formapagto,' + ' ve.vendedor, ' + ' ve.emissao, ' + ' ve.situacao, ' + ' it.cod_venda, ' + ' it.cod_prod, ' + ' it.nomeproduto, ' + ' it.quantidade, ' + ' it.valor, ' + ' it.desconto, ' + ' it.total, ' + ' it.unidade, ' + ' it.situacao as sititem, ' + ' it.vendedor ' + ' FROM t_vendamobile as ve, t_vendaitemmobile as it ' + ' WHERE ve.controleinterno = it.cod_venda and ve.situacao = :situacao'; _SQLNOME = 'SELECT REPLICATE (''0'',5 - LEN (ve.controleinterno)) + RTrim (ve.controleinterno)as controleinterno,' + ' ve.cpf_cnpj, ' + ' REPLICATE (''0'',5 - LEN (ve.formapagto)) + RTrim (ve.formapagto)as formapagto, ' + ' ve.vendedor, ' + ' ve.emissao, ' + ' ve.situacao, ' + ' it.cod_venda, ' + ' it.cod_prod, ' + ' it.nomeproduto, ' + ' it.quantidade, ' + ' it.valor, ' + ' it.desconto, ' + ' it.total, ' + ' it.unidade, ' + ' it.situacao as sititem, ' + ' it.vendedor ' + ' FROM t_vendamobile as ve, t_vendaitemmobile as it ' + ' WHERE ve.controleinterno = it.cod_venda and ve.vendedor = :vendedor'; _SQLTODAS = 'SELECT REPLICATE (''0'',5 - LEN (ve.controleinterno)) + RTrim (ve.controleinterno)as controleinterno,' + ' ve.cpf_cnpj, ' + ' REPLICATE (''0'',5 - LEN (ve.formapagto)) + RTrim (ve.formapagto)as formapagto, ' + ' ve.vendedor, ' + ' ve.emissao, ' + ' ve.situacao, ' + ' it.cod_venda, ' + ' it.cod_prod, ' + ' it.nomeproduto, ' + ' it.quantidade, ' + ' it.valor, ' + ' it.desconto, ' + ' it.total, ' + ' it.unidade, ' + ' it.situacao as sititem, ' + ' it.vendedor ' + ' FROM t_vendamobile as ve, t_vendaitemmobile as it ' + ' WHERE ve.controleinterno = it.cod_venda'; var JSONValue: TJSONValue; qryRelatorioSit: TFDQuery; begin if Params.ItemsString['Situacao'].AsString.Equals('todas') then begin JSONValue := TJSONValue.Create; qryRelatorioSit := TFDQuery.Create(nil); qryRelatorioSit.Connection := Server_FDConnection; TRY qryRelatorioSit.Active := FALSE; qryRelatorioSit.SQL.Clear; qryRelatorioSit.SQL.Text := _SQLTODAS; // qryRelatorioSit.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; qryRelatorioSit.Active := True; TRY // qryRelatorioSit.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatsituacao', qryRelatorioSit, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorioSit.Active then FreeAndNil(qryRelatorioSit); END; end else if not Params.ItemsString['Vendedor'].AsString.Equals(EmptyStr) then begin JSONValue := TJSONValue.Create; qryRelatorioSit := TFDQuery.Create(nil); qryRelatorioSit.Connection := Server_FDConnection; TRY qryRelatorioSit.Active := FALSE; qryRelatorioSit.SQL.Clear; qryRelatorioSit.SQL.Text := _SQLNOME; qryRelatorioSit.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; qryRelatorioSit.Active := True; if qryRelatorioSit.RecordCount = 0 then begin Params.ItemsString['Result'].AsString := 'Erro'; end else begin TRY // qryRelatorioSit.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatsituacao', qryRelatorioSit, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; end; FINALLY JSONValue.Free; if qryRelatorioSit.Active then FreeAndNil(qryRelatorioSit); END; end else begin JSONValue := TJSONValue.Create; qryRelatorioSit := TFDQuery.Create(nil); qryRelatorioSit.Connection := Server_FDConnection; TRY qryRelatorioSit.Active := FALSE; qryRelatorioSit.SQL.Clear; qryRelatorioSit.SQL.Text := _SQL; qryRelatorioSit.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; qryRelatorioSit.Active := True; TRY // qryRelatorioSit.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatpeditem', qryRelatorioSit, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorioSit.Active then FreeAndNil(qryRelatorioSit); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsPedidoRelatorioReplyEvent(var Params: TDWParams; var Result: string); const _SQLSITUACAO = 'SELECT ' + 'REPLICATE (''0'',5 - LEN (controleinterno)) + RTrim (controleinterno)as controleinterno,' + 'cpf_cnpj, ' + 'REPLICATE (''0'',5 - LEN (formapagto)) + RTrim (formapagto)as formapagto, ' + 'vendedor, ' + 'emissao, ' + 'valor, ' + 'desconto, ' + 'total, ' + 'situacao ' + 'FROM t_vendamobile WHERE situacao = :situacao'; _SQLNOME = 'SELECT ' + 'REPLICATE (''0'',5 - LEN (controleinterno)) + RTrim (controleinterno)as controleinterno,' + 'cpf_cnpj, ' + 'REPLICATE (''0'',5 - LEN (formapagto)) + RTrim (formapagto)as formapagto, ' + 'vendedor, ' + 'emissao, ' + 'valor, ' + 'desconto, ' + 'total, ' + 'situacao ' + 'FROM t_vendamobile WHERE vendedor = :vendedor'; var JSONValue: TJSONValue; qryRelatorio: TFDQuery; begin if (Params.ItemsString['NomeVendedor'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; qryRelatorio := TFDQuery.Create(nil); qryRelatorio.Connection := Server_FDConnection; TRY qryRelatorio.Active := FALSE; qryRelatorio.SQL.Clear; qryRelatorio.SQL.Text := _SQLNOME; qryRelatorio.ParamByName('vendedor').AsString := Params.ItemsString['NomeVendedor'].AsString; qryRelatorio.Active := True; if qryRelatorio.RecordCount = 0 then begin Params.ItemsString['Result'].AsString := 'Erro'; end else begin TRY // qryRelatorioSit.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatsituacao', qryRelatorio, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; end; FINALLY JSONValue.Free; if qryRelatorio.Active then FreeAndNil(qryRelatorio); END; end else begin JSONValue := TJSONValue.Create; qryRelatorio := TFDQuery.Create(nil); qryRelatorio.Connection := Server_FDConnection; TRY qryRelatorio.Active := FALSE; qryRelatorio.SQL.Clear; qryRelatorio.SQL.Text := _SQLSITUACAO; qryRelatorio.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; qryRelatorio.Active := True; TRY // qryRelatorio.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('relatorioaprovado', qryRelatorio, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if qryRelatorio.Active then FreeAndNil(qryRelatorio); END; end end; procedure TServerMethodDM.DWServerEvents1EventsResumoAbateReplyEvent(var Params: TDWParams; var Result: string); const _SQL = '' + 'select ' + ' replicate(''0'', (4-len(cast(ti.cod_animal as varchar))))+cast(ti.cod_animal as varchar)+ '' - '' + ' + ' case when ta.classific = '''' then RTRIM(ti.desc_animal) else RTRIM(ti.desc_animal)+ '' '' +ta.classific end as dsc_anm, ' + ' td.classe+ '' - ''+td.desc_classe as cls_pes, ' + ' count(ta.cod_pedcom) as tot_qtd, sum(ta.peso_total) as tot_kgs, sum(ta.peso_total)/15 as tot_arb, ' + ' sum(ta.peso_total)/count(ta.cod_pedcom)/15 as med_arb ' + 'from ' + ' t_animal_pesado ta, ' + ' t_pedidocomprapeso td, ' + ' t_pedidocompra tp, ' + ' t_pedidocompraitens ti ' + 'where ti.cod_pedcom = td.cod_pedcom and td.cod_pedcom = ta.cod_pedcom and ti.cod_animal = td.cod_animal and ti.cod_animal = ta.cod_animal and td.classe = ta.classe_peso and ta.peso_b is not null ' + ' and ta.cod_pedcom = tp.cod_pedcom ' + ' and tp.data_abt between :data and :data ' + 'group by ti.cod_animal, ti.desc_animal, td.classe, td.desc_classe, ta.classific ' + 'order by ti.desc_animal,ta.classific, td.classe '; var JSONValue: TJSONValue; Query3: TFDQuery; begin if (Params.ItemsString['Data'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query3 := TFDQuery.Create(nil); Query3.Connection := Server_FDConnection; TRY Query3.Active := FALSE; Query3.SQL.Clear; Query3.SQL.Text := _SQL; Query3.ParamByName('data').AsString := Params.ItemsString['Data'].AsString; Query3.Active := True; TRY // Query3.Open; JSONValue.JsonMode := Params.JsonMode; JSONValue.Encoding := Encoding; JSONValue.LoadFromDataset('resumoabate', Query3, True, Params.JsonMode, ''); Params.ItemsString['Result'].AsString := JSONValue.ToJSON; Except // END; FINALLY JSONValue.Free; if Query3.Active then FreeAndNil(Query3); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsSetPedidosItemReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'INSERT INTO T_PEDIDOVENDAITENS (num_item, cod_pedcar, cod_prod, tipo_pes, preco_unit ,quantidade, desconto, tipo_com, comissao)' { + 'VALUES (:num_item, :cod_pedcar, :cod_prod, :tipo_pes, :preco_unit , :quantidade, :desconto, :tipo_com, :comissao)'; } + 'select :num_item, :cod_pedcar, :cod_prod, :tipo_pes, :preco_unit , :quantidade, :desconto,' + 'isnull ((select tipo_com from t_vend_comis where cod_vend = :cod_vend and cod_prod = :cod_prod), 0),' + 'isnull ((select comissao from t_vend_comis where cod_vend = :cod_vend and cod_prod = :cod_prod), 0)'; _SQLBACKUP = 'INSERT INTO t_vendaitemmobile (controleinterno, cod_prod, cod_venda, nomeproduto, quantidade, valor, desconto, total, unidade, vendedor)' + 'VALUES (:controleinterno, :cod_prod, :cod_venda, :nomeproduto, :quantidade, :valor, :desconto, :total, :unidade, :vendedor) '; var sControle, sCod_prod, sCod_venda, sNomeproduto, sQuantidade, sValor, sDesconto, sTotal, sUnidade, sSituacao, sComplemento, sVendedor, sTipo_pes, sControleinterno, sCodVendedor: String; Query: TFDQuery; jValidar: TJSONObject; jResultado: TJSONObject; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; Result := EmptyStr; try if not Params.ItemsString['PedidosItem'].AsString.IsEmpty then begin jValidar := TJSONObject.ParseJSONValue(Params.ItemsString['PedidosItem'].AsString) as TJSONObject; try // Converte Json para String; sControle := (jValidar as TJSONObject).Values['cod_pedcar'].Value; sCod_prod := (jValidar as TJSONObject).Values['cod_prod'].Value; sQuantidade := (jValidar as TJSONObject).Values['quantidade'].Value; sValor := (jValidar as TJSONObject).Values['valor'].Value; sTipo_pes := (jValidar as TJSONObject).Values['tipo_pes'].Value; sControleinterno := (jValidar as TJSONObject).Values['controleinterno'].Value; sCod_venda := (jValidar as TJSONObject).Values['cod_venda'].Value; sNomeproduto := (jValidar as TJSONObject).Values['nomeproduto'].Value; sCodVendedor := (jValidar as TJSONObject).Values['codvendedor'].Value; sVendedor := (jValidar as TJSONObject).Values['vendedor'].Value; sTotal := (jValidar as TJSONObject).Values['total'].Value; Query.SQL.Clear; Query.SQL.Add(_SQL); Query.ParamByName('cod_pedcar').AsInteger := StrToInt(sControle); Query.ParamByName('cod_prod').AsInteger := StrToInt(sCod_prod); Query.ParamByName('quantidade').AsFloat := StrToFloat(sQuantidade); Query.ParamByName('preco_unit').AsCurrency := StrToCurr(StringReplace(sValor, '.', ',', [rfReplaceAll])); Query.ParamByName('tipo_pes').AsInteger := StrToInt(sTipo_pes); Query.ParamByName('num_item').AsInteger := StrToInt(ProxCod('t_pedidovendaitens', 'num_item', '000', 'cod_pedcar = ' + sControle)); Query.ParamByName('desconto').AsInteger := 0; Query.ParamByName('cod_vend').AsInteger := StrToInt(sCodVendedor); Query.ParamByName('cod_prod').AsInteger := StrToInt(sCod_prod); Query.ExecSQL; Query.SQL.Clear; Query.SQL.Add(_SQLBACKUP); Query.ParamByName('controleinterno').AsInteger := StrToInt(sControleinterno); Query.ParamByName('cod_prod').AsInteger := StrToInt(sCod_prod); Query.ParamByName('cod_venda').AsInteger := StrToInt(sCod_venda); Query.ParamByName('nomeproduto').AsString := sNomeproduto; Query.ParamByName('quantidade').AsFloat := StrToFloat(sQuantidade); Query.ParamByName('valor').AsCurrency := StrToCurr(StringReplace(sValor, '.', ',', [rfReplaceAll])); Query.ParamByName('desconto').AsCurrency := 0; Query.ParamByName('total').AsCurrency := StrToCurr(StringReplace(sTotal, '.', ',', [rfReplaceAll])); Query.ParamByName('unidade').AsString := sTipo_pes; Query.ParamByName('vendedor').AsString := sVendedor; Query.ExecSQL; Query.Connection.Commit; Params.ItemsString['Result'].AsString := 'Sucesso'; except on E: Exception do // raise Exception.Create(e.Message + 'Error Message'); Params.ItemsString['Result'].AsString := 'Erro1'; end; end else Params.ItemsString['Result'].AsString := 'Erro0'; finally FreeAndNil(jValidar); if Query.Active then Query.Close; FreeAndNil(Query); end; end; procedure TServerMethodDM.DWServerEvents1EventsUpdateItemReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'UPDATE T_VENDAITEMMOBILE' + ' SET situacao = :situacao ' + ' WHERE controleinterno = :controleinterno and vendedor = :vendedor '; _SQL2 = 'UPDATE T_VENDAITEMMOBILE' + ' SET situacao = :situacao , complemento = :complemento' + ' WHERE controleinterno = :controleinterno and vendedor = :vendedor '; var JSONValue: TJSONValue; Query1: TFDQuery; begin if (Params.ItemsString['Complemento'].AsString.Equals(EmptyStr)) then begin JSONValue := TJSONValue.Create; Query1 := TFDQuery.Create(nil); Query1.Connection := Server_FDConnection; TRY try Query1.Active := FALSE; Query1.SQL.Clear; Query1.SQL.Add(_SQL); Query1.ParamByName('situacao').AsString := QuotedStr(Params.ItemsString['Situacao'].AsString); Query1.ParamByName('controleinterno').AsInteger := Params.ItemsString['CI'].AsInteger; Query1.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query1.ExecSQL; except Params.ItemsString['Result'].AsString := 'Erro'; end; FINALLY Params.ItemsString['Result'].AsString := 'Sucesso'; JSONValue.Free; if Query1.Active then FreeAndNil(Query1); END; end else begin JSONValue := TJSONValue.Create; Query1 := TFDQuery.Create(nil); Query1.Connection := Server_FDConnection; TRY begin TRY Query1.Active := FALSE; Query1.SQL.Clear; Query1.SQL.Add(_SQL2); Query1.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; // QuotedStr(Params.ItemsString['Situacao'].AsString); Query1.ParamByName('complemento').AsString := Params.ItemsString['Complemento'].AsString; // QuotedStr(Params.ItemsString['Complemento'].AsString); Query1.ParamByName('controleinterno').AsInteger := Params.ItemsString['CI'].AsInteger; Query1.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query1.ExecSQL; Except Params.ItemsString['Result'].AsString := 'Erro'; END; end; FINALLY Params.ItemsString['Result'].AsString := 'Sucesso'; JSONValue.Free; if Query1.Active then FreeAndNil(Query1); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsUpdatePedidoReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'UPDATE T_VENDAMOBILE ' + ' SET situacao = :situacao ' + ' WHERE controleinterno = :CONTROLEINTERNO and vendedor = :vendedor'; var JSONValue: TJSONValue; Query4: TFDQuery; begin if (Params.ItemsString['Situacao'].AsString <> EmptyStr) then begin JSONValue := TJSONValue.Create; Query4 := TFDQuery.Create(nil); Query4.Connection := Server_FDConnection; TRY TRY Query4.Active := FALSE; Query4.SQL.Clear; Query4.SQL.Add(_SQL); Query4.ParamByName('situacao').AsString := Params.ItemsString['Situacao'].AsString; Query4.ParamByName('CONTROLEINTERNO').AsInteger := Params.ItemsString['CI'].AsInteger; Query4.ParamByName('vendedor').AsString := Params.ItemsString['Vendedor'].AsString; Query4.ExecSQL; Except Params.ItemsString['Result'].AsString := 'Erro'; END; FINALLY Params.ItemsString['Result'].AsString := 'Sucesso'; JSONValue.Free; if Query4.Active then FreeAndNil(Query4); END; end; end; procedure TServerMethodDM.DWServerEvents1EventsValidarReplyEvent(var Params: TDWParams; var Result: string); begin if (Params.ItemsString['Entrada'] <> nil) then Params.ItemsString['Result'].AsString := ValidarUsuario(Params.ItemsString['Entrada'].AsString); end; function TServerMethodDM.iif(Expressao, ParteTRUE, ParteFALSE: Variant): Variant; begin if (Expressao) then Result := ParteTRUE else Result := ParteFALSE; end; function TServerMethodDM.ProxCod(Tabela, Campo, Formato, Condicao: String): String; var Query: TFDQuery; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; try with Query do begin Close; SQL.Clear; SQL.Add('select max(' + Campo + ') as inc_codigo from ' + Tabela); if (Condicao <> '') then SQL.Add('where ' + Condicao); Open; if (FieldByName('inc_codigo').AsString = '') then Result := iif(Formato = '', 1, FormatFloat(Formato, 1)) else Result := iif(Formato = '', FieldByName('inc_codigo').AsInteger + 1, FormatFloat(Formato, FieldByName('inc_codigo').AsInteger + 1)); end; finally if Query.Active then Query.Close; FreeAndNil(Query); end; end; function TServerMethodDM.ValidarUsuario(JSON: String): String; const _SQL = 'SELECT * from t_usuarios where usuario like %s and senha like %s;'; var sUsuario: String; sSenha: String; Query: TFDQuery; jValidar: TJSONObject; jResultado: TJSONObject; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; Result := EmptyStr; jValidar := TJSONObject.ParseJSONValue(JSON) as TJSONObject; try try // Converte Json para String; sUsuario := (jValidar as TJSONObject).Values['usuario'].Value; sSenha := (jValidar as TJSONObject).Values['senha'].Value; // Pesquisa no banco Query.Active := FALSE; Query.SQL.Clear; Query.SQL.Text := Format(_SQL, [QuotedStr(sUsuario), QuotedStr(sSenha)]); Query.Active := True; // encontrou o usuario if not(Query.IsEmpty) then begin jResultado := TJSONObject.Create; jResultado.AddPair('resultado', 'sucesso'); jResultado.AddPair('codigo_mensagem', '200'); jResultado.AddPair('mensagem', ' '); jResultado.AddPair('cod_vendedor', IntToStr(Query.FieldByName('cod_vend').AsInteger)); Result := jResultado.ToString(); end // Não encontrou o usuario else begin jResultado := TJSONObject.Create; jResultado.AddPair('resultado', 'aviso'); jResultado.AddPair('codigo_mensagem', '300'); jResultado.AddPair('mensagem', 'Usuário e/ou senha inválidos .'); jResultado.AddPair('cod_vendedor', IntToStr(Query.FieldByName('cod_vend').AsInteger)); Result := jResultado.ToString(); end; except on E: Exception do // raise Exception.Create(e.Message + 'Error Message'); end; finally FreeAndNil(jValidar); if Query.Active then Query.Close; FreeAndNil(Query); end; end; procedure TServerMethodDM.DWServerEvents1EventsSetPedidosReplyEvent(var Params: TDWParams; var Result: string); const _SQL = 'INSERT INTO T_PEDIDOVENDA (cod_pedcar, cod_empresa, cod_pedcar_mobile, cod_doc, cod_cliente, tipo_car, cod_vend, status, comissao, cod_prest, valor_comis, data_ped, data_emb, valor_final, situacao)' + 'VALUES (:cod_pedcar, :cod_empresa, :cod_pedcar_mobile, :cod_doc, :cod_cliente, :tipo_car, :cod_vend, :status, :comissao, :cod_prest, :valor_comis, :data_ped, :data_emb, :valor_final, :situacao)'; _SQLPARC = 'INSERT INTO T_PEDIDOVENDAPARC (cod_pedcar, num_parc, data_venc, valor)' + 'VALUES (:cod_pedcar, :num_parc, :data_venc, :valor)'; _SQLDOC = 'SELECT * FROM t_docto_parc where cod_doc = :doc'; _SQLBACKUP = 'INSERT INTO t_vendamobile ( controleinterno, cpf_cnpj, formapagto, vendedor, emissao, valor, desconto, total, cod_cliente, cod_ret, data_emb, comissao, latitude, longitude) ' + 'VALUES (:controleinterno, :cpf_cnpj, :formapagto, :vendedor, :emissao, :valor, :desconto, :total, :cod_cliente, :cod_ret, :data_emb, :comissao, :latitude, :longitude)'; _SQLSTATUS = 'select status_ped from t_config'; var sCod_empresa, sCod_cliente, sStatus, sCod_vend, sData_ped, sData_emb, sValor_final, sTipo_car, sSituacao, sCod_Doc, sControle, sCpf_cnpj, sVendedor, sComissao, sLatitude, sLongitude: String; Query, QryParc, qryBackup, qryStatus: TFDQuery; jValidar: TJSONObject; jResultado: TJSONObject; Prox_cod, { NumParc, NumDias, } i: Integer; DataPed, DataEmb: TDateTime; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; QryParc := TFDQuery.Create(nil); QryParc.Connection := Server_FDConnection; qryBackup := TFDQuery.Create(nil); qryBackup.Connection := Server_FDConnection; qryStatus := TFDQuery.Create(nil); qryStatus.Connection := Server_FDConnection; Result := EmptyStr; try if not Params.ItemsString['Pedidos'].AsString.IsEmpty then begin jValidar := TJSONObject.ParseJSONValue(Params.ItemsString['Pedidos'].AsString) as TJSONObject; try qryStatus.Active := FALSE; qryStatus.SQL.Clear; qryStatus.SQL.Add(_SQLSTATUS); qryStatus.Active := True; if qryStatus.FieldByName('status_ped').AsInteger = 1 then sStatus := '1' else sStatus := '0'; Prox_cod := StrToInt(ProxCod('t_pedidovenda', 'cod_pedcar', '000000', '')); // Converte Json para String; sCod_empresa := (jValidar as TJSONObject).Values['cod_empresa'].Value; sControle := (jValidar as TJSONObject).Values['controleinterno'].Value; sCod_Doc := (jValidar as TJSONObject).Values['cod_doc'].Value; sCod_cliente := (jValidar as TJSONObject).Values['cod_cliente'].Value; // sStatus := '0'; sCod_vend := (jValidar as TJSONObject).Values['cod_vend'].Value; sData_ped := (jValidar as TJSONObject).Values['emissao'].Value; sData_emb := (jValidar as TJSONObject).Values['data_emb'].Value; sValor_final := (jValidar as TJSONObject).Values['total'].Value; sTipo_car := (jValidar as TJSONObject).Values['tipo_car'].Value; sSituacao := (jValidar as TJSONObject).Values['situacao'].Value; sCpf_cnpj := (jValidar as TJSONObject).Values['cpf_cnpj'].Value; sVendedor := (jValidar as TJSONObject).Values['vendedor'].Value; sComissao := (jValidar as TJSONObject).Values['comissao'].Value; sLatitude := (jValidar as TJSONObject).Values['latitude'].Value; sLongitude := (jValidar as TJSONObject).Values['longitude'].Value; // DataEmb := StrToDateTime(sData_ped); QryParc.SQL.Clear; QryParc.SQL.Add(_SQLDOC); QryParc.ParamByName('doc').AsInteger := StrToInt(sCod_Doc); QryParc.Active := True; { if QryParc.RecordCount > 0 then begin NumParc := QryParc.FieldByName('num_parc').AsInteger; NumDias := QryParc.FieldByName('dias_entre_parc').AsInteger; end else begin NumParc := 0; NumDias := 0; end; } Query.SQL.Clear; Query.SQL.Add(_SQL); Query.ParamByName('cod_pedcar').AsInteger := Prox_cod; Query.ParamByName('cod_empresa').AsInteger := StrToInt(sCod_empresa); Query.ParamByName('cod_pedcar_mobile').AsInteger := StrToInt(sControle); Query.ParamByName('cod_doc').AsInteger := StrToInt(sCod_Doc); Query.ParamByName('cod_cliente').AsInteger := StrToInt(sCod_cliente); Query.ParamByName('tipo_car').AsInteger := StrToInt(sTipo_car); Query.ParamByName('cod_vend').AsInteger := StrToInt(sCod_vend); Query.ParamByName('status').AsInteger := StrToInt(sStatus); Query.ParamByName('comissao').AsInteger := StrToInt(sComissao); Query.ParamByName('cod_prest').AsInteger := 1; Query.ParamByName('valor_comis').AsFloat := 0; Query.ParamByName('data_ped').AsDateTime := StrToDate(FormatDateTime('dd/mm/yyyy', StrToDateTime(sData_ped))); Query.ParamByName('data_emb').AsDateTime := StrToDate(FormatDateTime('dd/mm/yyyy', StrToDateTime(sData_emb))); // StrToDate(sData_ped); Query.ParamByName('valor_final').AsCurrency := 0; // StrToCurr(StringReplace(sValor_final, '.', ',', [rfReplaceAll])); Query.ParamByName('situacao').AsString := sSituacao; Query.ExecSQL; Query.Connection.Commit; // ShowMessage(Query.SQL.Text); qryBackup.SQL.Clear; qryBackup.SQL.Add(_SQLBACKUP); qryBackup.ParamByName('controleinterno').AsInteger := StrToInt(sControle); qryBackup.ParamByName('cpf_cnpj').AsString := sCpf_cnpj; qryBackup.ParamByName('formapagto').AsInteger := StrToInt(sCod_Doc); qryBackup.ParamByName('vendedor').AsString := sVendedor; qryBackup.ParamByName('emissao').AsDateTime := StrToDateTime(sData_ped); qryBackup.ParamByName('valor').AsCurrency := StrToCurr(StringReplace(sValor_final, '.', ',', [rfReplaceAll])); qryBackup.ParamByName('desconto').AsCurrency := 0; qryBackup.ParamByName('total').AsCurrency := StrToCurr(StringReplace(sValor_final, '.', ',', [rfReplaceAll])); qryBackup.ParamByName('cod_cliente').AsInteger := StrToInt(sCod_cliente); qryBackup.ParamByName('cod_ret').AsInteger := Prox_cod; qryBackup.ParamByName('data_emb').AsDateTime := StrToDateTime(sData_emb); qryBackup.ParamByName('comissao').AsInteger := StrToInt(sComissao); qryBackup.ParamByName('latitude').AsString := sLatitude; qryBackup.ParamByName('longitude').AsString := sLongitude; qryBackup.ExecSQL; qryBackup.Connection.Commit; Query.SQL.Clear; Query.SQL.Add('select cod_pedcar, num_parc, data_venc, valor '); Query.SQL.Add('from t_pedidovendaparc where cod_pedcar = cod_pedcar and cod_pedcar = :cod_pedcar'); Query.ParamByName('cod_pedcar').AsInteger := Prox_cod; Query.Open(); // Query.ParamByName('cod_pedcar').AsInteger := Prox_cod; // Query.ParamByName('num_parc').AsInteger := 1; // Query.ParamByName('data_venc').AsDateTime := Date; // // StrToDate(sData_ped); // Query.ParamByName('valor').AsFloat := 0; // for i := 1 to NumParc do QryParc.First; if QryParc.IsEmpty then begin Query.Insert; Query.FieldByName('cod_pedcar').AsInteger := Prox_cod; Query.FieldByName('num_parc').AsInteger := 1; Query.FieldByName('data_venc').Value := StrToDate(FormatDateTime('dd/mm/yyyy', StrToDateTime(sData_ped))); Query.FieldByName('valor').AsFloat := 0; Query.Post; end else while not QryParc.Eof do begin Query.Insert; Query.FieldByName('cod_pedcar').AsInteger := Prox_cod; Query.FieldByName('num_parc').AsInteger := QryParc.FieldByName('num_parc').AsInteger; Query.FieldByName('data_venc').Value := IncDay(StrToDate(FormatDateTime('dd/mm/yyyy', StrToDateTime(sData_ped))), QryParc.FieldByName('qtd_dias').AsInteger); Query.FieldByName('valor').AsFloat := 0; Query.Post; QryParc.Next; end; Params.ItemsString['Result'].AsString := 'Sucesso'; Params.ItemsString['Cod'].AsString := IntToStr(Prox_cod); except on E: Exception do // raise Exception.Create(e.Message + 'Error Message'); Params.ItemsString['Result'].AsString := 'Erro1'; end; end else Params.ItemsString['Result'].AsString := 'Erro0'; finally FreeAndNil(jValidar); if Query.Active then Query.Close; FreeAndNil(Query); end; end; procedure TServerMethodDM.DWServerEvents1EventsSetPreCadReplyEvent(var Params: TDWParams; var Result: string); const _SQLPRECAD = 'INSERT INTO T_CLIENTE_PRECAD' + '(codigo, cpfcnpj, nome, endereco, bairro, cidade, estado, cep, telefone, contato, celular, email, latitude,longitude, status, cod_vendedor, aniversario, formapagamento, limitecred)' + 'VALUES' + '(:codigo, :cpfcnpj, :nome, :endereco, :bairro, :cidade, :estado, :cep, :telefone, :contato, :celular, :email, :latitude, :longitude, :status, :cod_vendedor, :aniversario, :formapagamento, :limitecred)'; var scodigo, scpfcnpj, snome, sendereco, sbairro, scidade, sestado, scep, stelefone, scontato, scelular, semail, sLatitude, sLongitude, sStatus, scod_vendedor, saniversario, sformapagamento, slimitecred, scod: String; Query, QryParc, qryBackup, qryStatus: TFDQuery; jValidar: TJSONObject; JR: TJsonTextReader; jResultado: TJSONObject; Prox_cod, { NumParc, NumDias, } i: Integer; DataPed, DataEmb: TDateTime; Recebido: TStringStream; sFoto: String; SR: TStringReader; Input: TStringStream; Output: TBytesStream; Base64: String; JSONValue: TJSONValue; QuerySinc1, qryAux: TFDQuery; ljo: TJSONObject; StreamIn: TStream; StreamOut: TStringStream; Result1: TJSONArray; Fotos: string; LFirst: Integer; LShow: Integer; BStrm: TBytesStream; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; Result := EmptyStr; try if not Params.ItemsString['PreCad'].AsString.IsEmpty then begin jValidar := TJSONObject.ParseJSONValue(Params.ItemsString['PreCad'].AsString) as TJSONObject; try // Converte Json para String; scod := (jValidar as TJSONObject).Values['codigo'].Value; scpfcnpj := (jValidar as TJSONObject).Values['cpfcnpj'].Value; snome := (jValidar as TJSONObject).Values['nome'].Value; sendereco := (jValidar as TJSONObject).Values['endereco'].Value; sbairro := (jValidar as TJSONObject).Values['bairro'].Value; // sStatus := '0'; scidade := (jValidar as TJSONObject).Values['cidade'].Value; sestado := (jValidar as TJSONObject).Values['estado'].Value; scep := (jValidar as TJSONObject).Values['cep'].Value; stelefone := (jValidar as TJSONObject).Values['telefone'].Value; scontato := (jValidar as TJSONObject).Values['contato'].Value; scelular := (jValidar as TJSONObject).Values['celular'].Value; semail := (jValidar as TJSONObject).Values['email'].Value; sLatitude := (jValidar as TJSONObject).Values['latitude'].Value; sLongitude := (jValidar as TJSONObject).Values['longitude'].Value; sStatus := (jValidar as TJSONObject).Values['status'].Value; scod_vendedor := (jValidar as TJSONObject).Values['cod_vendedor'].Value; saniversario := (jValidar as TJSONObject).Values['aniversario'].Value; sformapagamento := (jValidar as TJSONObject).Values['formapagamento'].Value; slimitecred := (jValidar as TJSONObject).Values['limitecred'].Value; Query.SQL.Clear; Query.SQL.Add(_SQLPRECAD); Query.ParamByName('codigo').AsString := scod; Query.ParamByName('cpfcnpj').AsString := scpfcnpj; Query.ParamByName('nome').AsString := snome; Query.ParamByName('endereco').AsString := sendereco; Query.ParamByName('bairro').AsString := sbairro; Query.ParamByName('cidade').AsString := scidade; Query.ParamByName('estado').AsString := sestado; Query.ParamByName('cep').AsString := scep; Query.ParamByName('telefone').AsString := stelefone; Query.ParamByName('contato').AsString := scontato; Query.ParamByName('celular').AsString := scelular; Query.ParamByName('email').AsString := semail; Query.ParamByName('latitude').AsString := sLatitude; Query.ParamByName('longitude').AsString := sLongitude; Query.ParamByName('status').AsInteger := StrToInt(sStatus); Query.ParamByName('cod_vendedor').AsInteger := StrToInt(scod_vendedor); Query.ParamByName('aniversario').AsString := saniversario; Query.ParamByName('formapagamento').AsString := sformapagamento; Query.ParamByName('limitecred').AsString := slimitecred; Query.ExecSQL; Query.Connection.Commit; except on E: Exception do // raise Exception.Create(e.Message + 'Error Message'); Params.ItemsString['Result'].AsString := 'Erro1'; end; end else Params.ItemsString['Result'].AsString := 'Erro0'; finally FreeAndNil(jValidar); if Query.Active then Query.Close; FreeAndNil(Query); end; end; procedure TServerMethodDM.DWServerEvents1EventsgetFotoPrecadReplyEvent(var Params: TDWParams; var Result: string); const _SQLPRECAD = 'UPDATE T_CLIENTE_PRECAD' + 'SET FOTO = :foto ' + 'WHERE CODIGO = :CODIGO'; var scod, sFoto: String; Query, QryParc, qryBackup, qryStatus: TFDQuery; jValidar: TJSONObject; jResultado: TJSONObject; Prox_cod, { NumParc, NumDias, } i: Integer; DataPed, DataEmb: TDateTime; Recebido: TStringStream; StreamIn: TStream; StreamOut: TStringStream; Result1: TJSONArray; Fotos: string; LFirst: Integer; LShow: Integer; BStrm: TBytesStream; begin Query := TFDQuery.Create(nil); Query.Connection := Server_FDConnection; Result := EmptyStr; try if not Params.ItemsString['foto'].AsString.IsEmpty then begin jValidar := TJSONObject.ParseJSONValue(Params.ItemsString['foto'].AsString) as TJSONObject; try // Converte Json para String; scod := (jValidar as TJSONObject).Values['codigo'].Value; sFoto := (jValidar as TJSONObject).Values['foto'].Value; Query.SQL.Clear; Query.SQL.Add(_SQLPRECAD); Query.ParamByName('codigo').AsString := scod; Query.ParamByName('foto').AsString := sFoto ; Query.ExecSQL; Query.Connection.Commit; except on E: Exception do // raise Exception.Create(e.Message + 'Error Message'); Params.ItemsString['Result'].AsString := 'Erro1'; end; end else Params.ItemsString['Result'].AsString := 'Erro0'; finally FreeAndNil(jValidar); if Query.Active then Query.Close; FreeAndNil(Query); end; end; END.
unit UParam; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls, ColorBox, ExtCtrls, StdCtrls, ComCtrls, typinfo; type TClassList = array of TPersistentClass; { TParam } TParam = class(TPersistent) private FName: string; AttachedParams: array of TParam; procedure ChangeControl(Sender: TObject); virtual; abstract; public procedure AttachParam(AParam: TParam); procedure UnAttach(); property Name: string read FName; function ToControl(AParentPanel: TPanel): TControl; virtual; abstract; end; TParamList = array of TParam; { TPenColorParam } TPenColorParam = class(TParam) private FPenColor: TColor; procedure ChangeControl(Sender: TObject); override; public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TPenColorParam; published property Value: TColor read FPenColor write FPenColor; end; { TBrushColorParam } TBrushColorParam = class(TParam) private FBrushColor: TColor; procedure ChangeControl(Sender: TObject); override; public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TBrushColorParam; published property Value: TColor read FBrushColor write FBrushColor; end; { TWidthParam } TWidthParam = class(TParam) private FWidth: integer; procedure ChangeControl(Sender: TObject); override; public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TWidthParam; published property Value: integer read FWidth write FWidth; end; { TRadiusParam } TRadiusParam = class(TParam) private FRadius: integer; procedure ChangeControl(Sender: TObject); override; public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TRadiusParam; published property Value: integer read FRadius write FRadius; end; { TBrushStyleParam } TBrushStyleParam = class(TParam) private FFillIndex: integer; const FFillStyles: array[0..7] of TBrushStyle = (bsSolid, bsClear, bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross); function FGetBrushStyle: TBrushStyle; procedure ChangeControl(Sender: TObject); override; procedure FDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TBrushStyleParam; procedure FSetBrushStyle(ABrushStyle: TBrushStyle); published property Value: TBrushStyle read FGetBrushStyle write FSetBrushStyle; end; { TPenStyleParam } TPenStyleParam = class(TParam) private FLineIndex: integer; const FPenStyles: array[0..5] of TPenStyle = (psSolid, psClear, psDot, psDash, psDashDot, psDashDotDot); function FGetPenStyle: TPenStyle; procedure ChangeControl(Sender: TObject); override; procedure FDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); procedure FSetPenStyle(APenStyle: TPenStyle); public constructor Create; function ToControl(AParentPanel: TPanel): TControl; override; function Copy: TPenStyleParam; published property Value: TPenStyle read FGetPenStyle write FSetPenStyle; end; implementation uses UHistory; { TParam } procedure TParam.AttachParam(AParam: TParam); begin SetLength(AttachedParams, Length(AttachedParams) + 1); AttachedParams[High(AttachedParams)] := AParam; end; procedure TParam.UnAttach(); begin SetLength(AttachedParams, 0); end; { TPenStyleParam } function TPenStyleParam.FGetPenStyle: TPenStyle; begin Result := FPenStyles[FLineIndex]; end; procedure TPenStyleParam.ChangeControl(Sender: TObject); var p: TParam; begin FLineIndex := (Sender as TComboBox).ItemIndex; if AttachedParams <> nil then begin for p in AttachedParams do (p as TPenStyleParam).FLineIndex := (Sender as TComboBox).ItemIndex; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; procedure TPenStyleParam.FDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); begin with (Control as TComboBox).Canvas do begin FillRect(ARect); Pen.Color := clBlack; Pen.Style := FPenStyles[Index]; Pen.Width := 1; Line(ARect.left + 1, (ARect.Top + ARect.Bottom) div 2, ARect.Right - 1, (ARect.Top + ARect.Bottom) div 2); end; end; procedure TPenStyleParam.FSetPenStyle(APenStyle: TPenStyle); var i: SizeInt; begin for i := Low(FPenStyles) to High(FPenStyles) do begin if APenStyle = FPenStyles[i] then begin FLineIndex := i; exit; end; end; end; constructor TPenStyleParam.Create; begin FName := 'Стиль линии'; end; function TPenStyleParam.ToControl(AParentPanel: TPanel): TControl; var i: TPenStyle; s: string; begin Result := TComboBox.Create(AParentPanel); with Result as TComboBox do begin Parent := AParentPanel; Style := csOwnerDrawFixed; OnDrawItem := @FDrawItem; OnChange := @ChangeControl; for i in FPenStyles do begin WriteStr(s, i); Items.Add(s); end; ReadOnly := True; ItemIndex := FLineIndex; end; end; function TPenStyleParam.Copy: TPenStyleParam; begin Result := TPenStyleParam.Create; Result.FName := FName; Result.FLineIndex := FLineIndex; end; { TBrushStyleParam } function TBrushStyleParam.FGetBrushStyle: TBrushStyle; begin Result := FFillStyles[FFillIndex]; end; procedure TBrushStyleParam.ChangeControl(Sender: TObject); var p: TParam; begin FFillIndex := (Sender as TComboBox).ItemIndex; if Length(AttachedParams) > 0 then begin for p in AttachedParams do (p as TBrushStyleParam).FFillIndex := (Sender as TComboBox).ItemIndex; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; procedure TBrushStyleParam.FDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState); begin with (Control as TComboBox).Canvas do begin FillRect(ARect); Pen.Color := clBlack; Pen.Style := psClear; Pen.Width := 1; Brush.Style := FFillStyles[Index]; if Index <> 1 then Brush.color := clBlack; Rectangle(ARect.Left + 1, ARect.Top + 1, ARect.Right - 1, ARect.Bottom - 1); end; end; constructor TBrushStyleParam.Create; begin FName := 'Стиль заливки'; FFillIndex := 1; end; function TBrushStyleParam.ToControl(AParentPanel: TPanel): TControl; var i: TBrushStyle; s: string; begin Result := TComboBox.Create(AParentPanel); with Result as TComboBox do begin Parent := AParentPanel; Style := csOwnerDrawFixed; OnDrawItem := @FDrawItem; OnChange := @ChangeControl; for i in FFillStyles do begin WriteStr(s, i); Items.Add(s); end; ReadOnly := True; ItemIndex := FFillIndex; end; end; function TBrushStyleParam.Copy: TBrushStyleParam; begin Result := TBrushStyleParam.Create; Result.FName := FName; Result.FFillIndex := FFillIndex; end; procedure TBrushStyleParam.FSetBrushStyle(ABrushStyle: TBrushStyle); var i: SizeInt; begin for i := Low(FFillStyles) to High(FFillStyles) do begin if ABrushStyle = FFillStyles[i] then begin FFillIndex := i; exit; end; end; end; { TRadiusParam } procedure TRadiusParam.ChangeControl(Sender: TObject); var p: TParam; begin FRadius := (Sender as TTrackBar).Position; if Length(AttachedParams) > 0 then begin for p in AttachedParams do (p as TRadiusParam).FRadius := (Sender as TTrackBar).Position; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; constructor TRadiusParam.Create; begin FName := 'Радиус'; FRadius := 5; end; function TRadiusParam.ToControl(AParentPanel: TPanel): TControl; begin Result := TTrackBar.Create(AParentPanel); with Result as TTrackBar do begin OnChange := @ChangeControl; Parent := AParentPanel; Min := 5; Max := 100; PageSize := 1; Position := FRadius; end; end; function TRadiusParam.Copy: TRadiusParam; begin Result := TRadiusParam.Create; Result.FName := FName; Result.FRadius := FRadius; end; { TWidthParam } procedure TWidthParam.ChangeControl(Sender: TObject); var p: TParam; begin FWidth := (Sender as TTrackBar).Position; if Length(AttachedParams) > 0 then begin for p in AttachedParams do (p as TWidthParam).FWidth := (Sender as TTrackBar).Position; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; constructor TWidthParam.Create; begin FName := 'Толщина линии'; FWidth := 1; end; function TWidthParam.ToControl(AParentPanel: TPanel): TControl; begin Result := TTrackBar.Create(AParentPanel); with Result as TTrackBar do begin OnChange := @ChangeControl; Parent := AParentPanel; Min := 1; Max := 20; PageSize := 1; Position := FWidth; end; end; function TWidthParam.Copy: TWidthParam; begin Result := TWidthParam.Create; Result.FName := FName; Result.FWidth := FWidth; end; { TBrushColorParam } procedure TBrushColorParam.ChangeControl(Sender: TObject); var p: TParam; begin FBrushColor := (Sender as TColorBox).Selected; if Length(AttachedParams) > 0 then begin for p in AttachedParams do (p as TBrushColorParam).FBrushColor := (Sender as TColorBox).Selected; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; constructor TBrushColorParam.Create; begin FName := 'Цвет кисти'; FBrushColor := clBlack; end; function TBrushColorParam.ToControl(AParentPanel: TPanel): TControl; begin Result := TColorBox.Create(AParentPanel); with Result as TColorBox do begin Parent := AParentPanel; ColorRectWidth := 10; Style := [cbCustomColor, cbExtendedColors, cbPrettyNames, cbStandardColors]; Selected := FBrushColor; OnSelect := @ChangeControl; end; end; function TBrushColorParam.Copy: TBrushColorParam; begin Result := TBrushColorParam.Create; Result.FName := FName; Result.FBrushColor := FBrushColor; end; { TPenColorParam } procedure TPenColorParam.ChangeControl(Sender: TObject); var p: TParam; begin FPenColor := (Sender as TColorBox).Selected; if Length(AttachedParams) > 0 then begin for p in AttachedParams do (p as TPenColorParam).FPenColor := (Sender as TColorBox).Selected; (Sender as TControl).GetTopParent.Invalidate; History.Push; end; end; constructor TPenColorParam.Create; begin FName := 'Цвет линии'; FPenColor := clBlack; end; function TPenColorParam.ToControl(AParentPanel: TPanel): TControl; begin Result := TColorBox.Create(AParentPanel); with Result as TColorBox do begin Parent := AParentPanel; ColorRectWidth := 10; Style := [cbCustomColor, cbExtendedColors, cbPrettyNames, cbStandardColors]; Selected := FPenColor; OnSelect := @ChangeControl; end; end; function TPenColorParam.Copy: TPenColorParam; begin Result := TPenColorParam.Create; Result.FName := FName; Result.FPenColor := FPenColor; end; begin RegisterClasses(TClassList.Create(TBrushColorParam, TPenColorParam, TPenStyleParam, TBrushStyleParam, TWidthParam, TRadiusParam)); end.
unit kwPopTreeNodeGetNext; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopTreeNodeGetNext.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::TreeViewWords::pop_TreeNode_GetNext // // Помещает в стек указатель на следующий узел в дереве. Подробности см. TTreeNode.GetNext // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses ComCtrls, tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwTreeNodeFromStackWord.imp.pas} TkwPopTreeNodeGetNext = {final} class(_kwTreeNodeFromStackWord_) {* Помещает в стек указатель на следующий узел в дереве. Подробности см. TTreeNode.GetNext } protected // realized methods procedure DoWithTTreeNode(const aTreeView: TTreeNode; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopTreeNodeGetNext {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, Controls, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopTreeNodeGetNext; {$Include ..\ScriptEngine\kwTreeNodeFromStackWord.imp.pas} // start class TkwPopTreeNodeGetNext procedure TkwPopTreeNodeGetNext.DoWithTTreeNode(const aTreeView: TTreeNode; const aCtx: TtfwContext); //#UC START# *512F49F103A8_512F4A8901C1_var* //#UC END# *512F49F103A8_512F4A8901C1_var* begin //#UC START# *512F49F103A8_512F4A8901C1_impl* aCtx.rEngine.PushObj(aTreeView.GetNext); //#UC END# *512F49F103A8_512F4A8901C1_impl* end;//TkwPopTreeNodeGetNext.DoWithTTreeNode class function TkwPopTreeNodeGetNext.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:TreeNode:GetNext'; end;//TkwPopTreeNodeGetNext.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwTreeNodeFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit furqLoader; interface uses Classes, SysUtils ; function FURQLoadQS1(aStream: TStream): string; function FURQLoadQS2(aStream: TStream): string; function FURQLoadQST(aStream: TStream): string; type EFURQLoadError = class(Exception); implementation uses //JclMath, furqDecoders; type TQS2Header = packed record rSignature: array[0..3] of Char; rVersion : Longword; rLength : Longword; rCRC32 : Longword; end; const sUnexpectedEndOfStream = 'Неожиданный конец данных'; sCorruptedData = 'Испорченные данные'; function FURQLoadQS2(aStream: TStream): string; var l_B: Byte; l_Header: TQS2Header; l_BFLength: Longword; l_P1, l_P2: Pointer; l_Mod: Integer; l_CRC: Longword; begin Result := ''; // ищем нулевой байт (там вначале заглушка) l_B := 255; while (l_B <> 0) do begin if aStream.Read(l_B, 1) <> 1 then raise EFURQLoadError.Create(sUnexpectedEndOfStream); end; // читаем заголовок if aStream.Read(l_Header, SizeOf(TQS2Header)) <> SizeOf(TQS2Header) then raise EFURQLoadError.Create(sUnexpectedEndOfStream); // проверяем сигнатуру if PChar(@l_Header) <> 'QS2' then raise EFURQLoadError.Create(sCorruptedData); l_BFLength := l_Header.rLength; l_Mod := l_Header.rLength mod 8; if l_Mod <> 0 then l_BFLength := l_BFLength + 8 - l_Mod; // читаем данные и расшифровываем l_P1 := GetMemory(l_BFLength); l_P2 := GetMemory(l_BFLength); try if aStream.Read(l_P1^, l_BFLength) <> l_BFLength then raise EFURQLoadError.Create(sUnexpectedEndOfStream); BFDecode(l_P1, l_BFLength, l_P2); QS2Decode(l_P2, l_Header.rLength, l_P1); { TODO : Проверка CRC32 } l_CRC := Crc32(l_P1, l_Header.rLength); if l_CRC <> l_Header.rCRC32 then raise EFURQLoadError.Create(sCorruptedData); SetLength(Result, l_Header.rLength); Move(l_P1^, Result[1], l_Header.rLength); finally FreeMemory(l_P1); FreeMemory(l_P2); end; end; function FURQLoadQS1(aStream: TStream): string; begin Result := FURQLoadQST(aStream); QS1Decode(Pointer(Result), Length(Result)); end; function FURQLoadQST(aStream: TStream): string; var l_Len: Cardinal; begin Result := ''; l_Len := aStream.Size - aStream.Position; SetLength(Result, l_Len); aStream.Read(Pointer(Result)^, l_Len); end; end.
unit cabal_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,seibu_sound,rom_engine, pal_engine,sound_engine; function iniciar_cabal:boolean; implementation const cabal_rom:array[0..3] of tipo_roms=( (n:'13.7h';l:$10000;p:0;crc:$00abbe0c),(n:'11.6h';l:$10000;p:$1;crc:$44736281), (n:'12.7j';l:$10000;p:$20000;crc:$d763a47c),(n:'10.6j';l:$10000;p:$20001;crc:$96d5e8af)); cabal_char:tipo_roms=(n:'5-6s';l:$4000;p:0;crc:$6a76955a); cabal_sprites:array[0..7] of tipo_roms=( (n:'sp_rom1.bin';l:$10000;p:0;crc:$34d3cac8),(n:'sp_rom2.bin';l:$10000;p:$1;crc:$4e49c28e), (n:'sp_rom3.bin';l:$10000;p:$20000;crc:$7065e840),(n:'sp_rom4.bin';l:$10000;p:$20001;crc:$6a0e739d), (n:'sp_rom5.bin';l:$10000;p:$40000;crc:$0e1ec30e),(n:'sp_rom6.bin';l:$10000;p:$40001;crc:$581a50c1), (n:'sp_rom7.bin';l:$10000;p:$60000;crc:$55c44764),(n:'sp_rom8.bin';l:$10000;p:$60001;crc:$702735c9)); cabal_tiles:array[0..7] of tipo_roms=( (n:'bg_rom1.bin';l:$10000;p:0;crc:$1023319b),(n:'bg_rom2.bin';l:$10000;p:$1;crc:$3b6d2b09), (n:'bg_rom3.bin';l:$10000;p:$20000;crc:$420b0801),(n:'bg_rom4.bin';l:$10000;p:$20001;crc:$77bc7a60), (n:'bg_rom5.bin';l:$10000;p:$40000;crc:$543fcb37),(n:'bg_rom6.bin';l:$10000;p:$40001;crc:$0bc50075), (n:'bg_rom7.bin';l:$10000;p:$60000;crc:$d28d921e),(n:'bg_rom8.bin';l:$10000;p:$60001;crc:$67e4fe47)); cabal_sound:array[0..1] of tipo_roms=( (n:'4-3n';l:$2000;p:0;crc:$4038eff2),(n:'3-3p';l:$8000;p:$8000;crc:$d9defcbf)); cabal_adpcm:array[0..1] of tipo_roms=( (n:'2-1s';l:$10000;p:0;crc:$850406b4),(n:'1-1u';l:$10000;p:$10000;crc:$8b3e0789)); //Dip cabal_dip_a:array [0..11] of def_dip=( (mask:$f;name:'Coinage';number:16;dip:((dip_val:$a;dip_name:'6C 1C'),(dip_val:$b;dip_name:'5C 1C'),(dip_val:$c;dip_name:'4C 1C'),(dip_val:$d;dip_name:'3C 1C'),(dip_val:$1;dip_name:'8C 3C'),(dip_val:$e;dip_name:'2C 1C'),(dip_val:$2;dip_name:'5C 3C'),(dip_val:$3;dip_name:'3C 2C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$4;dip_name:'2C 3C'),(dip_val:$9;dip_name:'1C 2C'),(dip_val:$8;dip_name:'1C 3C'),(dip_val:$7;dip_name:'1C 4C'),(dip_val:$6;dip_name:'1C 5C'),(dip_val:$5;dip_name:'1C 6C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$3;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$c;dip_name:'1C 2C'),(dip_val:$8;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 5C'),(dip_val:$0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Coin Mode';number:2;dip:((dip_val:$10;dip_name:'Mode 1'),(dip_val:$0;dip_name:'Mode 2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Invert Buttons';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Track Ball';number:2;dip:((dip_val:$80;dip_name:'Small'),(dip_val:$0;dip_name:'Large'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$300;name:'Lives';number:4;dip:((dip_val:$200;dip_name:'2'),(dip_val:$300;dip_name:'3'),(dip_val:$100;dip_name:'5'),(dip_val:$0;dip_name:'121 (Cheat)'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c00;name:'Bonus Life';number:4;dip:((dip_val:$c00;dip_name:'150k 650k 500k+'),(dip_val:$800;dip_name:'200k 800k 600k+'),(dip_val:$400;dip_name:'300k 1000k 700k+'),(dip_val:$0;dip_name:'300k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$3000;name:'Difficulty';number:4;dip:((dip_val:$3000;dip_name:'Easy'),(dip_val:$2000;dip_name:'Normal'),(dip_val:$1000;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8000;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8000;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$1ffff] of word; main_ram:array[0..$7fff] of word; bg_ram:array[0..$1ff] of word; fg_ram:array[0..$3ff] of word; procedure update_video_cabal; var f,color,x,y,nchar,atrib:word; begin //Background for f:=0 to $ff do begin atrib:=bg_ram[f]; color:=(atrib shr 12) and $f; if (gfx[2].buffer[f] or buffer_color[color+$40]) then begin x:=f mod 16; y:=f div 16; nchar:=atrib and $fff; put_gfx(x*16,y*16,nchar,(color shl 4)+512,2,2); gfx[2].buffer[f]:=false; end; end; //Foreground for f:=0 to $3ff do begin atrib:=fg_ram[f]; color:=(atrib shr 10) and $3f; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f mod 32; y:=f div 32; nchar:=atrib and $3ff; put_gfx_trans(x*8,y*8,nchar,color shl 2,1,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,2,0,0,256,256,3); //Sprites for f:=$1ff downto 0 do begin y:=main_ram[(f*4)+$1c00]; if (y and $100)<>0 then begin atrib:=main_ram[(f*4)+$1c01]; x:=main_ram[(f*4)+$1c02]; nchar:=atrib and $fff; color:=(x and $7800) shr 7; put_gfx_sprite(nchar,color+256,(x and $400)<>0,false,1); actualiza_gfx_sprite(x,y,3,1); end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,3); actualiza_trozo_final(0,16,256,224,3); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_cabal; begin if event.arcade then begin //CONTROL1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800); if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000); if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000); if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $bfff) else marcade.in0:=(marcade.in0 or $4000); if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $7fff) else marcade.in0:=(marcade.in0 or $8000); //CONTROL2 if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bfff) else marcade.in1:=(marcade.in1 or $4000); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $7fff) else marcade.in1:=(marcade.in1 or $8000); //Coins if arcade_input.coin[1] then seibu_snd_0.input:=(seibu_snd_0.input or $1) else seibu_snd_0.input:=(seibu_snd_0.input and $fe); if arcade_input.coin[0] then seibu_snd_0.input:=(seibu_snd_0.input or $2) else seibu_snd_0.input:=(seibu_snd_0.input and $fd); end; end; procedure cabal_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=seibu_snd_0.z80.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //Sound CPU seibu_snd_0.z80.run(frame_s); frame_s:=frame_s+seibu_snd_0.z80.tframes-seibu_snd_0.z80.contador; if f=239 then begin update_video_cabal; m68000_0.irq[1]:=HOLD_LINE; end; end; eventos_cabal; video_sync; end; end; function cabal_getword(direccion:dword):word; begin case direccion of 0..$3ffff:cabal_getword:=rom[direccion shr 1]; $40000..$4ffff:cabal_getword:=main_ram[(direccion and $ffff) shr 1]; $60000..$607ff:cabal_getword:=fg_ram[(direccion and $7ff) shr 1]; $80000..$803ff:cabal_getword:=bg_ram[(direccion and $3ff) shr 1]; $a0000:cabal_getword:=marcade.dswa; //DSW $a0008:cabal_getword:=marcade.in0; $a000c:cabal_getword:=$ffff; //track 0 $a000a,$a000e:cabal_getword:=$0; //track 1 $a0010:cabal_getword:=marcade.in1; //input $e0000..$e07ff:cabal_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $e8000..$e800d:cabal_getword:=seibu_snd_0.get((direccion and $e) shr 1); end; end; procedure cabal_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.b:=pal4bit(tmp_color shr 8); color.g:=pal4bit(tmp_color shr 4); color.r:=pal4bit(tmp_color); set_pal_color(color,numero); case numero of 0..$ff:buffer_color[numero shr 2]:=true; 512..767:buffer_color[((numero shl 4) and $f)+$40]:=true; end; end; begin case direccion of 0..$3ffff:; //ROM $40000..$4ffff:main_ram[(direccion and $ffff) shr 1]:=valor; $60000..$607ff:if fg_ram[(direccion and $7ff) shr 1]<>valor then begin fg_ram[(direccion and $7ff) shr 1]:=valor; gfx[0].buffer[(direccion and $7ff) shr 1]:=true; end; $80000..$803ff:if bg_ram[(direccion and $3ff) shr 1]<>valor then begin bg_ram[(direccion and $3ff) shr 1]:=valor; gfx[2].buffer[(direccion and $3ff) shr 1]:=true; end; $c0040:; //NOP $c0080:main_screen.flip_main_screen:=(valor<>0); //Flip screen $e0000..$e07ff:if (buffer_paleta[(direccion and $7ff) shr 1]<>valor) then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,(direccion and $7ff) shr 1); end; $e8000..$e800d:seibu_snd_0.put((direccion and $e) shr 1,valor); end; end; //Main procedure reset_cabal; begin m68000_0.reset; seibu_snd_0.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; seibu_snd_0.input:=$fc; end; function iniciar_cabal:boolean; const pc_x:array[0..7] of dword=(3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0); pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16); pt_x:array[0..15] of dword=(3, 2, 1, 0, 16+3, 16+2, 16+1, 16+0, 32*16+3, 32*16+2, 32*16+1, 32*16+0, 33*16+3, 33*16+2, 33*16+1, 33*16+0); pt_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32 ); ps_x:array[0..15] of dword=(3, 2, 1, 0, 16+3, 16+2, 16+1, 16+0, 32+3, 32+2, 32+1, 32+0, 48+3, 48+2, 48+1, 48+0); ps_y:array[0..15] of dword=(30*32, 28*32, 26*32, 24*32, 22*32, 20*32, 18*32, 16*32, 14*32, 12*32, 10*32, 8*32, 6*32, 4*32, 2*32, 0*32 ); var memoria_temp:array[0..$7ffff] of byte; begin llamadas_maquina.bucle_general:=cabal_principal; llamadas_maquina.reset:=reset_cabal; llamadas_maquina.fps_max:=59.60; iniciar_cabal:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,256,256,true); screen_init(3,512,256,false,true); iniciar_video(256,224); //Main CPU m68000_0:=cpu_m68000.create(10000000,256); m68000_0.change_ram16_calls(cabal_getword,cabal_putword); if not(roms_load16w(@rom,cabal_rom)) then exit; //Sound Chips if not(roms_load(@memoria_temp,cabal_sound)) then exit; seibu_snd_0:=seibu_snd_type.create(SEIBU_ADPCM,3579545,256,@memoria_temp,true); copymemory(@mem_snd[$8000],@memoria_temp[$8000],$8000); //adpcm if not(roms_load(@memoria_temp,cabal_adpcm)) then exit; seibu_snd_0.adpcm_load_roms(@memoria_temp,$10000); //convertir chars if not(roms_load(@memoria_temp,cabal_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //sprites if not(roms_load16b(@memoria_temp,cabal_sprites)) then exit; init_gfx(1,16,16,$1000); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,64*16,2*4,3*4,0*4,1*4); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //tiles if not(roms_load16b(@memoria_temp,cabal_tiles)) then exit; init_gfx(2,16,16,$1000); gfx_set_desc_data(4,0,64*16,2*4,3*4,0*4,1*4); convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,false); //Dip marcade.dswa:=$efff; marcade.dswa_val:=@cabal_dip_a; //final reset_cabal; iniciar_cabal:=true; end; end.
unit AddOrderToRouteParameterProviderUnit; interface uses AddOrderToRouteRequestUnit, AddressUnit, RouteParametersUnit; type IAddOrderToRouteParameterProvider = interface ['{794E1351-AC94-40F7-8D02-DC4D7FFDFC59}'] function GetParameters: TRouteParameters; function GetAddresses: TOrderedAddressArray; end; TAddOrderToRouteParameterProvider = class(TInterfacedObject, IAddOrderToRouteParameterProvider) public function GetAddresses: TOrderedAddressArray; function GetParameters: TRouteParameters; end; implementation { TAddOrderToRouteParameterProvider } uses EnumsUnit; function TAddOrderToRouteParameterProvider.GetAddresses: TOrderedAddressArray; var Address: TOrderedAddress; begin SetLength(Result, 2); Address := TOrderedAddress.Create; Address.AddressString := '325 Broadway, New York, NY 10007, USA'; Address.Alias := 'BK Restaurant #: 20333'; Address.Latitude := 40.71615; Address.Longitude := -74.00505; Address.CurbsideLatitude := 40.71615; Address.CurbsideLongitude := -74.00505; Address.Phone := '(212) 227-7535'; Address.OrderId := 7205704; Result[0] := Address; Address := TOrderedAddress.Create; Address.AddressString := '106 Fulton St, Farmingdale, NY 11735, USA'; Address.Alias := 'BK Restaurant #: 17871'; Address.Latitude := 40.73073; Address.Longitude := -73.459283; Address.CurbsideLatitude := 40.73073; Address.CurbsideLongitude := -73.459283; Address.Phone := '(212) 566-5132'; Address.OrderId := 7205703; Result[1] := Address; end; function TAddOrderToRouteParameterProvider.GetParameters: TRouteParameters; begin Result := TRouteParameters.Create; Result.RouteName := 'Wednesday 15th of June 2016 07:01 PM (+03:00)'; Result.RouteDate := 1465948800; Result.RouteTime := 14400; Result.Optimize := TOptimize.Time; Result.RouteType := 'single'; Result.AlgorithmType := TAlgorithmType.TSP; Result.RT := False; Result.LockLast := False; Result.MemberId := '1116'; Result.DisableOptimization := False; end; end.
unit dcLUEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdvEdit, advlued, dbctrls, datacontroller, db, FFSTypes; type TdcLUEdit = class(TAdvLUEdit) private fdcLink : TdcLink; function GetDataBufIndex: integer; function GetDataController: TDataController; function GetDataField: String; function getDataSource: TDataSource; procedure SetDataBufIndex(const Value: integer); procedure setDataController(const Value: TDataController); procedure SetDataField(const Value: String); procedure SetDatasource(const Value: TDataSource); procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure Loaded; { Private declarations } protected { Protected declarations } procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; published { Published declarations } property CharCase; property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Data Entry', [TdcLUEdit]); end; { TdcLUEdit } procedure TdcLUEdit.ClearData(sender: TObject); begin text := ''; end; constructor TdcLUEdit.Create(AOwner: Tcomponent); begin inherited; // modified for our use //flat := true; //fheight := 16; //fparentcolor := true; // dc aware // font.color := FFSColor[fcsDataText]; FocusColor := FFSColor[fcsActiveEntryField]; fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; end; destructor TdcLUEdit.Destroy; begin fdclink.Free; inherited; end; function TdcLUEdit.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; function TdcLUEdit.GetDataController: TDataController; begin result := fdcLink.DataController; end; function TdcLUEdit.GetDataField: String; begin result := fdclink.FieldName; end; function TdcLUEdit.getDataSource: TDataSource; begin result := fdclink.DataSource; end; procedure TdcLUEdit.MsgFFSColorChange(var Msg: TMessage); begin font.color := FFSColor[fcsDataText]; FocusColor := FFSColor[fcsActiveEntryField]; ffontcolor := font.color; FNormalColor := FFSColor[fcsDatabackground]; end; procedure TdcLUEdit.Loaded; begin inherited; font.color := FFSColor[fcsDataText]; FocusColor := FFSColor[fcsActiveEntryField]; ffontcolor := font.color; FNormalColor := FFSColor[fcsDatabackground]; height := 16; end; procedure TdcLUEdit.ReadData(sender: TObject); begin if not assigned(fdclink.DataController) then exit; if assigned(fdclink.datacontroller.databuf) then Text := fdclink.datacontroller.databuf.AsString[DataBufIndex]; end; procedure TdcLUEdit.SetDataBufIndex(const Value: integer); begin // blank intentionally end; procedure TdcLUEdit.setDataController(const Value: TDataController); begin fdcLink.datacontroller := value; end; procedure TdcLUEdit.SetDataField(const Value: String); begin fdclink.FieldName := value; end; procedure TdcLUEdit.SetDatasource(const Value: TDataSource); begin // Blank intentionally end; procedure TdcLUEdit.WriteData(sender: TObject); begin if ReadOnly then exit; if not assigned(fdclink.DataController) then exit; if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := Text; end; end.
unit frm_pos_size_ini; interface uses IniFiles, Forms; //Visibility geht leider in OnCreate nicht...... :-( procedure SaveFormSizePos(ini: TIniFile; Section: String; Form: TForm; Visibility: Boolean = False); overload; procedure SaveFormSizePos(inifile: string; Form: TForm; Visibility: Boolean = False); overload; procedure LoadFormSizePos(ini: TIniFile; Section: String; Form: TForm; Visibility: Boolean = False); overload; procedure LoadFormSizePos(inifile: string; Form: TForm; Visibility: Boolean = False); overload; implementation procedure SaveFormSizePos(inifile: string; Form: TForm; Visibility: Boolean = False); overload; var ini: TIniFile; begin ini := TIniFile.Create(inifile); SaveFormSizePos(ini,Form.Name,Form,Visibility); ini.UpdateFile; ini.Free; end; procedure SaveFormSizePos(ini: TIniFile; Section: String; Form: TForm; Visibility: Boolean = False); overload; begin ini.WriteInteger(Section,'Left',Form.Left); ini.WriteInteger(Section,'Top',Form.Top); ini.WriteInteger(Section,'Width',Form.Width); ini.WriteInteger(Section,'Height',Form.Height); if Visibility then ini.WriteBool(Section,'Visible',Form.Visible); end; procedure LoadFormSizePos(inifile: string; Form: TForm; Visibility: Boolean = False); overload; var ini: TIniFile; begin ini := TIniFile.Create(inifile); LoadFormSizePos(ini,Form.Name,Form,Visibility); ini.Free; end; procedure LoadFormSizePos(ini: TIniFile; Section: String; Form: TForm; Visibility: Boolean = False); overload; begin Form.Left := ini.ReadInteger(Section,'Left',Form.Left); Form.Top := ini.ReadInteger(Section,'Top',Form.Top); if not(Form.BorderStyle in [bsSingle]) then begin Form.Width := ini.ReadInteger(Section,'Width',Form.Width); Form.Height := ini.ReadInteger(Section,'Height',Form.Height); end; if Form.Top > Screen.DesktopRect.Bottom - 50 then Form.Top := Screen.DesktopRect.Bottom - 100; if Form.Top < Screen.DesktopRect.Top - 50 then Form.Top := Screen.DesktopRect.Top; if Form.Left > Screen.DesktopRect.Right - 50 then Form.Left := Screen.DesktopRect.Right - 100; if Form.Left + Form.Width < Screen.DesktopRect.Left + 10 then Form.Left := Screen.DesktopRect.Left; if Visibility then Form.Visible := ini.ReadBool(Section,'Visible',False); end; end.
PROGRAM Approx; USES Random, IO; {FUNCTION ApproximatePI1(n: LONGINT): REAL; VAR x, y: REAL; i: LONGINT; pointsInCircle: LONGINT; BEGIN pointsInCircle := 0; //Randomize; FOR i := 1 TO n DO BEGIN x := Random; y := Random; IF (x*x + y*y) <= 1.0 THEN pointsInCircle := pointsInCircle + 1; END; ApproximatePI1 := (pointsInCircle / n) * 4; END;} FUNCTION ApproximatePI2(n: LONGINT): REAL; VAR x, y: REAL; i: LONGINT; pointsInCircle: LONGINT; BEGIN pointsInCircle := 0; //Randomize; FOR i := 1 TO n DO BEGIN x := RealRand; y := RealRand; IF (x*x + y*y) <= 1.0 THEN pointsInCircle := pointsInCircle + 1; END; ApproximatePI2 := (pointsInCircle / n) * 4; END; VAR n: LONGINT; BEGIN {n := 20; WriteLn(ApproximatePI1(n):1:5); n := 200; WriteLn(ApproximatePI1(n):1:5); n := 2000; WriteLn(ApproximatePI1(n):1:5); n := 20000; WriteLn(ApproximatePI1(n):1:5); n := 2000000; WriteLn(ApproximatePI1(n):1:5); n := 2000000; WriteLn(ApproximatePI1(n):1:5);} WriteLn('========================'); n := 20; WriteLn(ApproximatePI2(n):1:5); n := 200; WriteLn(ApproximatePI2(n):1:5); n := 2000; WriteLn(ApproximatePI2(n):1:5); n := 20000; WriteLn(ApproximatePI2(n):1:5); n := 2000000; WriteLn(ApproximatePI2(n):1:5); n := 2000000; WriteLn(ApproximatePI2(n):1:5); END.
unit uDateTimeScriptEngine; interface uses uBaseScriptEngine , CodeTemplateAPI , ToolsAPI ; type TDateTimeScriptEngine = class(TBaseScriptEngine) private const cDateFormatStr = 'dateformatstr'; cTimeFormatStr = 'timeformatstr'; procedure RemoveFormatStrings; procedure DeleteIfExists(i: Integer); private FDateFormatString: string; FTimeFormatString: string; procedure GetFormatStrings; function GetTimeString: string; function GetDateString: string; protected function GetIDString: WideString; override; function GetLanguage: WideString; override; procedure ProcessScriptEntry(const aPoint: IOTACodeTemplatePoint; const aName: string; const aValue: string); override; public procedure Execute(const ATemplate: IOTACodeTemplate; const APoint: IOTACodeTemplatePoint; const ASyncPoints: IOTASyncEditPoints; const AScript: IOTACodeTemplateScript; var Cancel: Boolean); override; end; procedure Register; implementation uses DateUtils , SysUtils , NixUtils ; procedure Register; begin (BorlandIDEServices as IOTACodeTemplateServices).RegisterScriptEngine(TDateTimeScriptEngine.Create); end; { TDateTimeScriptEngine } procedure TDateTimeScriptEngine.Execute(const ATemplate: IOTACodeTemplate; const APoint: IOTACodeTemplatePoint; const ASyncPoints: IOTASyncEditPoints; const AScript: IOTACodeTemplateScript; var Cancel: Boolean); var TempPoint: IOTACodeTemplatePoint; i: integer; TempPointName: string; TempFunctionName: string; TempDate: string; TempTime: string; const cDate = 'InsertDate'; cTime = 'InsertTime'; cDateTime = 'InsertDateTime'; begin inherited; GetFormatStrings; for i := 0 to ScriptInfo.Count - 1 do begin { In the script, the items are set up as follows: TempPointName=TempFunctionName where * TempPointName is the name of the point in the live template that is to be replaced by the script * TempFunctionName is the name given to the action to be taken. In this procedure, we'll be handling those TempFunctionName values. } TempPointName := ScriptInfo.Names[i]; TempFunctionName := ScriptInfo.Values[TempPointName]; if (ATemplate <> nil) then begin TempPoint := aTemplate.FindPoint(TempPointName); if TempPoint <> nil then begin TempPoint.Editable := False; if TempFunctionName = cDate then begin TempPoint.Value := GetDateString; end else begin if TempFunctionName = cTime then begin TempPoint.Value := GetTimeString; end else begin if TempFunctionName = cDateTime then begin TempDate := GetDateString; TempTime := GetTimeString; TempPoint.Value := Format('%s %s', [TempDate, TempTime]);; end; end; end; end; end; end; Cancel := False; end; procedure TDateTimeScriptEngine.DeleteIfExists(i: Integer); begin if i > 0 then begin ScriptInfo.Delete(i); end; end; function StringIsNotEmpty(Str: string): Boolean; begin Result := not StringIsEmpty(Str); end; function TDateTimeScriptEngine.GetDateString: string; begin // First look for format string..... if StringIsNotEmpty(FDateFormatString) then begin Result := FormatDateTime(FDateFormatString, Now); end else begin Result := DateToStr(Now); end; end; procedure TDateTimeScriptEngine.GetFormatStrings; begin end; //procedure TDateTimeScriptEngine.GetFormatStrings; //begin // // Pull the formatting strings out of the script string // FDateFormatString := ScriptInfo.Values[cDateFormatStr]; // FTimeFormatString := ScriptInfo.Values[cTimeFormatStr]; // // Once you have them, get rid of entries in string list //// RemoveFormatStrings; //end; function TDateTimeScriptEngine.GetIDString: WideString; begin // This function is required by the IOTACodeTemplateScriptEngine // interface, and needs a unique identifier. A GUID is unique as // they come, no? Result := '{5A866B09-828F-425C-99B6-4FDA2C446D3A}'; end; function TDateTimeScriptEngine.GetLanguage: WideString; begin // Should return a name for the scripting engine. This will be used // in the Live Template to identify the script engine to use. Result := 'DateTimeScript'; end; function TDateTimeScriptEngine.GetTimeString: string; begin // First check for formatting string..... if StringIsNotEmpty(FTimeFormatString) then begin Result := FormatDateTime(FTimeFormatString, Now); end else begin Result := TimeToStr(Now); end; end; procedure TDateTimeScriptEngine.ProcessScriptEntry(const aPoint: IOTACodeTemplatePoint; const aName:string; const aValue: string); begin end; procedure TDateTimeScriptEngine.RemoveFormatStrings; begin end; end.
{$IfNDef l3NotifierBase_imp} // Модуль: "w:\common\components\rtl\Garant\L3\l3NotifierBase.imp.pas" // Стереотип: "Impurity" // Элемент модели: "l3NotifierBase" MUID: (47F07AE10156) // Имя типа: "_l3NotifierBase_" {$Define l3NotifierBase_imp} _l3NotifierBase_ = class(_l3NotifierBase_Parent_, Il3ChangeNotifier) private f_NotifiedObjList: Tl3NotifyPtrList; protected function pm_GetHasNotified: Boolean; procedure Subscribe(const aRecipient: Il3Notify); {* подписка на извещения. } procedure Unsubscribe(const aRecipient: Il3Notify); {* "отписка" от извещений. } procedure Cleanup; override; {* Функция очистки полей объекта. } protected property HasNotified: Boolean read pm_GetHasNotified; {* наличие уведомляемых объектов. } property NotifiedObjList: Tl3NotifyPtrList read f_NotifiedObjList; end;//_l3NotifierBase_ {$Else l3NotifierBase_imp} {$IfNDef l3NotifierBase_imp_impl} {$Define l3NotifierBase_imp_impl} function _l3NotifierBase_.pm_GetHasNotified: Boolean; //#UC START# *47F07CCE0379_47F07AE10156get_var* //#UC END# *47F07CCE0379_47F07AE10156get_var* begin //#UC START# *47F07CCE0379_47F07AE10156get_impl* Result := (f_NotifiedObjList <> nil) and (f_NotifiedObjList.Count > 0); //#UC END# *47F07CCE0379_47F07AE10156get_impl* end;//_l3NotifierBase_.pm_GetHasNotified procedure _l3NotifierBase_.Subscribe(const aRecipient: Il3Notify); {* подписка на извещения. } //#UC START# *46A44F6B035E_47F07AE10156_var* //#UC END# *46A44F6B035E_47F07AE10156_var* begin //#UC START# *46A44F6B035E_47F07AE10156_impl* if (aRecipient = nil) then Exit; if (f_NotifiedObjList = nil) then f_NotifiedObjList := Tl3NotifyPtrList.MakeSorted; f_NotifiedObjList.Add(aRecipient); //#UC END# *46A44F6B035E_47F07AE10156_impl* end;//_l3NotifierBase_.Subscribe procedure _l3NotifierBase_.Unsubscribe(const aRecipient: Il3Notify); {* "отписка" от извещений. } //#UC START# *46A44FFE0143_47F07AE10156_var* //#UC END# *46A44FFE0143_47F07AE10156_var* begin //#UC START# *46A44FFE0143_47F07AE10156_impl* if (aRecipient <> nil) AND (f_NotifiedObjList <> nil) then f_NotifiedObjList.Remove(aRecipient); //#UC END# *46A44FFE0143_47F07AE10156_impl* end;//_l3NotifierBase_.Unsubscribe procedure _l3NotifierBase_.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_47F07AE10156_var* //#UC END# *479731C50290_47F07AE10156_var* begin //#UC START# *479731C50290_47F07AE10156_impl* FreeAndNil(f_NotifiedObjList); inherited; //#UC END# *479731C50290_47F07AE10156_impl* end;//_l3NotifierBase_.Cleanup {$EndIf l3NotifierBase_imp_impl} {$EndIf l3NotifierBase_imp}
unit Unt_FuncaoLog; interface type /// <summary> /// Classe responsável pela geração de LOG /// </summary> TGeraLog = class private /// <summary> /// Indica o arquivo em que o LOG será gerado, no caso, no mesmo diretório do executável /// </summary> const C_ARQUIVO = '.\arquivo_log.txt'; /// <summary> /// Instância única do objeto /// </summary> class var FInstance: TGeraLog; /// <summary> /// Método responsável por instanciar o objeto singleton /// </summary> class function GetInstancia: TGeraLog; static; public /// <summary> /// Deleta o arquivo de LOG caso o mesma exista /// </summary> procedure AfterConstruction; override; /// <summary> /// Método que efetivamente gera o LOG /// </summary> /// <param name="AReferencia">Referência à thread chamadora</param> /// <param name="AData">Date e hora da geração do LOG</param> /// <param name="ATextoLog">Texto a ser escrito no arquivo de log</param> procedure GerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string); /// <summary> /// Referência à instância singleton /// </summary> class property Instancia: TGeraLog read GetInstancia; end; implementation uses System.SysUtils; { TGeraLog } procedure TGeraLog.AfterConstruction; begin inherited; DeleteFile(Self.C_ARQUIVO); end; procedure TGeraLog.GerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string); var _arquivo : TextFile; sNovaLinha: string; begin sNovaLinha := Format('%s|%s|%s', [AReferencia, DateTimeToStr(AData), ATextoLog]); AssignFile(_arquivo, Self.C_ARQUIVO); if (FileExists(Self.C_ARQUIVO)) then begin Append(_arquivo); end else begin Rewrite(_arquivo); end; Writeln(_arquivo, sNovaLinha); CloseFile(_arquivo); end; class function TGeraLog.GetInstancia: TGeraLog; begin if not(Assigned(FInstance)) then begin FInstance := TGeraLog.Create; end; Result := FInstance; end; initialization finalization TGeraLog.Instancia.Free; end.
unit UACadastroCliente; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Data.DB, Datasnap.DBClient, IdBaseComponent, IdComponent; type TUCadastroCliente = class(TForm) pBackground: TPanel; eNome: TLabeledEdit; eTelefone: TMaskEdit; lTelefone: TLabel; eCPF: TMaskEdit; lCPF: TLabel; eIdentidade: TLabeledEdit; eEmail: TLabeledEdit; bExit: TButton; lEndereco: TLabel; Splitter1: TSplitter; eLogradouro: TLabeledEdit; eNumero: TLabeledEdit; ePais: TLabeledEdit; eEstado: TLabeledEdit; eCidade: TLabeledEdit; eBairro: TLabeledEdit; eComplemento: TLabeledEdit; eCEP: TMaskEdit; bValidCEP: TButton; bSave: TButton; lCEP: TLabel; dsDados: TDataSource; cdsDados: TClientDataSet; cdsDadosNOME: TStringField; cdsDadosIDENTIDADE: TStringField; cdsDadosCPF: TStringField; cdsDadosTELEFONE: TStringField; cdsDadosEMAIL: TStringField; cdsDadosCEP: TStringField; cdsDadosLOGRADOURO: TStringField; cdsDadosNUMERO: TStringField; cdsDadosBAIRRO: TStringField; cdsDadosCOMPLEMENTO: TStringField; cdsDadosCIDADE: TStringField; cdsDadosESTADO: TStringField; cdsDadosPAIS: TStringField; eEmailEnv: TLabeledEdit; procedure bExitClick(Sender: TObject); procedure bValidCEPClick(Sender: TObject); procedure bSaveClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var UCadastroCliente: TUCadastroCliente; implementation {$R *.dfm} uses UASMTPMail, UAAPIviacep; procedure TUCadastroCliente.bExitClick(Sender: TObject); begin Close; end; procedure TUCadastroCliente.bSaveClick(Sender: TObject); var xSendMail: newMail; begin if (eNome.Text = '') then begin showMessage('O campo "'+ eNome.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eNome.SetFocus; Abort; end; if (eIdentidade.Text = '') then begin showMessage('O campo "'+ eIdentidade.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eIdentidade.SetFocus; Abort; end; if (eCPF.Text = '') then begin showMessage('O campo "'+ lCPF.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCPF.SetFocus; Abort; end; if (eTelefone.Text = '') then begin showMessage('O campo "'+ lTelefone.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eTelefone.SetFocus; Abort; end; if (eEmail.Text = '') then begin showMessage('O campo "'+ eEmail.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eEmail.SetFocus; Abort; end; if (eCEP.Text = '') then begin showMessage('O campo "'+ lCEP.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (eLogradouro.Text = '') then begin showMessage('O campo "'+ eLogradouro.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (eNumero.Text = '') then begin showMessage('O campo "'+ eNumero.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (eBairro.Text = '') then begin showMessage('O campo "'+ eBairro.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (eCidade.Text = '') then begin showMessage('O campo "'+ eCidade.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (eEstado.Text = '') then begin showMessage('O campo "'+ eEstado.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eCEP.SetFocus; Abort; end; if (ePais.Text = '') then begin showMessage('O campo "'+ ePais.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); ePais.SetFocus; Abort; end; if (eEmailEnv.Text = '') then begin ShowMessage('O campo "'+ eEmailEnv.EditLabel.Caption +'" é obrigatório.'#13'Favor informar um valor.'); eEmailEnv.SetFocus; Abort; end; try if (not cdsDados.Active) then begin cdsDados.CreateDataSet; cdsDados.EmptyDataSet; cdsDados.Active := True; end; cdsDados.Insert; cdsDadosNOME.Value := eNome.Text; cdsDadosIDENTIDADE.Value := eIdentidade.Text; cdsDadosCPF.Value := eCPF.Text; cdsDadosTELEFONE.Value := eTelefone.Text; cdsDadosEMAIL.Value := eEmail.Text; cdsDadosCEP.Value := eCEP.Text; cdsDadosLOGRADOURO.Value := eLogradouro.Text; cdsDadosNUMERO.Value := eNumero.Text; cdsDadosBAIRRO.Value := eBairro.Text; cdsDadosCOMPLEMENTO.Value := eComplemento.Text; cdsDadosCIDADE.Value := eCidade.Text; cdsDadosESTADO.Value := eEstado.Text; cdsDadosPAIS.Value := ePais.Text; cdsDados.Post; //showMessage('XML Criado com suscesso!'); except showMessage('Houve um erro ao criar o XML!'); Abort; end; xSendMail := newMail.Create; xSendMail.messageRecipient := eEmailEnv.Text; xSendMail.messageCC := ''; xSendMail.messageSubject := 'Cadastro de Cliente'; xSendMail.messageFromAdress := 'marcos.p.cruz@hotmail.com'; xSendMail.messageBodyAdd := 'Cadastro do cliente: '+ eNome.Text +' anexado.'; xSendMail.messageAttachment := cdsDados.FileName; if(xSendMail.sendEmail()) then xSendMail.Free; Close; end; procedure TUCadastroCliente.bValidCEPClick(Sender: TObject); var UmAPIviacep : TAPIviacep; begin try UmAPIviacep := TAPIviacep.Create(eCEP.Text); if (UmAPIviacep.GetRespCode = 200 ) then begin eLogradouro.Text := UmAPIviacep.GetLogradouro; eBairro.Text := UmAPIviacep.GetBairro; eComplemento.Text := UmAPIviacep.GetComplemento; eCidade.Text := UmAPIviacep.GetLocalidade; eEstado.Text := UmAPIviacep.GetUF; end else if (UmAPIviacep.GetRespCode = 400) then showMessage('CEP inválido ou năo encontrado'); finally FreeAndNil(UmAPIviacep); end; end; end.
unit np.ut; interface uses SysUtils; // {$IFDEF } // type // PUTF8Char = _PAnsiChr; // UTF8Char = AnsiChar; // {$endif} {$IFNDEF NEXTGEN} type UTF8Char = AnsiChar; PUTF8Char = PAnsiChar; {$ENDIF} const CP_USASCII = 20127; CP_UTF8 = 65001; type TUnixTime = type int64; function FmtTimestamp(Date: TDateTime): String; function FmtTimestampISO(Date: TDateTime): String; function StringPrefixIs(const prefix, str : string) : Boolean; function StringPostfixIs(const postfix, str : string) : Boolean; function StrToHex(const s: RawByteString): UTF8String; function prettyJSON(const inJson :string) : string; function JSONText(const json : string; OnlySpacial: Boolean = false) : string; function JSONBoolean(bool : Boolean): string; {$IFDEF MSWINDOWS} function CurrentFileTime : int64; {$ENDIF} function CurrentTimestamp : int64; function FileTimeToTimestamp(ft : int64) : int64; function TimeStampToDateTime( ts : int64 ) : TDateTime; inline; function ClipValue(V,Min,Max: Integer) : Integer; overload; function ClipValue(V,Min,Max: int64) : Int64; overload; function trimR(const s: String; trimChars : array of char) : String; function charInSet16(ch : char; const chars : array of char) : Boolean; function PosEx(const SubStr, Str: string; Skip: INTEGER): Integer; overload; procedure OutputDebugStr( const S : String ); overload; procedure OutputdebugStr( const S : String; P : Array of const);overload; procedure RMove(const Source; var Dest; Count: Integer); function WildFind(wild, s: PUTF8Char; count:Integer): TArray<UTF8String>; overload; function WildFind(const wild, s: UTF8String; count:Integer): TArray<UTF8String>; overload; inline; function WildFindW(wild, s: PChar; count:Integer): TArray<String>; overload; function WildFindW(const wild, s: String; count:Integer): TArray<String>; overload; inline; function SplitString(const AContent: string; out AResult : TArray<String>; Separators : TSysCharSet) : integer; overload; function SplitString(const AContent: UTF8String; out AResult : TArray<UTF8String>; Separator : TSysCharSet) : integer; overload; function SplitString(const str: UTF8String; Separator : TSysCharSet) : TArray<UTF8String>; overload; procedure SetLengthZ(var S : RawByteString; len : integer); overload; procedure SetLengthZ(var S : String; len : integer); overload; function strrstr(const _find,_string:string) : integer; overload; function strrstr(const _find,_string:RawByteString) : integer; overload; function WildComp(const wild, s: String): boolean; function compareTicks(old, new : int64): integer; function StrRemoveQuote(const s :string) : string; function DecodeJSONText(const JSON : string; var Index: Integer) : string; function UnicodeSameText(const A1,A2 : String) : Boolean; type TTokenMap = TFunc<string,string>; function macros(const templ: string; const macroOpen,macroClose: string; const mapFunc : TTokenMap; macroInsideMacro:Boolean=false ) : string; function trimar(const ar: TArray<string>) : TArray<string>; implementation uses {$IFDEF MSWINDOWS} WinApi.Windows, {$ENDIF} {$IFDEF POSIX} Posix.SysTime, {$ENDIF} Classes, DateUtils, Character; var g_TraceEnabled : Boolean = {$IFDEF DEBUG} true {$ELSE} false {$ENDIF} ; function TimeStampToDateTime( ts : int64 ) : TDateTime; begin result := IncMilliSecond(UnixDateDelta, ts ); end; function ClipValue(V,Min,Max: Integer) : Integer; begin result := V; if result > Max then result := Max; if result < Min then result := Min; end; function ClipValue(V,Min,Max: Int64) : Int64; begin result := V; if result > Max then result := Max; if result < Min then result := Min; end; function FmtTimestamp(Date: TDateTime): String; begin try Result := FormatDateTime('dd.mm.yy hh:nn:ss.zzz', Date); except On E:Exception do Result := '(invalid)'; end; end; function FmtTimestampISO(Date: TDateTime): String; begin try Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Date); except On E:Exception do Result := '(invalid)'; end; end; function StringPrefixIs(const prefix, str : string) : Boolean; var s1,s2 : PChar; begin s1 := PChar(prefix); s2 := PChar(str); if s1 = nil then exit(s2=nil); while s1^=s2^ do begin inc(s1); inc(s2); if s1^ = #0 then exit(true); end; exit(false); end; function StringPostfixIs(const postfix, str : string) : Boolean; var I1,I2 : integer; begin I1 := length(str); I2 := length(postfix); while (I2 > 0) and (I1 > 0) and (str[I1] = postfix[I2]) do begin dec(I1); dec(I2); end; result := I2 = 0; end; function StrToHex(const s: RawByteString): UTF8String; var ch : UTF8Char; begin result := ''; for ch in s do result := result + LowerCase( format('%.2x',[(byte(ch))]) ); end; function prettyJSON(const inJson :string) : string; var s : string; i,l : integer; ch : Char; Quote : Boolean; level : integer; begin Quote := False; level := 0; //pass1 : remove spaces for ch in inJSon do begin if ch = '"' then begin Quote := not Quote; s := s + ch; continue; end; if Quote then s := s + ch else if ord(ch) >= 32 then s := s + ch; end; //pass2 : formating Quote := False; l := Length(s); i := 1; while l > 0 do begin ch := s[i]; inc(i); dec(l); if ch = '"' then begin Quote := not Quote; result := result + ch; continue; end; if not Quote then begin if ch = ':' then result := result + ': ' else if ch in ['[','{'] then begin inc(level); result := result + ch + #13#10+StringOfChar(' ',level*2) end else if ch in [']','}'] then begin dec(level); result := result + #13#10 +StringOfChar(' ',level*2); if s[i] = ',' then begin result := result + ch+','#13#10 +StringOfChar(' ',level*2); inc(i); dec(l); end else result := result + ch; end else if ch = ',' then result := result + ch+#13#10+StringOfChar(' ',level*2) else result := result + ch; end else result := result + ch; end; end; function JSONText(const json : string; OnlySpacial: Boolean) : string; var sb : TStringBuilder; ch : char; begin sb := TStringBuilder.Create; try for ch in json do begin case ch of //#0..#7:; #8: sb.Append('\b'); #9: sb.Append('\t'); #10: sb.Append('\n'); //#11:; #12: sb.Append('\f'); #13: sb.Append('\r'); //#14..#$1f:; '"': sb.Append('\"'); '\': sb.Append('\\'); '/': sb.Append('\/'); #$80..#$ffff: if OnlySpacial then sb.Append(ch) else sb.AppendFormat('\u%.4x',[word(ch)]); else begin case ch of #$20..#$7f: sb.Append(ch); end; end; end; end; result := sb.ToString; finally sb.Free; end; end; function FileTimeToTimestamp(ft : int64) : int64; begin result := (ft-116444736000000000 ) div 10000; end; {$IFDEF MSWINDOWS} function CurrentFileTime : int64; begin GetSystemTimeAsFileTime(TFileTime(result)); end; function CurrentTimestamp : int64; begin result := FileTimeToTimestamp( CurrentFileTime ); end; {$ENDIF} {$IFDEF POSIX} function CurrentTimestamp : int64; var tv: timeval; begin assert( gettimeofday(tv,nil) = 0); result := int64(tv.tv_sec)*1000+(tv.tv_usec div 1000); end; {$ENDIF} //function ReadTextFile(const path: string; encoding : string) : string; //var // fd : THandle; // enc : TEncoding; // stats : TStats; // buf : BufferRef; //begin // stats := fs.statsync(path); // buf := Buffer.Create(stats.Size); // fd := fs.openSync(path,'>r'); // buf.length := fs.readSync(fd,buf,0); // result := buf.AsString(encoding); //end; function charInSet16(ch : char; const chars : array of char) : Boolean; var _ch : char; begin result := false; for _ch in chars do if _ch = ch then exit(true); end; function JSONBoolean(bool : Boolean): string; begin if bool then Result := 'true' else Result := 'false'; end; function trimR(const s : string; trimChars : array of char) : string; var L : integer; begin L := Length(s); while (L>0) and CharInSet16(s[L], trimChars) do dec(L); result := copy(s,1,L); end; const http_day_of_week : array [0..6] of string = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ); http_month : array [1..12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); var g_tickCount : Cardinal = 0; g_lock_current_httpTime : integer = 0; function PosEx(const SubStr, Str: string; Skip: INTEGER): Integer; var SubLen, SrcLen, Len, I, J: Integer; C1: Char; begin Result := 0; if Skip < 1 then skip := 1; if (Pointer(SubStr) = nil) or (Pointer(Str) = nil) then Exit; SrcLen := Length(Str); SubLen := Length(SubStr); if (SubLen <= 0) or (SrcLen <= 0) or (SrcLen < SubLen) then Exit; // find SubStr[1] in Str[1 .. SrcLen - SubLen + 1] Len := SrcLen - SubLen + 1; C1 := PChar(SubStr)[0]; for I := Skip-1 to Len - 1 do begin if PChar(Str)[I] = C1 then begin Result := I + 1; for J := 1 to SubLen-1 do begin if PChar(Str)[I+J] <> PChar(SubStr)[J] then begin Result := 0; break; end; end; if Result <> 0 then break; end; end; end; procedure OutputDebugStr( const S : String ); begin {$IFDEF MSWINDOWS} {$IFDEF DEBUG} if g_TraceEnabled then OutputDebugString( PChar( s ) ); {$ENDIF} {$ENDIF} end; procedure OutputdebugStr( const S : String; P : Array of const); begin {$IFDEF DEBUG} OutputDebugStr( Format(s, p) ); {$ENDIF} end; procedure RMove(const Source; var Dest; Count: Integer); var S, D: PByte; begin if Count <= 0 then exit; S := PByte(@Source); D := PByte(@Dest)+Count-1; repeat D^ := S^; inc(s); dec(d); dec(count); until count = 0; end; function WildFind(wild, s: PUTF8Char; count:Integer): TArray<UTF8String>; var mp_i, cp_i : PUTF8Char; j : integer; match : PUTF8Char; begin setLength(result,0); setLength(result,count); if count < 0 then exit; mp_i := nil; cp_i := nil; match := nil; while (s^ <> #0) and (wild^ <> #0) and (wild^ <> '*') do begin if (wild^ <> s^) and (wild^<>'?') then Exit; inc(s); inc(wild); end; j := 0; while s^ <> #0 do begin if (wild^ <> #0) and (wild^ = '*') then begin if match = nil then match := s; inc(wild); if wild^ = #0 then break; mp_i := wild; cp_i := s+1; end else if (wild^ <> #0) and ((wild^ = s^) or (wild^='?')) then begin if (match <> nil) then begin SetString(result[j],match,s-match); match := nil; inc(j); if j = count then exit; end; inc(wild); inc(s); end else begin assert(mp_i <> nil); assert(cp_i <> nil); wild := mp_i; s := cp_i; inc(cp_i); end; end; if match <> nil then begin while s^ <> #0 do inc(s); SetString(result[j],match,s-match); end end; function WildFindW(wild, s: PChar; count:Integer): TArray<String>; var mp_i, cp_i : PChar; j : integer; match : PChar; begin setLength(result,0); setLength(result,count); if count < 0 then exit; mp_i := nil; cp_i := nil; match := nil; while (s^ <> #0) and (wild^ <> #0) and (wild^ <> '*') do begin if (wild^ <> s^) and (wild^<>'?') then Exit; inc(s); inc(wild); end; j := 0; while s^ <> #0 do begin if (wild^ <> #0) and (wild^ = '*') then begin if match = nil then match := s; inc(wild); if wild^ = #0 then break; mp_i := wild; cp_i := s+1; end else if (wild^ <> #0) and ((wild^ = s^) or (wild^='?')) then begin if (match <> nil) then begin SetString(result[j],match,s-match); match := nil; inc(j); if j = count then exit; end; inc(wild); inc(s); end else begin assert(mp_i <> nil); assert(cp_i <> nil); wild := mp_i; s := cp_i; inc(cp_i); end; end; if match <> nil then begin while s^ <> #0 do inc(s); SetString(result[j],match,s-match); end end; function WildFindW(const wild, s: String; count:Integer): TArray<String>; begin result := WildFindW(PChar(wild),PChar(s), count); end; function WildFind(const wild, s: UTF8String; count:Integer): TArray<UTF8String>; begin result := WildFind(PUTF8Char(wild),PUTF8Char(s), count ); end; function SplitString(const str: UTF8String; Separator : TSysCharSet) : TArray<UTF8String>; begin if SplitString(str,result, Separator) = 0 then begin SetLength(result,1); result[0] := ''; end; end; function SplitString(const AContent: UTF8String; out AResult : TArray<UTF8String>; Separator : TSysCharSet) : integer; var Head, Tail, Content: PUTF8Char; EOS: Boolean; Item: string; InQ : Boolean; label LoopInit; begin Result := 0; Content := PUTF8Char(AContent); Tail := Content; inQ := false; if Tail^<>#0 then repeat while (Tail^ = ' ') do Inc(Tail); Head := Tail; // if tail^='"' then // inQ := not inQ; goto LoopInit; while not ((Tail^=#0) or (not InQ and (Tail^ in Separator))) do begin Inc(Tail); LoopInit: if tail^='"' then inQ := not inQ; end; EOS := Tail^ = #0; // if ((Head^ <> #0) and ((Head <> Tail) or (Tail^=Separator) or )) then // begin SetString(Item, Head, Tail - Head); if Result = Length(AResult) then setlength(AResult, result + 16); AResult[Result] := Item; Inc(Result); // end; Inc(Tail); until EOS; setLength(AResult,Result); end; function SplitString(const AContent: string; out AResult : TArray<String>; Separators : TSysCharSet) : integer; var Head, Tail, Content: PChar; EOS, InQuote: Boolean; QuoteChar: Char; Item: string; LWhiteSpaces: TSysCharSet; LSeparators: TSysCharSet; // WhiteSpace: TSysCharSet; begin Result := 0; Content := PChar(AContent); Tail := Content; InQuote := false; QuoteChar := #0; LWhiteSpaces := [' ']; LSeparators := Separators + [#0, #13, #10, '''', '"']; repeat while (Tail^ in LWhiteSpaces) do Inc(Tail); Head := Tail; while True do begin while (InQuote and not ((Tail^ = #0) or (Tail^ = QuoteChar))) or not (Tail^ in LSeparators) do Inc(Tail); if (Tail^ in ['"']) then begin if (QuoteChar <> #0) and (QuoteChar = Tail^) then QuoteChar := #0 else if QuoteChar = #0 then QuoteChar := Tail^; InQuote := QuoteChar <> #0; Inc(Tail); end else Break; end; EOS := Tail^ = #0; if (Head <> Tail) and (Head^ <> #0) then begin SetString(Item, Head, Tail - Head); if Result = Length(AResult) then setlength(AResult, result + 16); AResult[Result] := Item; Inc(Result); end; Inc(Tail); until EOS; setLength(AResult,Result); end; procedure SetLengthZ(var S : RawByteString; len : integer); var prevLen : integer; begin prevLen := length(s); SetLength(s, len); if len > prevLen then fillchar(s[prevLen+1],len-prevLen,0); end; procedure SetLengthZ(var S : String; len : integer); var prevLen : integer; begin prevLen := length(s); SetLength(s, len); if len > prevLen then fillchar(s[prevLen+1],(len-prevLen)*2,0); end; (* ** find the last occurrance of find in string *) function strrstr(const _find,_string:string) : integer; var stringlen, findlen,i : integer; find,str,cp : PChar; begin findlen := Length(_find); find := PChar(_find); str := PChar(_string); stringlen := length(_string); if (findlen > stringlen) then exit(0); cp := str + stringlen - findlen; while (cp >= str) do begin i := findLen-1; while (i >= 0) and (cp[i] = find[i]) do dec(i); if i < 0 then exit(cp-str+1); dec(cp); end; exit(0); end; function strrstr(const _find,_string:RawByteString): Integer; var stringlen, findlen,i : integer; find,str,cp : PUTF8Char; begin findlen := Length(_find); find := PUTF8Char(_find); str := PUTF8Char(_string); stringlen := length(_string); if (findlen > stringlen) then exit(0); cp := str + stringlen - findlen; while (cp >= str) do begin i := findLen-1; while (i >= 0) and (cp[i] = find[i]) do dec(i); if i < 0 then exit(cp-str+1); dec(cp); end; exit(0); end; //function WildComp(const WildS,IstS: String): boolean; //var // i, j, l, p : integer; //begin // i := 1; // j := 1; // while (i<=length(WildS)) do // begin // if WildS[i]='*' then // begin // if i = length(WildS) then // begin // result := true; // exit // end // else // begin // { we need to synchronize } // l := i+1; // while (l < length(WildS)) and (WildS[l+1] <> '*') and (WildS[l+1] <> '?') do // inc (l); // p := pos (copy (WildS, i+1, l-i), IstS); // if p > 0 then // begin // j := p-1; // end // else // begin // result := false; // exit; // end; // end; // end // else // if (WildS[i]<>'?') and ((length(IstS) < i) // or (WildS[i]<>IstS[j])) then // begin // result := false; // exit // end; // // inc (i); // inc (j); // end; // result := (j > length(IstS)); //end; function WildComp(const wild, s: String): boolean; var i_w,i_s : integer; l_w,l_s : integer; mp_i : integer; cp_i : integer; begin i_w := 1; i_s := 1; l_w := Length(wild); l_s := Length(s); mp_i := MAXINT; cp_i := MAXINT; while (i_s <= l_s) and (i_w <= l_w) and (wild[i_w] <> '*') do begin if (wild[i_w] <> s[i_s]) and (wild[i_w] <> '?') then exit(false); inc(i_w); inc(i_s); end; while i_s <= L_s do begin if (i_w <= L_w) and (wild[i_w] = '*') then begin inc(i_w); if i_w > L_w then exit(true); mp_i := i_w; cp_i := i_s+1; end else if (i_w <= L_w) and (wild[i_w] = s[i_s]) or (wild[i_w]='?') then begin inc(i_w); inc(i_s); end else begin i_w := mp_i; i_s := cp_i; inc(cp_i); end; end; while (i_w <= L_w) and (wild[i_w] = '*') do inc(i_w); exit(i_w > L_w); end; function compareTicks(old, new : int64): integer; begin if old > new then inc(new,$100000000); result := new-old; end; //procedure SaveToIni(const P : IS20Properties; const Header: String; const ini : String); //var // F : text; // S : String; // V : Variant; // HSync : IS20Locker; //begin // HSync := CreateNamedMutexRS(ini,'file'); // HSync.Lock; // AssignFile(F, ini); // Rewrite(F); // try // WriteLn(F,'[',Header,']'); // for S in P.SortedKeys do // begin // if not P.IsNull(S,V) then // begin // WriteLn(F, S,'=',V); // end; // end; // finally // CloseFile(F); // end; //end; // //function LoadFromIniSection(const Section : String; const ini : String) : IS20Properties; //var // F : text; // S : String; // L : INTEGER; // V : Variant; // lSection : String; // tmp : String; // SectionMode : Boolean; // HSync : IS20Locker; //begin // result := TS20Properties.Create; // HSync := CreateNamedMutexRS(ini,'file'); // HSync.Lock; // AssignFile(F, ini); // Reset(F); // try // lSection := '['+Section+']'; // SectionMode := false; // while not Eof(F) and not SectionMode do // begin // ReadLn(F,S); // SectionMode := trim(S) = lSection; // end; // while not Eof(F) and SectionMode do // begin // ReadLn(F,S); // S:= trim(s); // if Copy(S,1,1)<>';' then // begin // if Copy(S,1,1)+Copy(S,Length(S),1) = '[]' then // SectionMode := S = Section; // if SectionMode then // begin // tmp := tmp + S + #13 + #10; // end; // end; // end; // result := KVParser(tmp); // finally // CloseFile(F); // end; //end; function StrRemoveQuote(const s :string) : string; var l : integer; begin l := length(s); if (l>1) and (s[1]='"') and (s[l]='"') then result := copy(s,2,l-2) else result := s; end; function DecodeJSONText(const JSON : string; var Index: Integer) : string; var L : Integer; SkipMode : Boolean; begin result := ''; if Index < 1 then Index := 1; SkipMode := true; L := Length(JSON); While (Index<=L) DO BEGIN case JSON[Index] of '"': begin Inc(Index); //Skip rigth " if not SkipMode then break; skipMode := false; end; #0..#$1f: INC(Index);//ignore '\': begin if Index+1 <= L then begin case JSON[Index+1] of '"','\','/' : begin if not skipMode then Result := Result + JSON[Index+1]; INC(Index,2); end; 'u': begin if not skipMode then Result := Result + char(word( StrToIntDef('$'+copy(JSON,Index+2,4),ord('?')) )); INC(Index,6); end; 'b': begin if not skipMode then Result := Result + #8; INC(Index,2); end; 'f': begin if not skipMode then Result := Result + #12; INC(Index,2); end; 'n': begin if not skipMode then Result := Result + #10; INC(Index,2); end; 'r': begin if not skipMode then Result := Result + #13; INC(Index,2); end; 't': begin if not skipMode then Result := Result + #9; INC(Index,2); end; else INC(Index,2); //Ignore end; end; end; else begin if not skipMode then Result := Result + JSON[Index]; INC(Index); end; end; END; end; function UnicodeSameText(const A1,A2 : String) : Boolean; begin result := Char.ToLower(A1) = Char.ToLower(A2); end; function macros(const templ: string; const macroOpen,macroClose: string; const mapFunc : TTokenMap; macroInsideMacro:Boolean ) : string; var F,T,SKIP: INTEGER; token : string; S : string; begin if (macroOpen = '') or (macroClose='') then Exit( macros(templ,'${','}',mapFunc)); S := templ; SKIP := 1; repeat F := PosEx(macroOpen,S,SKIP); if (F=0) then break; T := PosEx(macroClose,S,F+Length(macroOpen)); if T=0 then break; token := copy(s,F+Length(macroOpen),(T-F-Length(macroOpen))); if assigned(mapFunc) then token := mapFunc(token) else token := ''; Delete(s,F,(T-F+Length(macroClose))); Insert(token,s,F); SKIP := F;//+length(token); if not macroInsideMacro then INC(SKIP,Length(token)); until false; result := s; end; function trimar(const ar: TArray<string>) : TArray<string>; var i : integer; begin SetLength(result, length(ar)); for i := 0 to length(ar)-1 do result[i] := trim(ar[i]); end; end.
unit csUploadDocStream; // Модуль: "w:\common\components\rtl\Garant\cs\csUploadDocStream.pas" // Стереотип: "SimpleClass" // Элемент модели: "TcsUploadDocStream" MUID: (57D2706902F8) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , csPersonificatedMessage , k2SizedMemoryPool , l3MarshalledTypes , k2Base ; type TcsUploadDocStream = class(TcsPersonificatedMessage) protected function pm_GetData: Tk2RawData; procedure pm_SetData(aValue: Tk2RawData); function pm_GetIsObjTopic: Boolean; procedure pm_SetIsObjTopic(aValue: Boolean); function pm_GetDocFamily: Integer; procedure pm_SetDocFamily(aValue: Integer); function pm_GetDocID: Integer; procedure pm_SetDocID(aValue: Integer); function pm_GetDocPart: Tm3DocPartSelector; procedure pm_SetDocPart(aValue: Tm3DocPartSelector); function pm_GetParseToDB: Boolean; procedure pm_SetParseToDB(aValue: Boolean); function pm_GetIsClassChanged: Boolean; procedure pm_SetIsClassChanged(aValue: Boolean); function pm_GetNeedSaveText: Boolean; procedure pm_SetNeedSaveText(aValue: Boolean); function pm_GetDocClass: TDocType; procedure pm_SetDocClass(aValue: TDocType); public class function GetTaggedDataType: Tk2Type; override; public property Data: Tk2RawData read pm_GetData write pm_SetData; property IsObjTopic: Boolean read pm_GetIsObjTopic write pm_SetIsObjTopic; property DocFamily: Integer read pm_GetDocFamily write pm_SetDocFamily; property DocID: Integer read pm_GetDocID write pm_SetDocID; property DocPart: Tm3DocPartSelector read pm_GetDocPart write pm_SetDocPart; property ParseToDB: Boolean read pm_GetParseToDB write pm_SetParseToDB; property IsClassChanged: Boolean read pm_GetIsClassChanged write pm_SetIsClassChanged; property NeedSaveText: Boolean read pm_GetNeedSaveText write pm_SetNeedSaveText; property DocClass: TDocType read pm_GetDocClass write pm_SetDocClass; end;//TcsUploadDocStream {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , csUploadDocStream_Const //#UC START# *57D2706902F8impl_uses* //#UC END# *57D2706902F8impl_uses* ; function TcsUploadDocStream.pm_GetData: Tk2RawData; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := Tk2RawData(TaggedData.cAtom(k2_attrData)); end;//TcsUploadDocStream.pm_GetData procedure TcsUploadDocStream.pm_SetData(aValue: Tk2RawData); begin TaggedData.AttrW[k2_attrData, nil] := (aValue); end;//TcsUploadDocStream.pm_SetData function TcsUploadDocStream.pm_GetIsObjTopic: Boolean; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.BoolA[k2_attrIsObjTopic]); end;//TcsUploadDocStream.pm_GetIsObjTopic procedure TcsUploadDocStream.pm_SetIsObjTopic(aValue: Boolean); begin TaggedData.BoolW[k2_attrIsObjTopic, nil] := (aValue); end;//TcsUploadDocStream.pm_SetIsObjTopic function TcsUploadDocStream.pm_GetDocFamily: Integer; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.IntA[k2_attrDocFamily]); end;//TcsUploadDocStream.pm_GetDocFamily procedure TcsUploadDocStream.pm_SetDocFamily(aValue: Integer); begin TaggedData.IntW[k2_attrDocFamily, nil] := (aValue); end;//TcsUploadDocStream.pm_SetDocFamily function TcsUploadDocStream.pm_GetDocID: Integer; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.IntA[k2_attrDocID]); end;//TcsUploadDocStream.pm_GetDocID procedure TcsUploadDocStream.pm_SetDocID(aValue: Integer); begin TaggedData.IntW[k2_attrDocID, nil] := (aValue); end;//TcsUploadDocStream.pm_SetDocID function TcsUploadDocStream.pm_GetDocPart: Tm3DocPartSelector; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := Tm3DocPartSelector(TaggedData.IntA[k2_attrDocPart]); end;//TcsUploadDocStream.pm_GetDocPart procedure TcsUploadDocStream.pm_SetDocPart(aValue: Tm3DocPartSelector); begin TaggedData.IntW[k2_attrDocPart, nil] := Ord(aValue); end;//TcsUploadDocStream.pm_SetDocPart function TcsUploadDocStream.pm_GetParseToDB: Boolean; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.BoolA[k2_attrParseToDB]); end;//TcsUploadDocStream.pm_GetParseToDB procedure TcsUploadDocStream.pm_SetParseToDB(aValue: Boolean); begin TaggedData.BoolW[k2_attrParseToDB, nil] := (aValue); end;//TcsUploadDocStream.pm_SetParseToDB function TcsUploadDocStream.pm_GetIsClassChanged: Boolean; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.BoolA[k2_attrIsClassChanged]); end;//TcsUploadDocStream.pm_GetIsClassChanged procedure TcsUploadDocStream.pm_SetIsClassChanged(aValue: Boolean); begin TaggedData.BoolW[k2_attrIsClassChanged, nil] := (aValue); end;//TcsUploadDocStream.pm_SetIsClassChanged function TcsUploadDocStream.pm_GetNeedSaveText: Boolean; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.BoolA[k2_attrNeedSaveText]); end;//TcsUploadDocStream.pm_GetNeedSaveText procedure TcsUploadDocStream.pm_SetNeedSaveText(aValue: Boolean); begin TaggedData.BoolW[k2_attrNeedSaveText, nil] := (aValue); end;//TcsUploadDocStream.pm_SetNeedSaveText function TcsUploadDocStream.pm_GetDocClass: TDocType; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := TDocType(TaggedData.IntA[k2_attrDocClass]); end;//TcsUploadDocStream.pm_GetDocClass procedure TcsUploadDocStream.pm_SetDocClass(aValue: TDocType); begin TaggedData.IntW[k2_attrDocClass, nil] := Ord(aValue); end;//TcsUploadDocStream.pm_SetDocClass class function TcsUploadDocStream.GetTaggedDataType: Tk2Type; begin Result := k2_typcsUploadDocStream; end;//TcsUploadDocStream.GetTaggedDataType {$IfEnd} // NOT Defined(Nemesis) end.
unit Resources; interface uses gm_engine; type TFontEnum = (ttFont1, ttFont2); TResEnum = (ttBack, ttFire, ttIce, ttSellCell, ttNSellCell, ttItemSlot, ttDoll, ttGold, ttIL, ttBackbar, ttLifebar, ttManabar, ttClose); var Font: array [TFontEnum] of TFont; Resource: array [TResEnum] of TTexture; const FontPath: array [TFontEnum] of string = ( 'mods\default\fonts\font.zfi', 'mods\default\fonts\font2.zfi' ); ResourcePath: array [TResEnum] of string = ( 'mods\core\sprites\back.png', 'mods\core\sprites\fire.png', 'mods\core\sprites\ice.png', 'mods\core\sprites\glow.png', 'mods\core\sprites\nglow.png', 'mods\core\sprites\itemslot.png', 'mods\core\sprites\doll.png', 'mods\core\sprites\gold.png', 'mods\core\sprites\il.png', 'mods\core\sprites\backbar.png', 'mods\core\sprites\lifebar.png', 'mods\core\sprites\manabar.png', 'mods\core\sprites\close.png' ); procedure Load; implementation procedure Load; var I: TResEnum; J: TFontEnum; begin for I := Low(TResEnum) to High(TResEnum) do Resource[I] := LoadTexture(ResourcePath[I]); for J := Low(TFontEnum) to High(TFontEnum) do Font[J] := LoadFont(FontPath[J]); SetFrameSize(Resource[ttIL], 32, 32); end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: Helper routines for the MidWare sample client/server demo. Use Adaptive Huffman Coding (LZH) for data compression. The LZH routines are from the SWAG and adapted by various peoples. See lzh.pas unit for details. Creation: Mar 24, 1999 Version: 1.02 EMail: http://www.overbyte.be http://www.rtfm.be/fpiette francois.piette@overbyte.be francois.piette@rtfm.be Support: Unsupported code Legal issues: Copyright (C) 1999-2005 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@pophost.eunet.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software and or any derived or altered versions for any purpose, excluding commercial applications. You can use this software for personal or internal use only. You may distribute it freely untouched. The following restrictions applies: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation and displayed on screen is required. The text must be: "This product is based on MidWare. Freeware source code is available at http://www.overbyte.be." 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution and must be added to the product documentation. Updates: Nov 10, 2001 V1.01 Paolo Lanzoni <paolol@salsan.com> adapted to use LongWORD Aug 12, 2010 V1.02 F.Piette use AnsiChar instead of Char {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteCipherLz; interface uses OverbyteLzh, SysUtils; procedure Encrypt( Src1 : PAnsiChar; Src1Len : Integer; Src2 : PAnsiChar; Src2Len : Integer; var aDst : PAnsiChar; var aDstLen : Integer; Offset : Integer); procedure Decrypt( CmdBuf : PAnsiChar; CmdLen : Integer; var aDst : PAnsiChar; var aDstLen : Integer); implementation type TLZObject = class(TObject) private FSrc1 : PAnsiChar; FSrc1Len : Integer; FSrc2 : PAnsiChar; FSrc2Len : Integer; FDst : PAnsiChar; FDstLen : Integer; FRdPtr : Integer; FWrPtr : Integer; procedure EncryptGetBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); procedure EncryptPutBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); procedure DecryptGetBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); procedure DecryptPutBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TLZObject.EncryptGetBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); var P : PAnsiChar; begin // Data is split into two buffers, we must get data from the first // buffer and when exhausted, from the second buffer. // Buffers may be empty or not assigned if (FRdPtr < FSrc1Len) and (FSrc1Len > 0) and (FSrc1 <> nil) then begin P := FSrc1 + FrdPtr; Bytes_Got := FSrc1Len - FRdPtr; if Bytes_Got > NBytes then Bytes_Got := NBytes; end else begin if (FSrc2 = nil) or (FSrc2Len = 0) then begin P := nil; Bytes_Got := 0 end else begin P := FSrc2 + FRdPtr - FSrc1Len; Bytes_Got := FSrc2Len - (FRdPtr - FSrc1Len); end; if Bytes_Got > NBytes then Bytes_Got := NBytes; end; if Bytes_Got > 0 then Move(P^, DTA, Bytes_Got); Inc(FRdPtr, Bytes_Got); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TLZObject.EncryptPutBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); var Src : PAnsiChar; Dst : PAnsiChar; I : Integer; begin if NBytes <= 0 then Exit; Bytes_Got := NBytes; Src := @DTA; Dst := FDst + FWrPtr; for I := 0 to NBytes - 1 do begin Dst^ := Src^; Inc(Src); { We must escape some characters because they are used as } { delimiters in MidWare protocol } case Dst^ of #0: begin Dst^ := #4; Inc(Dst); Inc(FWrPtr); Dst^ := #7; end; #4: begin Dst^ := #4; Inc(Dst); Inc(FWrPtr); Dst^ := #4; end; #10: begin Dst^ := #4; Inc(Dst); Inc(FWrPtr); Dst^ := #6; end; #13: begin Dst^ := #4; Inc(Dst); Inc(FWrPtr); Dst^ := #5; end; end; Inc(Dst); Inc(FWrPtr); if FWrPtr > (FDstLen - 3) then begin // We need to enlarge the buffer. Add 1KB Inc(FDstLen, 1024); ReallocMem(FDst, FDstLen); Dst := FDst + FWrPtr; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Encrypt( Src1 : PAnsiChar; Src1Len : Integer; Src2 : PAnsiChar; Src2Len : Integer; var aDst : PAnsiChar; var aDstLen : Integer; Offset : Integer); var Lzh : TLZH; LzObject : TLZObject; Bytes_Written : LongInt; Buf : String; begin Lzh := TLzh.Create; try LzObject := TLZObject.Create; try LzObject.FSrc1 := Src1; LzObject.FSrc1Len := Src1Len; LzObject.FSrc2 := Src2; LzObject.FSrc2Len := Src2Len; // Create an output buffer LzObject.FDstLen := (((Src1Len + Src2Len) div 1024) + 1) * 1024; GetMem(LzObject.FDst, LzObject.FDstLen); // Reset pointers LzObject.FRdPtr := 0; LzObject.FWrPtr := Offset + 8; // Save length in destination Buf := IntToHex(Src1Len + Src2Len, 8); Move(Buf[1], LzObject.FDst[Offset], 8); Bytes_Written := 0; Lzh.LZHPack(Bytes_Written, LzObject.EncryptGetBytes, LzObject.EncryptPutBytes); aDst := LzObject.FDst; aDstLen := LzObject.FWrPtr; // Adjust buffer size ReallocMem(aDst, aDstLen); finally LzObject.Destroy; end; finally Lzh.Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TLzObject.DecryptGetBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); var Src : PAnsiChar; Dst : PAnsiChar; begin Bytes_Got := 0; Dst := @DTA; Src := FSrc1 + FRdPtr; while Bytes_Got < NBytes do begin if FRdPtr >= FSrc1Len then // No more data break; if Src^ <> #4 then Dst^ := Src^ else begin Inc(Src); Inc(FRdPtr); case Src^ of #4 : Dst^ := #4; #5 : Dst^ := #13; #6 : Dst^ := #10; #7 : Dst^ := #0; end; end; Inc(Dst); Inc(Src); Inc(FRdPtr); Inc(Bytes_Got); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TLzObject.DecryptPutBytes(var DTA; NBytes : WORD; var Bytes_Got : Longword); begin Bytes_Got := NBytes; if NBytes <= 0 then Exit; Move(DTA, FDst[FWrPtr], NBytes); Inc(FWrPtr, NBytes); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Decrypt( CmdBuf : PAnsiChar; CmdLen : Integer; var aDst : PAnsiChar; var aDstLen : Integer); var Lzh : TLZH; LzObject : TLZObject; I : Integer; Len : Integer; begin Lzh := TLzh.Create; try LzObject := TLZObject.Create; try // First 8 bytes are original data size in ascii-hex Len := 0; for I := 0 to 7 do begin if CmdBuf[I] in ['0'..'9'] then Len := (Len * 16) + Ord(Cmdbuf[I]) - Ord('0') else Len := (Len * 16) + (Ord(Cmdbuf[I]) and 15) + 9; end; LzObject.FSrc1 := CmdBuf + 8; LzObject.FSrc1Len := CmdLen - 8; LzObject.FDstLen := Len; LzObject.FRdPtr := 0; LzObject.FWrPtr := 0; GetMem(LzObject.FDst, LzObject.FDstLen); Lzh.LZHUnpack(LzObject.FDstLen, LzObject.DecryptGetBytes, LzObject.DecryptPutBytes); aDst := LzObject.FDst; aDstLen := LzObject.FDstLen; finally LzObject.Destroy; end; finally Lzh.Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit superbasketball_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,nz80,main_engine,controls_engine,sn_76496,vlm_5030,gfx_engine, dac,rom_engine,pal_engine,konami_decrypt,sound_engine,qsnapshot; function iniciar_sbasketb:boolean; implementation const sbasketb_rom:array[0..2] of tipo_roms=( (n:'405g05.14j';l:$2000;p:$6000;crc:$336dc0ab),(n:'405i03.11j';l:$4000;p:$8000;crc:$d33b82dd), (n:'405i01.9j';l:$4000;p:$c000;crc:$1c09cc3f)); sbasketb_char:tipo_roms=(n:'405e12.22f';l:$4000;p:0;crc:$e02c54da); sbasketb_sprites:array[0..2] of tipo_roms=( (n:'405h06.14g';l:$4000;p:0;crc:$cfbbff07),(n:'405h08.17g';l:$4000;p:$4000;crc:$c75901b6), (n:'405h10.20g';l:$4000;p:$8000;crc:$95bc5942)); sbasketb_pal:array[0..4] of tipo_roms=( (n:'405e17.5a';l:$100;p:$0;crc:$b4c36d57),(n:'405e16.4a';l:$100;p:$100;crc:$0b7b03b8), (n:'405e18.6a';l:$100;p:$200;crc:$9e533bad),(n:'405e20.19d';l:$100;p:$300;crc:$8ca6de2f), (n:'405e19.16d';l:$100;p:$400;crc:$e0bc782f)); sbasketb_vlm:tipo_roms=(n:'405e15.11f';l:$2000;p:$0;crc:$01bb5ce9); sbasketb_snd:tipo_roms=(n:'405e13.7a';l:$2000;p:$0;crc:$1ec7458b); sbasketb_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),()); sbasketb_dip_b:array [0..6] of def_dip=( (mask:$3;name:'Game Time';number:4;dip:((dip_val:$3;dip_name:'30'),(dip_val:$1;dip_name:'40'),(dip_val:$2;dip_name:'50'),(dip_val:$0;dip_name:'60'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Starting Score';number:2;dip:((dip_val:$8;dip_name:'70-78'),(dip_val:$0;dip_name:'100-115'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Ranking';number:2;dip:((dip_val:$0;dip_name:'Data Remaining'),(dip_val:$10;dip_name:'Data Initialized'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Medium'),(dip_val:$20;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var pedir_snd_irq,irq_ena:boolean; sound_latch,chip_latch,scroll_x,sbasketb_palettebank,sprite_select:byte; mem_opcodes:array[0..$9fff] of byte; last_addr:word; procedure update_video_sbasketb; var f,nchar,color,offset:word; x,y,atrib:byte; begin for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=31-(f div 32); y:=f mod 32; atrib:=memoria[$3000+f]; nchar:=memoria[$3400+f]+((atrib and $20) shl 3); color:=(atrib and $f) shl 4; put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $80)<>0,(atrib and $40)<>0); gfx[0].buffer[f]:=false; end; end; //La parte de arriba es fija... actualiza_trozo(0,0,256,48,1,0,0,256,48,2); scroll__x_part2(1,2,208,@scroll_x,0,0,48); offset:=sprite_select*$100; for f:=0 to $3f do begin atrib:=memoria[$3801+offset+(f*4)]; nchar:=memoria[$3800+offset+(f*4)]+((atrib and $20) shl 3); y:=memoria[$3802+offset+(f*4)]; x:=240-(memoria[$3803+offset+(f*4)]); color:=((atrib and $0f)+16*sbasketb_palettebank) shl 4; put_gfx_sprite(nchar,color,(atrib and $80)<>0,(atrib and $40)<>0,1); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(16,0,224,256,2); end; procedure eventos_sbasketb; begin if event.arcade then begin //P1 if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); //P2 if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40); //System if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2); end; end; procedure sbasketb_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; if f=239 then begin if irq_ena then m6809_0.change_irq(HOLD_LINE); update_video_sbasketb; end; end; //General eventos_sbasketb; video_sync; end; end; function sbasketb_getbyte(direccion:word):byte; begin case direccion of $2000..$3bff:sbasketb_getbyte:=memoria[direccion]; $3e00:sbasketb_getbyte:=marcade.in0; $3e01:sbasketb_getbyte:=marcade.in1; $3e02:sbasketb_getbyte:=marcade.in2; $3e80:sbasketb_getbyte:=marcade.dswb; $3f00:sbasketb_getbyte:=marcade.dswa; $6000..$ffff:if m6809_0.opcode then sbasketb_getbyte:=mem_opcodes[direccion-$6000] else sbasketb_getbyte:=memoria[direccion]; end; end; procedure sbasketb_putbyte(direccion:word;valor:byte); begin case direccion of $2000..$2fff,$3800..$3bff:memoria[direccion]:=valor; $3000..$37ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $3c20:sbasketb_palettebank:=valor; $3c80:main_screen.flip_main_screen:=(valor and $1)<>0; $3c81:irq_ena:=(valor<>0); $3c85:sprite_select:=valor and 1; $3d00:sound_latch:=valor; $3d80:z80_0.change_irq(HOLD_LINE); $3f80:scroll_x:=not(valor); $6000..$ffff:; //ROM end; end; function sbasketb_snd_getbyte(direccion:word):byte; begin case direccion of 0..$1fff,$4000..$43ff:sbasketb_snd_getbyte:=mem_snd[direccion]; $6000:sbasketb_snd_getbyte:=sound_latch; $8000:sbasketb_snd_getbyte:=((z80_0.totalt shr 10) and $3) or ((vlm5030_0.get_bsy and 1) shl 2); end; end; procedure sbasketb_snd_putbyte(direccion:word;valor:byte); var changes,offset:word; begin case direccion of 0..$1fff:; //ROM $4000..$43ff:mem_snd[direccion]:=valor; $a000:vlm5030_0.data_w(valor); $c000..$dfff:begin offset:=direccion and $1fff; changes:=offset xor last_addr; // A4 VLM5030 ST pin if (changes and $10)<>0 then vlm5030_0.set_st((offset and $10) shr 4); // A5 VLM5030 RST pin if (changes and $20)<>0 then vlm5030_0.set_rst((offset and $20) shr 5); last_addr:=offset; end; $e000:dac_0.data8_w(valor); $e001:chip_latch:=valor; $e002:sn_76496_0.Write(chip_latch); end; end; procedure sbasketb_sound_update; begin sn_76496_0.Update; dac_0.update; vlm5030_0.update; end; procedure sbasketb_qsave(nombre:string); var data:pbyte; buffer:array[0..8] of byte; size:word; begin open_qsnapshot_save('sbasketb'+nombre); getmem(data,250); //CPU size:=m6809_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=sn_76496_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=vlm5030_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=dac_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria,$6000); savedata_com_qsnapshot(@mem_snd[$2000],$e000); //MISC buffer[0]:=byte(pedir_snd_irq); buffer[1]:=byte(irq_ena); buffer[2]:=sound_latch; buffer[3]:=chip_latch; buffer[4]:=scroll_x; buffer[5]:=sbasketb_palettebank; buffer[6]:=sprite_select; buffer[7]:=last_addr and $ff; buffer[8]:=last_addr shr 8; savedata_qsnapshot(@buffer,9); freemem(data); close_qsnapshot; end; procedure sbasketb_qload(nombre:string); var data:pbyte; buffer:array[0..8] of byte; begin if not(open_qsnapshot_load('sbasketb'+nombre)) then exit; getmem(data,250); //CPU loaddata_qsnapshot(data); m6809_0.load_snapshot(data); loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); sn_76496_0.load_snapshot(data); loaddata_qsnapshot(data); vlm5030_0.load_snapshot(data); loaddata_qsnapshot(data); dac_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria); loaddata_qsnapshot(@mem_snd[$2000]); //MISC loaddata_qsnapshot(@buffer); pedir_snd_irq:=buffer[0]<>0; irq_ena:=buffer[1]<>0; sound_latch:=buffer[2]; chip_latch:=buffer[3]; scroll_x:=buffer[4]; sbasketb_palettebank:=buffer[5]; sprite_select:=buffer[6]; last_addr:=buffer[7] or (buffer[8] shl 8); freemem(data); close_qsnapshot; //END fillchar(gfx[0].buffer,$400,1); end; //Main procedure reset_sbasketb; begin m6809_0.reset; z80_0.reset; vlm5030_0.reset; dac_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; pedir_snd_irq:=false; irq_ena:=false; sound_latch:=0; chip_latch:=0; scroll_x:=0; sbasketb_palettebank:=0; sprite_select:=0; last_addr:=0; end; function iniciar_sbasketb:boolean; var colores:tpaleta; f,j:byte; memoria_temp:array[0..$bfff] of byte; const pc_y:array[0..7] of dword=(0*4*8, 1*4*8, 2*4*8, 3*4*8, 4*4*8, 5*4*8, 6*4*8, 7*4*8); ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 8*4, 9*4, 10*4, 11*4, 12*4, 13*4, 14*4, 15*4); ps_y:array[0..15] of dword=(0*4*16, 1*4*16, 2*4*16, 3*4*16, 4*4*16, 5*4*16, 6*4*16, 7*4*16, 8*4*16, 9*4*16, 10*4*16, 11*4*16, 12*4*16, 13*4*16, 14*4*16, 15*4*16); begin llamadas_maquina.bucle_general:=sbasketb_principal; llamadas_maquina.reset:=reset_sbasketb; llamadas_maquina.save_qsnap:=sbasketb_qsave; llamadas_maquina.load_qsnap:=sbasketb_qload; iniciar_sbasketb:=false; iniciar_audio(false); screen_init(1,256,256); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,false,true); iniciar_video(224,256); //Main CPU m6809_0:=cpu_m6809.Create(1400000,$100,TCPU_MC6809E); m6809_0.change_ram_calls(sbasketb_getbyte,sbasketb_putbyte); //Sound CPU z80_0:=cpu_z80.create(3579545,$100); z80_0.change_ram_calls(sbasketb_snd_getbyte,sbasketb_snd_putbyte); z80_0.init_sound(sbasketb_sound_update); //Sound Chip sn_76496_0:=sn76496_chip.Create(1789772); vlm5030_0:=vlm5030_chip.Create(3579545,$2000,4); if not(roms_load(vlm5030_0.get_rom_addr,sbasketb_vlm)) then exit; dac_0:=dac_chip.Create(0.80); //cargar roms if not(roms_load(@memoria,sbasketb_rom)) then exit; konami1_decode(@memoria[$6000],@mem_opcodes,$a000); //cargar snd roms if not(roms_load(@mem_snd,sbasketb_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,sbasketb_char)) then exit; init_gfx(0,8,8,512); gfx_set_desc_data(4,0,8*4*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@ps_x,@pc_y,true,false); //sprites if not(roms_load(@memoria_temp,sbasketb_sprites)) then exit; init_gfx(1,16,16,384); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,32*4*8,0,1,2,3); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false); //paleta if not(roms_load(@memoria_temp,sbasketb_pal)) then exit; for f:=0 to $ff do begin colores[f].r:=((memoria_temp[f] and $f) shl 4) or (memoria_temp[f] and $f); colores[f].g:=((memoria_temp[f+$100] and $f) shl 4) or (memoria_temp[f+$100] shr 4); colores[f].b:=((memoria_temp[f+$200] and $f) shl 4) or (memoria_temp[f+$200] and $f); end; set_pal(colores,256); for f:=0 to $ff do begin gfx[0].colores[f]:=(memoria_temp[$300+f] and $f) or $f0; for j:=0 to $f do gfx[1].colores[(j shl 8) or f]:=((j shl 4) or (memoria_temp[f + $400] and $0f)); end; //DIP marcade.dswa:=$ff; marcade.dswb:=$68; marcade.dswa_val:=@sbasketb_dip_a; marcade.dswb_val:=@sbasketb_dip_b; //final reset_sbasketb; iniciar_sbasketb:=true; end; end.
unit SoundCache; interface const cMaxSoundCacheSize = 50; type TSoundSource = (ssDiskFile, ssResource); type TCachedSoundInfo = record Name : string; Ticks : integer; end; type TSoundCache = class private fSoundCount : integer; fSounds : array [0..pred(cMaxSoundCacheSize)] of TCachedSoundInfo; public destructor Destroy; override; public function GetSound(const Name : string; Source : TSoundSource) : boolean; procedure Clear; end; implementation uses Windows, SoundLib; destructor TSoundCache.Destroy; begin inherited; end; function TSoundCache.GetSound(const Name : string; Source : TSoundSource) : boolean; function FindVictim : integer; var i : integer; mintick : integer; victim : integer; begin victim := 0; mintick := fSounds[0].Ticks; for i := 1 to pred(fSoundCount) do if fSounds[i].Ticks < mintick then begin mintick := fSounds[i].Ticks; victim := i; end; UnloadSound(fSounds[victim].Name); Result := victim; end; var i : integer; loaded : boolean; begin i := 0; loaded := false; while (i < fSoundCount) and not loaded do begin loaded := fSounds[i].Name = Name; if not loaded then inc(i); end; if not loaded then begin case Source of ssDiskFile: loaded := LoadSoundFromFile(Name); ssResource: loaded := LoadSoundFromResName(Name); end; if loaded then begin if i < cMaxSoundCacheSize then inc(fSoundCount) else i := FindVictim; fSounds[i].Name := Name; fSounds[i].Ticks := GetTickCount; end; end; Result := loaded; end; procedure TSoundCache.Clear; begin fSoundCount := 0; end; end.
unit AdoConec; interface uses Windows, Messages, classes, Forms, Dialogs, ADODB, DB, IniFiles, SysUtils, dmasientos; const ctdatosconec = 'Provider=SQLOLEDB.1;Persist Security Info=True;'; ctCatalogo = 'Initial Catalog='; ctDataSource = ';Data Source='; // ctUser='sa'; ctdatosconecAzu = 'Provider=MSDASQL.1;'; function conectar( ado: TAdoConnection; negro: boolean= false ): boolean; function vieja_coneccion( ado: TAdoConnection; negro: boolean= false ): boolean; function nueva_coneccion( ado: TAdoConnection; negro: boolean= false ): boolean; function get_base: string; procedure SetConeccionAsientos( ado: TAdoConnection ); var ctPassword: string; ctUser: string; BaseDeDatos: string; implementation function get_base: string; begin result := BaseDeDatos; end; function conectar(ado: TAdoConnection; negro: boolean= false ): boolean; begin result := nueva_coneccion(ado, negro); end; function vieja_coneccion( ado: TAdoConnection; negro: boolean ): boolean; var FIni: TIniFile; f, Base, BaseX, DataS: string; bAzure, datosConec: string; begin FIni := TIniFile.Create( ExtractFilePath( application.ExeName ) + 'Conf\bdatos.ini' ); try BaseX := FIni.ReadString('BDATOS', 'SISNOBX', 'SISNOBX'); if ( ParamCount > 1) then Base := ParamStr(2) else Base := FIni.ReadString('ULTIMA', 'ULTIMA', 'SISNOB' ); DataS := FIni.ReadString('BDATOS', Base, 'SQL\SQLEXPRESS' ); // ShowMessage(Base + #13 + DataS); bAzure := FIni.ReadString('AZURE', Base, '0' ); if (bAzure='1') then begin ctUser := FIni.ReadString('AZURE', 'USUARIO', 'sisnob' ); ctPassword := FIni.ReadString('AZURE', 'PASSWORD', 'Kazaztan' ); datosConec := ctdatosconecAzu; end else begin ctUser := FIni.ReadString('USER', 'USUARIO', 'sisnob' ); ctPassword := FIni.ReadString('USER', 'PASSWORD', 'kazaztan' ); datosConec := ctdatosconec; end; FIni.Free; if negro then f := BaseX else f := Base; if Ado.Connected then Ado.Connected := false; // codesite.Send( 'preparando coneccion' ); Ado.ConnectionString := datosconec + ctCatalogo + f + ctDataSource + DataS + ';User ID=' + ctUser + ';Password=' + ctPassword; // showmessage( Ado.ConnectionString ); Ado.Connected := true; // codesite.Send( 'conectado' ); Result := true; except on e:exception do begin showmessage( ado.connectionstring + #13 +'Error en coneccion a base de datos' + #13 + e.Message ); Result := false; end; end; end; function nueva_coneccion( ado: TAdoConnection; negro: boolean= false ): boolean; var Ruta: string; FSer, FUsu, FBase, FCat, FCla, FCadena: string; FPos: integer; FIni: TIniFile; FLista: TStringlist; begin FLista := TStringlist.Create; try FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'Conf\coneccion.ini' ); FIni.ReadSections(FLista); if ( ParamCount > 1) then FCat := ParamStr(2) else if FLista.Count > 0 then FCat := FLista[0] else begin PostMessage( Application.Handle, WM_CLOSE, 0, 0 ); Exit; end; FBase := FIni.ReadString(FCat, 'Base', '' ); FSer := FIni.ReadString(FCat, 'Servidor', '' ); FCla := FIni.ReadString(FCat, 'clave', '' ); FUsu := FIni.ReadString(FCat, 'Usuario', '' ); FCadena := FIni.ReadString(FCat, 'cadena', '' ); FCadena := StringReplace(FCadena, '{app}', extractfilepath(application.ExeName), [rfReplaceAll]); BaseDeDatos := FBase; FCadena := FCadena + 'User ID=%s;Password=%s;Initial Catalog=%s;Data Source=%s;'; if Ado.Connected then Ado.Connected := false; Ado.ConnectionString := Format( FCadena, [FUsu, FCla, FBase, FSer ]); // showmessage( Ado.ConnectionString ); try Ado.Connected := true; Result := true; // pasar la nueva coneccion a DmAsientos... SetConeccionAsientos( ado ); except on e:exception do begin showmessage( ado.connectionstring + #13 +'Error en coneccion a base de datos' + #13 + e.Message ); Result := false; end; end; if not ( Ado.Connected) then PostMessage( Application.Handle, WM_CLOSE, 0, 0 ); finally FLista.free; FIni.free; end; end; procedure SetConeccionAsientos( ado: TAdoConnection ); begin if not Assigned( FDataModulo) then FDataModulo := TFDataModulo.create( application ); FdataModulo.setearOficial(ado); end; end.